Documentation
¶
Overview ¶
Package db holds the database connections (ADR-0006): the main pool, for every query, and the session connection, for what needs a real session — the migration lock here, the Leader lock and LISTEN later. It runs the startup checks of C-02.FR-5 and FR-14 and the embedded migrations.
Index ¶
- Constants
- func Backoff(failures int, base, limit time.Duration, random func() float64) time.Duration
- func CheckSession(ctx context.Context, session sessionConn, notifier querier) error
- func CheckVersion(ctx context.Context, q querier) error
- func Claim[T any](ctx context.Context, b Beginner, l Lease, limit int32, ...) ([]T, error)
- func Encrypted(ctx context.Context, q querier) (bool, error)
- func Held(until, now time.Time) bool
- func KnownVersion() (uint, error)
- func NotifyHint(ctx context.Context, e Execer, h Hint) error
- func ReportSecurity(ctx context.Context, log *logging.Logger, connection, sslMode string, ...)
- type Beginner
- type ClaimParams
- type DB
- func (d *DB) Check(ctx context.Context, log *logging.Logger) error
- func (d *DB) CheckSchema(ctx context.Context, log *logging.Logger) error
- func (d *DB) Close()
- func (d *DB) ConnectSession(ctx context.Context) (*pgx.Conn, error)
- func (d *DB) Migrate(ctx context.Context, log *logging.Logger) error
- func (d *DB) Ping(ctx context.Context) error
- func (d *DB) RegisterMetrics()
- func (d *DB) SessionListenConn(ctx context.Context) (ListenConn, error)
- func (d *DB) WithMigrationLock(ctx context.Context, f func(context.Context) error) error
- type Execer
- type Hint
- type Lease
- type ListenConn
- type Listener
- type Poller
- type PoolerError
- type SchemaError
Constants ¶
const ( ConnectionMain = "main" ConnectionSession = "session" )
The names of the two connections in log lines.
const AccountLinkCodeTargetLockClass int32 = 0x6d75_0005
AccountLinkCodeTargetLockClass is the first key of the transaction advisory lock of the Mattermost code requests for one account of a Connection, whose second key is hashtext of the Organization, the Connection and the account: a code request holds it while it counts the account's requests of the last hour and stores its own (account_link.mattermost_code_requests).
const HintChannel = "muster_hints"
HintChannel is the LISTEN/NOTIFY channel of the live-update hints (ADR-0009): writers send a Hint in the transaction of their change, and every replica's Listener receives it once the transaction commits.
const ( // MigrationLockKey is taken around migrations and, from S-007 on, the start-up steps that create the first data. MigrationLockKey int64 = 0x6d75_7374_6572_0001 )
The advisory lock keys of Muster, one per use; each is a constant so that every replica takes the same lock.
const ( // MinPoolConns is the smallest default of the main pool (pool_max_conns of MUSTER_DATABASE_URL, P-50): the // pool opens max(MinPoolConns, CPUs) connections unless the main connection's URL sets pool_max_conns. pgx's own // default of max(4, CPUs) left four connections on a 4-CPU node, too few for processing, delivery and ingestion // together under the NFR-1 load. MinPoolConns = 10 )
const ( // MinServerVersion is PostgreSQL 14, the first with idle_session_timeout, which the Leader lease relies on // (ADR-0006, ADR-0007). MinServerVersion = 140000 )
const RouteMembershipLockClass int32 = 0x6d75_0002
RouteMembershipLockClass is the first key of the transaction advisory locks of the Destinations of a Route, whose second key is hashint8 of the Route's id: a change of its Destinations takes it exclusively (routing), an Enqueue on the Route shared (delivery). The two-key advisory locks do not overlap the one-key locks above.
const TelegramUpdateLockClass int32 = 0x6d75_0004
TelegramUpdateLockClass is the first key of the transaction advisory lock of a Telegram Connection's updates, whose second key is hashint8 of the Connection's id: the update router holds it while a handler runs, so that a second poller or a webhook request with the same update waits and then skips it, and the delivery worker tries it shared, without waiting, before an edit of a Root message of the Connection. The class 0x6d75_0003 is delivery's lock of a channel post's copy.
Variables ¶
This section is empty.
Functions ¶
func Backoff ¶
Backoff is the wait after failures consecutive failed rounds: exponential from base, at most limit, with full jitter (a uniform share of the bound that random, in [0, 1), picks), and never below base/2, so that replicas that failed together do not retry together and none spins.
func CheckSession ¶
CheckSession takes and releases a session advisory lock on session, then completes a LISTEN/NOTIFY round trip: session listens and notifier, another connection, notifies. It fails with a PoolerError when either does not work within five seconds. PgBouncer has no SQL that reports its pool mode, so the check is functional.
func CheckVersion ¶
CheckVersion refuses a PostgreSQL older than MinServerVersion.
func Claim ¶
func Claim[T any](ctx context.Context, b Beginner, l Lease, limit int32, claim func(ctx context.Context, tx pgx.Tx, p ClaimParams) ([]T, error)) ([]T, error)
Claim runs claim in one short transaction with the values of l for at most limit rows and returns the rows it claimed; they are committed, and so leased, when Claim returns. claim selects the due rows FOR UPDATE SKIP LOCKED and sets their lease, so that two claimers never take the same row.
func KnownVersion ¶
KnownVersion is the version of the newest embedded migration.
func NotifyHint ¶
NotifyHint sends h on HintChannel through e. Sent inside a transaction, it reaches the listeners only when the transaction commits, and not at all when it rolls back.
Types ¶
type ClaimParams ¶
type ClaimParams struct {
Owner string
Due time.Time
Now time.Time
LeaseUntil time.Time
Limit int32
}
ClaimParams are the values one claim compares and sets: rows due at or before Due (business clock) whose lease is free or ran out at or before Now (real clock) get Owner and LeaseUntil, at most Limit of them.
type DB ¶
DB is the main pool and the settings of the session connection.
func Open ¶
Open prepares the main pool and the session settings without connecting; Check connects.
func (*DB) Check ¶
Check connects both connections and runs the startup checks: the server version on each, the session state of the session connection, then the TLS report of each as database_connection_security.
func (*DB) CheckSchema ¶
CheckSchema reads the schema version over the main pool and refuses to run on a schema that is dirty, newer than the binary knows or, since the server did not migrate, older.
func (*DB) ConnectSession ¶
ConnectSession opens a new session connection; the caller closes it.
func (*DB) Migrate ¶
Migrate applies the embedded migrations over a session connection that holds the migration advisory lock, and logs the versions applied. It refuses a dirty schema and one newer than the binary knows, naming both versions.
func (*DB) RegisterMetrics ¶
func (d *DB) RegisterMetrics()
RegisterMetrics exports the metrics of the main pool, read at every scrape.
func (*DB) SessionListenConn ¶
func (d *DB) SessionListenConn(ctx context.Context) (ListenConn, error)
SessionListenConn opens a session connection for a Listener.
type Execer ¶
type Execer interface {
Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
}
Execer runs a statement: a pool, a connection or the transaction of the change a hint announces.
type Hint ¶
type Hint struct {
OrgID int64 `json:"org_id"`
Type string `json:"type"`
ID string `json:"id,omitempty"`
User string `json:"user,omitempty"`
}
Hint is the payload of a notification on HintChannel: something of the Organization changed. Type is the type of a live-update hint (HintEvent in the API specification) and ID the public_id it names, or empty for a whole collection. User, the public_id of a User, limits the hint to that User's streams, such as the account-links hint of the User whose Account link changed; empty is every stream.
type Lease ¶
Lease is how a worker of one replica claims rows: Owner names the replica in lease_owner, and a claim holds a row for Duration on the real clock.
func (Lease) Params ¶
func (l Lease) Params(limit int32) ClaimParams
Params are the values of a claim of at most limit rows, read from the clocks now.
type ListenConn ¶
type ListenConn interface {
Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
WaitForNotification(ctx context.Context) (*pgconn.Notification, error)
Close(ctx context.Context) error
}
ListenConn is the session connection a Listener holds; *pgx.Conn implements it.
type Listener ¶
type Listener struct {
// contains filtered or unexported fields
}
Listener keeps a LISTEN on HintChannel over a session connection of its own — a pooler in transaction mode would lose it — and passes every hint it receives on. It pings the connection when no notification came for a while and connects again after a loss, with a growing delay.
func NewListener ¶
NewListener returns the Listener over connect, which opens a session connection.
func (*Listener) Listen ¶
Listen makes the Listener also listen on channel and pass each payload to f, such as the notification that wakes the processing workers; it is called before Run.
func (*Listener) Run ¶
Run listens until ctx ends. Each hint goes to hint, and listening calls listening each time the LISTEN is in place; after the first time, notifications sent while the connection was lost are gone, so the caller tells its clients to read everything again. A payload that is not a Hint is skipped. A loss is logged as live_updates_listen_failed once until the LISTEN is back, which is logged as live_updates_listen_restored.
type Poller ¶
type Poller struct {
Interval time.Duration
MaxBackoff time.Duration
// Wait waits d; nil is time.After.
Wait func(d time.Duration) <-chan time.Time
// Random is uniform in [0, 1); nil is math/rand/v2.
Random func() float64
}
Poller runs the rounds of a worker: one round every Interval, give or take a tenth for jitter, and after a failed round the Backoff from Interval up to MaxBackoff.
type PoolerError ¶
type PoolerError struct {
Err error
}
PoolerError says that the session connection does not keep session state, probably because it goes through a transaction pooler.
func (*PoolerError) Error ¶
func (e *PoolerError) Error() string
func (*PoolerError) Unwrap ¶
func (e *PoolerError) Unwrap() error
type SchemaError ¶
type SchemaError struct {
Event logging.Event
Database uint
Known uint
// contains filtered or unexported fields
}
SchemaError is a schema the binary refuses to run on.
func (*SchemaError) Error ¶
func (e *SchemaError) Error() string