aperturedb

package
v0.0.0-...-56940a3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 4, 2024 License: GPL-3.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultStoreTimeout is the default timeout used for any interaction
	// with the storage/database.
	DefaultStoreTimeout = time.Second * 10

	// DefaultNumTxRetries is the default number of times we'll retry a
	// transaction if it fails with an error that permits transaction
	// repetition.
	DefaultNumTxRetries = 10

	// DefaultRetryDelay is the default delay between retries. This will be
	// used to generate a random delay between 0 and this value.
	DefaultRetryDelay = time.Millisecond * 50
)
View Source
const (
	PostgresTag = "11"
)
View Source
const Subsystem = "APDB"

Subsystem defines the logging code for this subsystem.

Variables

View Source
var (
	// DefaultPostgresFixtureLifetime is the default maximum time a Postgres
	// test fixture is being kept alive. After that time the docker
	// container will be terminated forcefully, even if the tests aren't
	// fully executed yet. So this time needs to be chosen correctly to be
	// longer than the longest expected individual test run time.
	DefaultPostgresFixtureLifetime = 10 * time.Minute
)
View Source
var (
	// ErrRetriesExceeded is returned when a transaction is retried more
	// than the max allowed valued without a success.
	ErrRetriesExceeded = errors.New("db tx retries exceeded")
)

Functions

func MapSQLError

func MapSQLError(err error) error

MapSQLError attempts to interpret a given error as a database agnostic SQL error.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

Types

type BaseDB

type BaseDB struct {
	*sql.DB

	*sqlc.Queries
}

BaseDB is the base database struct that each implementation can embed to gain some common functionality.

func (*BaseDB) BeginTx

func (s *BaseDB) BeginTx(ctx context.Context, opts TxOptions) (*sql.Tx, error)

BeginTx wraps the normal sql specific BeginTx method with the TxOptions interface. This interface is then mapped to the concrete sql tx options struct.

type BatchedLNCSessionsDB

type BatchedLNCSessionsDB interface {
	LNCSessionsDB

	BatchedTx[LNCSessionsDB]
}

BatchedLNCSessionsDB is a version of the LNCSecretsDB that's capable of batched database operations.

type BatchedOnionDB

type BatchedOnionDB interface {
	OnionDB

	BatchedTx[OnionDB]
}

BatchedOnionDB is a version of the OnionDB that's capable of batched database operations.

type BatchedQuerier

type BatchedQuerier interface {
	// Querier is the underlying query source, this is in place so we can
	// pass a BatchedQuerier implementation directly into objects that
	// create a batched version of the normal methods they need.
	sqlc.Querier

	// BeginTx creates a new database transaction given the set of
	// transaction options.
	BeginTx(ctx context.Context, options TxOptions) (*sql.Tx, error)
}

BatchedQuerier is a generic interface that allows callers to create a new database transaction based on an abstract type that implements the TxOptions interface.

type BatchedSecretsDB

type BatchedSecretsDB interface {
	SecretsDB

	BatchedTx[SecretsDB]
}

BatchedSecretsDB is a version of the SecretsDB that's capable of batched database operations.

type BatchedTx

type BatchedTx[Q any] interface {
	// ExecTx will execute the passed txBody, operating upon generic
	// parameter Q (usually a storage interface) in a single transaction.
	// The set of TxOptions are passed in in order to allow the caller to
	// specify if a transaction should be read-only and optionally what
	// type of concurrency control should be used.
	ExecTx(ctx context.Context, txOptions TxOptions,
		txBody func(Q) error) error
}

BatchedTx is a generic interface that represents the ability to execute several operations to a given storage interface in a single atomic transaction. Typically, Q here will be some subset of the main sqlc.Querier interface allowing it to only depend on the routines it needs to implement any additional business logic.

type ErrSQLUniqueConstraintViolation

type ErrSQLUniqueConstraintViolation struct {
	DBError error
}

ErrSQLUniqueConstraintViolation is an error type which represents a database agnostic SQL unique constraint violation.

func (ErrSQLUniqueConstraintViolation) Error

Error returns the error message.

type ErrSerializationError

type ErrSerializationError struct {
	DBError error
}

ErrSerializationError is an error type which represents a database agnostic error that a transaction couldn't be serialized with other concurrent db transactions.

func (ErrSerializationError) Error

func (e ErrSerializationError) Error() string

Error returns the error message.

func (ErrSerializationError) Unwrap

func (e ErrSerializationError) Unwrap() error

Unwrap returns the wrapped error.

type LNCSessionsDB

type LNCSessionsDB interface {
	// InsertLNCSession inserts a new session into the database.
	InsertSession(ctx context.Context, arg NewLNCSession) error

	// GetLNCSession returns the session tagged with the given passphrase
	// entropy.
	GetSession(ctx context.Context,
		passphraseEntropy []byte) (sqlc.LncSession, error)

	// SetRemotePubKey sets the remote public key for the session.
	SetRemotePubKey(ctx context.Context,
		arg SetRemoteParams) error

	// SetExpiry sets the expiry for the session.
	SetExpiry(ctx context.Context, arg SetExpiryParams) error
}

LNCSessionsDB is an interface that defines the set of operations that can be executed agaist the lnc sessions database.

type LNCSessionsDBTxOptions

type LNCSessionsDBTxOptions struct {
	// contains filtered or unexported fields
}

LNCSessionsDBTxOptions defines the set of db txn options the LNCSessionsDB understands.

func NewLNCSessionsDBReadTx

func NewLNCSessionsDBReadTx() LNCSessionsDBTxOptions

NewLNCSessionsDBReadTx creates a new read transaction option set.

func (*LNCSessionsDBTxOptions) ReadOnly

func (a *LNCSessionsDBTxOptions) ReadOnly() bool

ReadOnly returns true if the transaction should be read only.

NOTE: This implements the TxOptions

type LNCSessionsStore

type LNCSessionsStore struct {
	// contains filtered or unexported fields
}

LNCSessionsStore represents a storage backend.

func NewLNCSessionsStore

func NewLNCSessionsStore(db BatchedLNCSessionsDB) *LNCSessionsStore

NewSecretsStore creates a new SecretsStore instance given a open BatchedSecretsDB storage backend.

func (*LNCSessionsStore) AddSession

func (l *LNCSessionsStore) AddSession(ctx context.Context,
	session *lnc.Session) error

AddSession adds a new session to the database.

func (*LNCSessionsStore) GetSession

func (l *LNCSessionsStore) GetSession(ctx context.Context,
	passphraseEntropy []byte) (*lnc.Session, error)

GetSession returns the session tagged with the given label.

func (*LNCSessionsStore) SetExpiry

func (l *LNCSessionsStore) SetExpiry(ctx context.Context,
	passphraseEntropy []byte, expiry time.Time) error

SetExpiry sets the expiry time for a session.

func (*LNCSessionsStore) SetRemotePubKey

func (l *LNCSessionsStore) SetRemotePubKey(ctx context.Context,
	passphraseEntropy, remotePubKey []byte) error

SetRemotePubKey sets the remote public key for a session.

type NewLNCSession

type NewLNCSession = sqlc.InsertSessionParams

type NewOnionPrivateKey

type NewOnionPrivateKey = sqlc.UpsertOnionParams

type NewSecret

type NewSecret = sqlc.InsertSecretParams

NewSecret is a struct that contains the parameters required to insert a new secret into the database.

type NullTime

type NullTime = sql.NullTime

type OnionDB

type OnionDB interface {
	// UpsertOnion inserts a new onion private key into the database. If
	// the onion private key already exists in the db this is a NOOP
	// operation.
	UpsertOnion(ctx context.Context, arg NewOnionPrivateKey) error

	// SelectOnionPrivateKey selects the onion private key from the
	// database.
	SelectOnionPrivateKey(ctx context.Context) ([]byte, error)

	// DeleteOnionPrivateKey deletes the onion private key from the
	// database.
	DeleteOnionPrivateKey(ctx context.Context) error
}

OnionDB is an interface that defines the set of operations that can be executed against the onion database.

type OnionDBTxOptions

type OnionDBTxOptions struct {
	// contains filtered or unexported fields
}

OnionTxOptions defines the set of db txn options the OnionStore understands.

func NewOnionDBReadTx

func NewOnionDBReadTx() OnionDBTxOptions

NewOnionDBReadTx creates a new read transaction option set.

func (*OnionDBTxOptions) ReadOnly

func (a *OnionDBTxOptions) ReadOnly() bool

ReadOnly returns true if the transaction should be read only.

NOTE: This implements the TxOptions

type OnionStore

type OnionStore struct {
	// contains filtered or unexported fields
}

OnionStore represents a storage backend.

func NewOnionStore

func NewOnionStore(db BatchedOnionDB) *OnionStore

NewOnionStore creates a new OnionStore instance given a open BatchedOnionDB storage backend.

func (*OnionStore) DeletePrivateKey

func (o *OnionStore) DeletePrivateKey() error

DeletePrivateKey securely removes the private key from the store.

func (*OnionStore) PrivateKey

func (o *OnionStore) PrivateKey() ([]byte, error)

PrivateKey retrieves a stored private key. If it is not found, then ErrNoPrivateKey should be returned.

func (*OnionStore) StorePrivateKey

func (o *OnionStore) StorePrivateKey(privateKey []byte) error

StorePrivateKey stores the private key according to the implementation of the OnionStore interface.

type PostgresConfig

type PostgresConfig struct {
	SkipMigrations     bool   `long:"skipmigrations" description:"Skip applying migrations on startup."`
	Host               string `long:"host" description:"Database server hostname."`
	Port               int    `long:"port" description:"Database server port."`
	User               string `long:"user" description:"Database user."`
	Password           string `long:"password" description:"Database user's password."`
	DBName             string `long:"dbname" description:"Database name to use."`
	MaxOpenConnections int32  `long:"maxconnections" description:"Max open connections to keep alive to the database server."`
	RequireSSL         bool   `long:"requiressl" description:"Whether to require using SSL (mode: require) when connecting to the server."`
}

PostgresConfig holds the postgres database configuration.

func (*PostgresConfig) DSN

func (s *PostgresConfig) DSN(hidePassword bool) string

DSN returns the dns to connect to the database.

type PostgresStore

type PostgresStore struct {
	*BaseDB
	// contains filtered or unexported fields
}

PostgresStore is a database store implementation that uses a Postgres backend.

func NewPostgresStore

func NewPostgresStore(cfg *PostgresConfig) (*PostgresStore, error)

NewPostgresStore creates a new store that is backed by a Postgres database backend.

func NewTestPostgresDB

func NewTestPostgresDB(t *testing.T) *PostgresStore

NewTestPostgresDB is a helper function that creates a Postgres database for testing.

type QueryCreator

type QueryCreator[Q any] func(*sql.Tx) Q

QueryCreator is a generic function that's used to create a Querier, which is a type of interface that implements storage related methods from a database transaction. This will be used to instantiate an object callers can use to apply multiple modifications to an object interface in a single atomic transaction.

type SecretsDB

type SecretsDB interface {
	// InsertSecret inserts a new secret into the database.
	InsertSecret(ctx context.Context, arg NewSecret) (int32, error)

	// SetSettledTime sets the settled_at that corresponds to the given hash.
	SetSettledAtByPaymentHash(ctx context.Context, arg SetSettledAtByPaymentHashParams) error

	// GetSecretByIdHash returns the secret that corresponds to the given hash.
	GetSecretByIdHash(ctx context.Context, idHash []byte) ([]byte, error)

	// GetSettledAtByPaymentHash returns the settled_at that corresponds to the given
	// hash.
	GetSettledAtByPaymentHash(ctx context.Context, paymentHash []byte) (NullTime, error)

	// DeleteSecretByIdHash removes the secret that corresponds to the given
	// hash.
	DeleteSecretByIdHash(ctx context.Context, idHash []byte) (int64, error)
}

SecretsDB is an interface that defines the set of operations that can be executed against the secrets database.

type SecretsDBTxOptions

type SecretsDBTxOptions struct {
	// contains filtered or unexported fields
}

SecretsTxOptions defines the set of db txn options the SecretsStore understands.

func NewSecretsDBReadTx

func NewSecretsDBReadTx() SecretsDBTxOptions

NewSecretsDBReadTx creates a new read transaction option set.

func (*SecretsDBTxOptions) ReadOnly

func (a *SecretsDBTxOptions) ReadOnly() bool

ReadOnly returns true if the transaction should be read only.

NOTE: This implements the TxOptions

type SecretsStore

type SecretsStore struct {
	// contains filtered or unexported fields
}

SecretsStore represents a storage backend.

func NewSecretsStore

func NewSecretsStore(db BatchedSecretsDB) *SecretsStore

NewSecretsStore creates a new SecretsStore instance given a open BatchedSecretsDB storage backend.

func (*SecretsStore) GetSecret

func (s *SecretsStore) GetSecret(ctx context.Context,
	idHash [sha256.Size]byte) ([lsat.SecretSize]byte, error)

GetSecret returns the cryptographically random secret that corresponds to the given hash. If there is no secret, then ErrSecretNotFound is returned.

func (*SecretsStore) GetSettledAtByPaymentHash

func (s *SecretsStore) GetSettledAtByPaymentHash(ctx context.Context,
	paymentHash [sha256.Size]byte) (NullTime, error)

GetSettledAtByPaymentHash returns the settled_at time for the secret that corresponds to the given hash.

func (*SecretsStore) NewSecret

func (s *SecretsStore) NewSecret(ctx context.Context,
	idHash [sha256.Size]byte, paymentHash [sha256.Size]byte) ([lsat.SecretSize]byte, error)

NewSecret creates a new cryptographically random secret which is keyed by the given hash.

func (*SecretsStore) RevokeSecret

func (s *SecretsStore) RevokeSecret(ctx context.Context,
	idHash [sha256.Size]byte) error

RevokeSecret removes the cryptographically random secret that corresponds to the given hash. This acts as a NOP if the secret does not exist.

func (*SecretsStore) SetSettledAtByPaymentHash

func (s *SecretsStore) SetSettledAtByPaymentHash(ctx context.Context,
	paymentHash [sha256.Size]byte, settledAt NullTime) error

SetSettledAtByPaymentHash sets the settled_at time for the secret that corresponds to the given hash.

type SetExpiryParams

type SetExpiryParams = sqlc.SetExpiryParams

type SetRemoteParams

type SetRemoteParams = sqlc.SetRemotePubKeyParams

type SetSettledAtByPaymentHashParams

type SetSettledAtByPaymentHashParams = sqlc.SetSettledAtByPaymentHashParams

type TestPgFixture

type TestPgFixture struct {
	// contains filtered or unexported fields
}

TestPgFixture is a test fixture that starts a Postgres 11 instance in a docker container.

func NewTestPgFixture

func NewTestPgFixture(t *testing.T, expiry time.Duration) *TestPgFixture

NewTestPgFixture constructs a new TestPgFixture starting up a docker container running Postgres 11. The started container will expire in after the passed duration.

func (*TestPgFixture) ClearDB

func (f *TestPgFixture) ClearDB(t *testing.T)

ClearDB clears the database.

func (*TestPgFixture) GetConfig

func (f *TestPgFixture) GetConfig() *PostgresConfig

GetConfig returns the full config of the Postgres node.

func (*TestPgFixture) GetDSN

func (f *TestPgFixture) GetDSN() string

GetDSN returns the DSN (Data Source Name) for the started Postgres node.

func (*TestPgFixture) TearDown

func (f *TestPgFixture) TearDown(t *testing.T)

TearDown stops the underlying docker container.

type TransactionExecutor

type TransactionExecutor[Query any] struct {
	BatchedQuerier
	// contains filtered or unexported fields
}

TransactionExecutor is a generic struct that abstracts away from the type of query a type needs to run under a database transaction, and also the set of options for that transaction. The QueryCreator is used to create a query given a database transaction created by the BatchedQuerier.

func NewTransactionExecutor

func NewTransactionExecutor[Querier any](db BatchedQuerier,
	createQuery QueryCreator[Querier],
	opts ...TxExecutorOption) *TransactionExecutor[Querier]

NewTransactionExecutor creates a new instance of a TransactionExecutor given a Querier query object and a concrete type for the type of transactions the Querier understands.

func (*TransactionExecutor[Q]) ExecTx

func (t *TransactionExecutor[Q]) ExecTx(ctx context.Context,
	txOptions TxOptions, txBody func(Q) error) error

ExecTx is a wrapper for txBody to abstract the creation and commit of a db transaction. The db transaction is embedded in a `*Queries` that txBody needs to use when executing each one of the queries that need to be applied atomically. This can be used by other storage interfaces to parameterize the type of query and options run, in order to have access to batched operations related to a storage object.

type Tx

type Tx interface {
	// Commit commits the database transaction, an error should be returned
	// if the commit isn't possible.
	Commit() error

	// Rollback rolls back an incomplete database transaction.
	// Transactions that were able to be committed can still call this as a
	// noop.
	Rollback() error
}

Tx represents a database transaction that can be committed or rolled back.

type TxExecutorOption

type TxExecutorOption func(*txExecutorOptions)

TxExecutorOption is a functional option that allows us to pass in optional argument when creating the executor.

func WithTxRetries

func WithTxRetries(numRetries int) TxExecutorOption

WithTxRetries is a functional option that allows us to specify the number of times a transaction should be retried if it fails with a repeatable error.

func WithTxRetryDelay

func WithTxRetryDelay(delay time.Duration) TxExecutorOption

WithTxRetryDelay is a functional option that allows us to specify the delay to wait before a transaction is retried.

type TxOptions

type TxOptions interface {
	// ReadOnly returns true if the transaction should be read only.
	ReadOnly() bool
}

TxOptions represents a set of options one can use to control what type of database transaction is created. Transaction can wither be read or write.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL