sqlite

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: AGPL-3.0 Imports: 26 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 sqlite implements the store interfaces on SQLite with the CGO-free modernc.org/sqlite driver (ADR 0004, 0013).

Every database file is opened twice: a writer pool with exactly one connection and immediate transactions, so writers never race for the lock (PF-22), and a read-only pool for concurrent readers.

Index

Constants

View Source
const (

	// DefaultMetricsCacheKiB is the writer page cache of metrics.db (ADR 0013 C5).
	DefaultMetricsCacheKiB = 64 << 10
)
View Source
const MetricsFile = "metrics.db"

MetricsFile is the file name of the data class B database inside the data directory.

View Source
const StateFile = "state.db"

StateFile is the file name of the data class A database inside the data directory.

Variables

This section is empty.

Functions

This section is empty.

Types

type CheckpointResult

type CheckpointResult struct {
	// Busy is true if readers prevented a complete checkpoint.
	Busy         bool
	LogFrames    int
	Checkpointed int
}

CheckpointResult reports the outcome of a WAL checkpoint.

type DB

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

DB is one SQLite file with a single-connection writer and a read pool.

func Open

func Open(ctx context.Context, opts Options) (*DB, error)

Open opens the file, applies migrations and verifies the effective pragmas on every pooled connection (FA-NODE-06). The directory must exist.

func (*DB) Checkpoint

func (db *DB) Checkpoint(ctx context.Context) (CheckpointResult, error)

Checkpoint runs PRAGMA wal_checkpoint(TRUNCATE) on the writer (ADR 0013 C4).

func (*DB) Close

func (db *DB) Close() error

Close closes both pools.

func (*DB) IncrementalVacuum

func (db *DB) IncrementalVacuum(ctx context.Context, pages int) error

IncrementalVacuum returns up to pages free pages to the file system (0 = all free pages).

func (*DB) Path

func (db *DB) Path() string

Path returns the database file path.

func (*DB) RunCheckpointer

func (db *DB) RunCheckpointer(ctx context.Context, interval time.Duration, log *slog.Logger)

RunCheckpointer checkpoints periodically until ctx is cancelled and logs incomplete checkpoints, which indicate checkpoint starvation (PF-24).

func (*DB) SelfTest

func (db *DB) SelfTest(ctx context.Context) error

SelfTest reads back the pragmas on the writer and on every reader connection. A typo in the DSN would otherwise silently leave the database without WAL or busy timeout (PF-22).

func (*DB) WALSize

func (db *DB) WALSize() (int64, error)

WALSize returns the size of the write-ahead log in bytes (0 if absent).

type MetricsOptions

type MetricsOptions struct {
	// CacheSizeKiB of the writer; 0 = DefaultMetricsCacheKiB.
	CacheSizeKiB int
}

MetricsOptions tune metrics.db.

type MetricsStore

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

MetricsStore implements store.Metrics on metrics.db.

func OpenMetrics

func OpenMetrics(ctx context.Context, dataDir string, opts MetricsOptions) (*MetricsStore, error)

OpenMetrics opens or creates dataDir/metrics.db. A new file gets a new random incarnation, even if the node ID is unchanged (ADR 0012 B4, PF-12).

func (*MetricsStore) AdvanceStreamPosition

func (m *MetricsStore) AdvanceStreamPosition(ctx context.Context, pos store.StreamPosition) error

AdvanceStreamPosition raises the position of a stream to pos.Seq; a lower seq is ignored. An unknown stream is created.

func (*MetricsStore) Close

func (m *MetricsStore) Close() error

Close closes the database.

func (*MetricsStore) CompactHeartbeats

func (m *MetricsStore) CompactHeartbeats(ctx context.Context, minutes []store.LatencyMinute, deleted []store.HeartbeatKey) error

CompactHeartbeats stores latency minutes and deletes heartbeats atomically.

func (*MetricsStore) DB

func (m *MetricsStore) DB() *DB

DB exposes the underlying database for maintenance (checkpoints, vacuum).

func (*MetricsStore) DeleteHeartbeatsBefore

func (m *MetricsStore) DeleteHeartbeatsBefore(ctx context.Context, beforeMs int64, batchSize int) (int64, error)

DeleteHeartbeatsBefore deletes one batch of heartbeats older than beforeMs.

func (*MetricsStore) DeleteLatencyMinutesBefore

func (m *MetricsStore) DeleteLatencyMinutesBefore(ctx context.Context, beforeMs int64, batchSize int) (int64, error)

DeleteLatencyMinutesBefore deletes one batch of latency minutes, at most batchSize rows in one transaction (FA-UPT-06).

func (*MetricsStore) DeleteRollupsBefore

func (m *MetricsStore) DeleteRollupsBefore(ctx context.Context, bucketMs, beforeMs int64, batchSize int) (int64, error)

DeleteRollupsBefore deletes one batch of rollups of a bucket size. The batch holds at most batchSize rows in one transaction (FA-UPT-06).

func (*MetricsStore) HeartbeatsAfter

func (m *MetricsStore) HeartbeatsAfter(ctx context.Context, nodeID, incarnation string, afterSeq, untilSeq uint64, limit int) ([]store.Heartbeat, bool, error)

HeartbeatsAfter returns up to limit heartbeats of one stream with afterSeq < seq <= untilSeq in seq order, and whether more follow. untilSeq 0 means no upper bound.

func (*MetricsStore) Incarnation

func (m *MetricsStore) Incarnation() string

Incarnation returns the incarnation of this metrics database.

func (*MetricsStore) InsertDegradedAlert

func (m *MetricsStore) InsertDegradedAlert(ctx context.Context, a store.DegradedAlert) (int64, error)

InsertDegradedAlert appends an alert to the node-local degraded log.

func (*MetricsStore) InsertHeartbeats

func (m *MetricsStore) InsertHeartbeats(ctx context.Context, hbs []store.Heartbeat) (int, error)

InsertHeartbeats stores heartbeats in one transaction; duplicates are ignored. The same transaction advances the position of each stream it touches.

func (*MetricsStore) LastSeq

func (m *MetricsStore) LastSeq(ctx context.Context, nodeID, incarnation string) (uint64, error)

LastSeq returns the highest stored seq of the stream, or 0.

func (*MetricsStore) LatestHeartbeats

func (m *MetricsStore) LatestHeartbeats(ctx context.Context, tenantID, monitorID, nodeID string, limit int) ([]store.Heartbeat, error)

LatestHeartbeats returns the newest heartbeats of a monitor, newest first.

func (*MetricsStore) LatestHeartbeatsByMonitor

func (m *MetricsStore) LatestHeartbeatsByMonitor(ctx context.Context, tenantID string, monitorIDs []string) (map[string]store.Heartbeat, error)

LatestHeartbeatsByMonitor returns the newest heartbeat of each listed monitor over all nodes, in one query. Rows that share the newest instant are resolved by the highest seq, as LatestHeartbeats orders them.

func (*MetricsStore) ListHeartbeats

func (m *MetricsStore) ListHeartbeats(ctx context.Context, tenantID string, q store.HeartbeatQuery) (store.HeartbeatPage, error)

ListHeartbeats returns one page of the tenant's heartbeats of a monitor.

func (*MetricsStore) ListRollups

func (m *MetricsStore) ListRollups(ctx context.Context, tenantID string, q store.RollupQuery) ([]store.Rollup, error)

ListRollups returns rollups ordered by node and start.

func (*MetricsStore) ListRollupsBatch

func (m *MetricsStore) ListRollupsBatch(ctx context.Context, tenantID string, q store.RollupBatchQuery) ([]store.Rollup, error)

ListRollupsBatch returns the rollups of several monitors for one node, ordered by monitor and time.

func (*MetricsStore) ListUnreportedDegradedAlerts

func (m *MetricsStore) ListUnreportedDegradedAlerts(ctx context.Context, limit int) ([]store.DegradedAlert, error)

ListUnreportedDegradedAlerts returns up to limit alerts not yet reported, by ID.

func (*MetricsStore) MarkDegradedAlertsReported

func (m *MetricsStore) MarkDegradedAlertsReported(ctx context.Context, ids []int64) error

MarkDegradedAlertsReported records in one transaction that the alerts reached the leader.

func (*MetricsStore) MarkTenantPurged

func (m *MetricsStore) MarkTenantPurged(ctx context.Context, tenantID string, purgedMs int64) error

MarkTenantPurged records that the purge of the tenant finished on this node.

func (*MetricsStore) PruneDegradedAlerts

func (m *MetricsStore) PruneDegradedAlerts(ctx context.Context, beforeMs int64) (int64, error)

PruneDegradedAlerts deletes the alerts sent before beforeMs.

func (*MetricsStore) PurgeTenant

func (m *MetricsStore) PurgeTenant(ctx context.Context, tenantID string, batchSize int) (int64, error)

PurgeTenant deletes up to batchSize rows of the tenant from each metrics table that holds tenant data: heartbeats and degraded alerts by tenant_id, rollups and latency minutes through their series, and the series last, once nothing references them (ADR 0029). It returns the rows deleted in this call; 0 means nothing of the tenant is left. One call is one write transaction.

func (*MetricsStore) PurgedTenants

func (m *MetricsStore) PurgedTenants(ctx context.Context) ([]string, error)

PurgedTenants returns the IDs of the tenants whose purge finished on this node, ordered by ID.

func (*MetricsStore) PutRollups

func (m *MetricsStore) PutRollups(ctx context.Context, rollups []store.Rollup, watermarks map[string]int64) error

PutRollups stores rollups and watermarks in one transaction.

func (*MetricsStore) SetWatermark

func (m *MetricsStore) SetWatermark(ctx context.Context, name string, value int64) error

SetWatermark stores a watermark.

func (*MetricsStore) StreamPositions

func (m *MetricsStore) StreamPositions(ctx context.Context) ([]store.StreamPosition, error)

StreamPositions returns the position of every stream known locally.

func (*MetricsStore) Watermark

func (m *MetricsStore) Watermark(ctx context.Context, name string) (int64, error)

Watermark returns a stored watermark, 0 if unset.

type Options

type Options struct {
	Path        string
	Synchronous Synchronous
	// ReadConns is the size of the read pool (ADR 0013 C4: 4 for metrics.db).
	ReadConns int
	// CacheSizeKiB sets PRAGMA cache_size on the writer; 0 keeps the SQLite default.
	CacheSizeKiB int
	// Migrations holds goose SQL migrations at the root of the FS.
	Migrations fs.FS
}

Options configure one database file.

type StateStore

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

StateStore implements store.State on state.db.

mu guards the database handle: RestoreSnapshot swaps the whole file while readers keep using the store.

func OpenState

func OpenState(ctx context.Context, dataDir string) (*StateStore, error)

OpenState opens or creates dataDir/state.db.

func (*StateStore) AppliedIndex

func (s *StateStore) AppliedIndex(ctx context.Context) (uint64, error)

AppliedIndex returns the last applied Raft index stored in state.db.

func (*StateStore) Close

func (s *StateStore) Close() error

Close closes the database.

func (*StateStore) CommandLevel

func (s *StateStore) CommandLevel(ctx context.Context) (uint32, error)

CommandLevel returns the command level stored in state.db (ADR 0018), 0 if unset.

func (*StateStore) CountPendingAlerts

func (s *StateStore) CountPendingAlerts(ctx context.Context) (int, error)

CountPendingAlerts returns the number of outbox entries that are not delivered yet (the pulsequorum_outbox_pending metric, ADR 0025).

func (*StateStore) CountUsers

func (s *StateStore) CountUsers(ctx context.Context) (int, error)

CountUsers returns the number of users of all tenants.

func (*StateStore) DB

func (s *StateStore) DB() *DB

DB exposes the underlying database for maintenance (checkpoints). The handle is replaced by RestoreSnapshot; callers must not keep it across a restore.

func (*StateStore) DueAlerts

func (s *StateStore) DueAlerts(ctx context.Context, nowMs int64, limit int) ([]store.AlertDelivery, error)

DueAlerts returns pending deliveries due at nowMs.

func (*StateStore) Fingerprint

func (s *StateStore) Fingerprint(ctx context.Context) (string, error)

Fingerprint hashes all replicated rows in a fixed order. Two replicas that applied the same log entries have the same fingerprint (FA-CLU-07, ADR 0012 A7).

func (*StateStore) GetAPITokenBySecretHash

func (s *StateStore) GetAPITokenBySecretHash(ctx context.Context, secretHash string) (store.APIToken, error)

GetAPITokenBySecretHash returns the API token with the secret hash or ErrNotFound (ADR 0031).

func (*StateStore) GetAlert

func (s *StateStore) GetAlert(ctx context.Context, alertKey, channelID string) (store.AlertDelivery, error)

GetAlert returns one outbox entry.

func (*StateStore) GetChannel

func (s *StateStore) GetChannel(ctx context.Context, tenantID, id string) (store.NotificationChannel, error)

GetChannel returns a notification channel of the tenant.

func (*StateStore) GetIncident

func (s *StateStore) GetIncident(ctx context.Context, tenantID, id string) (store.Incident, error)

GetIncident returns an incident of the tenant.

func (*StateStore) GetJoinToken

func (s *StateStore) GetJoinToken(ctx context.Context, id string) (store.JoinToken, error)

GetJoinToken returns the join token with the ID.

func (*StateStore) GetMaintenanceWindow

func (s *StateStore) GetMaintenanceWindow(ctx context.Context, tenantID, id string) (store.MaintenanceWindow, error)

GetMaintenanceWindow returns a maintenance window of the tenant.

func (*StateStore) GetMonitor

func (s *StateStore) GetMonitor(ctx context.Context, tenantID, id string) (store.Monitor, error)

GetMonitor returns a monitor of the tenant.

func (*StateStore) GetPlan

func (s *StateStore) GetPlan(ctx context.Context, id string) (store.Plan, error)

GetPlan returns a plan or ErrNotFound.

func (*StateStore) GetSession

func (s *StateStore) GetSession(ctx context.Context, tokenHash string) (store.Session, error)

GetSession returns the refresh token with the hash.

func (*StateStore) GetTenant

func (s *StateStore) GetTenant(ctx context.Context, id string) (store.Tenant, error)

GetTenant returns a tenant by ID.

func (*StateStore) GetTenantByOrg

func (s *StateStore) GetTenantByOrg(ctx context.Context, orgID string) (store.Tenant, error)

GetTenantByOrg returns the tenant bound to the identity-provider organization. An empty orgID is ErrNotFound without a query: tenants without an organization have NULL in the column, and NULL never matches (ADR 0027).

func (*StateStore) GetUser

func (s *StateStore) GetUser(ctx context.Context, tenantID, id string) (store.User, error)

GetUser returns a user of the tenant.

func (*StateStore) GetUserByUsername

func (s *StateStore) GetUserByUsername(ctx context.Context, username string) (store.User, error)

GetUserByUsername returns the user with the username, compared case-insensitively.

func (*StateStore) LastIssuedAt

func (s *StateStore) LastIssuedAt(ctx context.Context) (int64, error)

LastIssuedAt returns the command time of the last applied command (ADR 0024).

func (*StateStore) ListAPITokens

func (s *StateStore) ListAPITokens(ctx context.Context, tenantID string) ([]store.APIToken, error)

ListAPITokens returns the API tokens of the tenant, newest first.

func (*StateStore) ListAllMaintenanceWindows

func (s *StateStore) ListAllMaintenanceWindows(ctx context.Context) ([]store.MaintenanceWindow, error)

ListAllMaintenanceWindows returns the windows of all tenants ordered by tenant ID and ID.

func (*StateStore) ListAudit

func (s *StateStore) ListAudit(ctx context.Context, q store.AuditQuery) (store.AuditPage, error)

ListAudit returns one page of the audit log, newest first. Empty filter fields do not filter; the cursor continues strictly after its entry. Next is set only if more entries exist.

func (*StateStore) ListChannels

func (s *StateStore) ListChannels(ctx context.Context, tenantID string) ([]store.NotificationChannel, error)

ListChannels returns the tenant's channels ordered by name.

func (*StateStore) ListClusterCAs

func (s *StateStore) ListClusterCAs(ctx context.Context) ([]store.ClusterCA, error)

ListClusterCAs returns the cluster CAs ordered by creation.

func (*StateStore) ListDeletedTenants

func (s *StateStore) ListDeletedTenants(ctx context.Context) ([]store.DeletedTenant, error)

ListDeletedTenants returns the tombstones ordered by ID.

func (*StateStore) ListIncidents

func (s *StateStore) ListIncidents(ctx context.Context, tenantID string, q store.IncidentQuery) (store.IncidentPage, error)

ListIncidents returns one page of the tenant's incidents, newest first.

func (*StateStore) ListJoinTokens

func (s *StateStore) ListJoinTokens(ctx context.Context) ([]store.JoinToken, error)

ListJoinTokens returns all join tokens ordered by creation and ID.

func (*StateStore) ListMaintenanceWindows

func (s *StateStore) ListMaintenanceWindows(ctx context.Context, tenantID string) ([]store.MaintenanceWindow, error)

ListMaintenanceWindows returns the tenant's windows ordered by name and ID.

func (*StateStore) ListMonitors

func (s *StateStore) ListMonitors(ctx context.Context, tenantID string, q store.MonitorQuery) (store.MonitorPage, error)

ListMonitors returns one page of the tenant's monitors ordered by ID.

func (*StateStore) ListNodeIncarnations

func (s *StateStore) ListNodeIncarnations(ctx context.Context) ([]store.NodeIncarnation, error)

ListNodeIncarnations returns the last known incarnations ordered by node ID (ADR 0025).

func (*StateStore) ListNodes

func (s *StateStore) ListNodes(ctx context.Context) ([]store.Node, error)

ListNodes returns the node registry ordered by node ID (ADR 0017).

func (*StateStore) ListOpenUnconfirmedAlerts

func (s *StateStore) ListOpenUnconfirmedAlerts(ctx context.Context, limit int) ([]store.UnconfirmedAlert, error)

ListOpenUnconfirmedAlerts returns up to limit alerts without verdict (ADR 0024).

func (*StateStore) ListPlans

func (s *StateStore) ListPlans(ctx context.Context) ([]store.Plan, error)

ListPlans returns all plans ordered by ID.

func (*StateStore) ListRevokedCerts

func (s *StateStore) ListRevokedCerts(ctx context.Context) ([]store.RevokedCert, error)

ListRevokedCerts returns the revoked certificates ordered by serial.

func (*StateStore) ListRevokedNodes

func (s *StateStore) ListRevokedNodes(ctx context.Context) ([]store.RevokedNode, error)

ListRevokedNodes returns the revoked nodes ordered by node ID.

func (*StateStore) ListSecretKeys

func (s *StateStore) ListSecretKeys(ctx context.Context) ([]store.SecretKey, error)

ListSecretKeys returns all data encryption keys ordered by creation.

func (*StateStore) ListSigningKeys

func (s *StateStore) ListSigningKeys(ctx context.Context) ([]store.SigningKey, error)

ListSigningKeys returns all signing keys ordered by creation time and KID.

func (*StateStore) ListSystemAlerts

func (s *StateStore) ListSystemAlerts(ctx context.Context, activeOnly bool) ([]store.SystemAlert, error)

ListSystemAlerts returns the system alerts ordered by kind and subject; with activeOnly only the active ones (ADR 0025).

func (*StateStore) ListTenants

func (s *StateStore) ListTenants(ctx context.Context) ([]store.Tenant, error)

ListTenants returns all tenants ordered by ID.

func (*StateStore) ListUnrevokedSessionUsers

func (s *StateStore) ListUnrevokedSessionUsers(ctx context.Context) ([]store.SessionUser, error)

ListUnrevokedSessionUsers returns the users with a refresh token that is not revoked (ADR 0032).

func (*StateStore) ListUsers

func (s *StateStore) ListUsers(ctx context.Context, tenantID string) ([]store.User, error)

ListUsers returns the tenant's users ordered by username.

func (*StateStore) RestoreSnapshot

func (s *StateStore) RestoreSnapshot(ctx context.Context, r io.Reader) error

RestoreSnapshot replaces state.db with the database read from r and reopens it (ADR 0012 A1). Readers block for the duration of the swap.

func (*StateStore) StatusHistory

func (s *StateStore) StatusHistory(ctx context.Context, tenantID, monitorID string, fromMs, toMs int64) ([]store.StatusChange, error)

StatusHistory returns the status changes in [fromMs, toMs) and the last one before.

func (*StateStore) StatusHistoryBatch

func (s *StateStore) StatusHistoryBatch(ctx context.Context, tenantID string, monitorIDs []string, fromMs, toMs int64) (map[string][]store.StatusChange, error)

StatusHistoryBatch returns StatusHistory for each listed monitor of the tenant.

func (*StateStore) TenantUsage

func (s *StateStore) TenantUsage(ctx context.Context, tenantID string) (store.TenantUsage, error)

TenantUsage counts what a tenant uses of its limits (ADR 0029).

func (*StateStore) Update

func (s *StateStore) Update(ctx context.Context, fn func(tx store.StateTx) error) error

Update runs fn in a single immediate write transaction.

func (*StateStore) WriteSnapshot

func (s *StateStore) WriteSnapshot(ctx context.Context, w io.Writer) error

WriteSnapshot writes a consistent copy of state.db to w using VACUUM INTO (ADR 0012 A1). It runs on the read pool and does not block writers, so the copy may be newer than the Raft index the snapshot is taken at; that is safe because the applied index is part of the copy.

type Synchronous

type Synchronous int

Synchronous is the value of PRAGMA synchronous.

const (
	SyncNormal Synchronous = 1
	SyncFull   Synchronous = 2
)

Durability levels (ADR 0004: FULL for state.db, NORMAL for metrics.db).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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