db

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: AGPL-3.0 Imports: 31 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	ConnectionMain    = "main"
	ConnectionSession = "session"
)

The names of the two connections in log lines.

View Source
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).

View Source
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.

View Source
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.

View Source
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
)
View Source
const (
	// MinServerVersion is PostgreSQL 14, the first with idle_session_timeout, which the Leader lease relies on
	// (ADR-0006, ADR-0007).
	MinServerVersion = 140000
)
View Source
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.

View Source
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

func Backoff(failures int, base, limit time.Duration, random func() float64) time.Duration

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

func CheckSession(ctx context.Context, session sessionConn, notifier querier) error

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

func CheckVersion(ctx context.Context, q querier) error

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 Encrypted

func Encrypted(ctx context.Context, q querier) (bool, error)

Encrypted reports whether the connection behind q uses TLS, from pg_stat_ssl.

func Held

func Held(until, now time.Time) bool

Held reports whether a lease that runs until until is still held at the real time now.

func KnownVersion

func KnownVersion() (uint, error)

KnownVersion is the version of the newest embedded migration.

func NotifyHint

func NotifyHint(ctx context.Context, e Execer, h Hint) error

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.

func ReportSecurity

func ReportSecurity(ctx context.Context, log *logging.Logger, connection, sslMode string, encrypted bool)

ReportSecurity logs database_connection_security, at WARN when the connection is not encrypted.

Types

type Beginner

type Beginner interface {
	Begin(ctx context.Context) (pgx.Tx, error)
}

Beginner starts the short transaction of a claim; the main pool implements it.

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

type DB struct {
	Pool *pgxpool.Pool
	// contains filtered or unexported fields
}

DB is the main pool and the settings of the session connection.

func Open

func Open(ctx context.Context, main, session config.Database) (*DB, error)

Open prepares the main pool and the session settings without connecting; Check connects.

func (*DB) Check

func (d *DB) Check(ctx context.Context, log *logging.Logger) error

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

func (d *DB) CheckSchema(ctx context.Context, log *logging.Logger) error

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) Close

func (d *DB) Close()

Close closes the pool.

func (*DB) ConnectSession

func (d *DB) ConnectSession(ctx context.Context) (*pgx.Conn, error)

ConnectSession opens a new session connection; the caller closes it.

func (*DB) Migrate

func (d *DB) Migrate(ctx context.Context, log *logging.Logger) error

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) Ping

func (d *DB) Ping(ctx context.Context) error

Ping runs SELECT 1 on the main pool, within a second: the readiness check.

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.

func (*DB) WithMigrationLock

func (d *DB) WithMigrationLock(ctx context.Context, f func(context.Context) error) error

WithMigrationLock runs f while this process holds the migration advisory lock on a session connection; it waits while another process holds it.

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

type Lease struct {
	Owner    string
	Duration time.Duration
	Clocks   clock.Clocks
}

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

func NewListener(connect func(context.Context) (ListenConn, error), log *logging.Logger) *Listener

NewListener returns the Listener over connect, which opens a session connection.

func (*Listener) Listen

func (l *Listener) Listen(channel string, f func(payload string))

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

func (l *Listener) Run(ctx context.Context, hint func(Hint), listening func(restored bool))

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.

func (Poller) Run

func (p Poller) Run(ctx context.Context, round func(ctx context.Context) error)

Run calls round until ctx ends; round reports whether it failed, and logs why itself.

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

Jump to

Keyboard shortcuts

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