store

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 22 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 store persists clusters, snapshots and evaluations for the upgradescope server. Store is the seam P3's Postgres implementation fills in; P2 ships the SQLite implementation in this package.

Index

Constants

View Source
const (
	SummaryCapabilityBytes = 64
	SummaryReasonBytes     = 256
	SummarySkipped         = 3
	SummarySkippedBytes    = 128
)

What the not_assessed column keeps of a gap. The fleet-wide reads load it for every cluster and target, so it is bounded: a gap's capability name (a push may name one of 16 KiB) is cut to SummaryCapabilityBytes, its reason (up to 64 KiB) to SummaryReasonBytes, and its skipped list to its first SummarySkipped entries, each cut to SummarySkippedBytes, with skippedOmitted counting the rest. A gap is then at most about 900 bytes, and with at most inventory.MaxCapabilities gaps and the engine's own an evaluation's column at most about 30 KB. (With names whole, a 1 KiB reason and 10 entries of 512 bytes, the columns of 50 clusters made /fleet answer 108 MB and grow the heap 516 MiB; the reads also list only part of a column: fleetSummaryBytes in the server.) A genuine name, reason or entry is shorter; the report keeps every gap whole.

View Source
const ReadScopeFleet = "*"

ReadScopeFleet is the team scope of a fleet-wide read token.

Variables

View Source
var ErrClusterChanged = errors.New("store: the cluster was renamed or deleted while the push was processed")

ErrClusterChanged is returned by CommitEvaluations when the batch's Cluster.ID is set and the cluster registered under its name is no longer that cluster: it was renamed or deleted after the push looked it up. Nothing was written.

View Source
var ErrClusterNameTaken = errors.New("store: cluster name is taken")

ErrClusterNameTaken is returned by RenameCluster when the new name is registered to another cluster. Test with errors.Is.

View Source
var ErrClusterUIDConflict = errors.New("store: cluster name is bound to another cluster UID")

ErrClusterUIDConflict is returned (as a *ClusterUIDConflictError) by UpsertCluster when the name is already bound to a different cluster UID. Test with errors.Is.

View Source
var ErrConflict = errors.New("store: evaluation state changed concurrently")

ErrConflict is returned by CommitEvaluations when the batch was computed against state another writer has since changed. Nothing was written; the caller may drop the pass (the other writer covered it) or recompute.

View Source
var ErrNotFound = errors.New("store: not found")

ErrNotFound is returned (possibly wrapped) by lookups that match no row. Test with errors.Is.

View Source
var ErrTokenRevoked = errors.New("store: the ingest token is no longer valid for this cluster")

ErrTokenRevoked is returned by CommitEvaluations when the batch's IngestToken is no longer an active token of its cluster: revoked, or moved or deleted with the cluster, while the push was processed. Nothing was written.

Functions

func CarriesHold added in v0.2.0

func CarriesHold(report []byte) bool

CarriesHold reports whether a stored report carries a held deprecated caller (holdMarker): the carries_hold column of report, and the cheap test before a report is decoded for a hold.

func CutString added in v0.2.0

func CutString(s string, max int) string

CutString is s cut to at most max bytes, at a UTF-8 boundary, marked with "…" when it is cut.

func HashToken

func HashToken(token string) string

HashToken is the storage form of an ingest token: lowercase hex sha256. Exported so callers (CLI, tests) can locate rows without the plaintext.

func Migrate

func Migrate(ctx context.Context, db *sql.DB, fsys fs.FS) ([]string, error)

Migrate applies every "*.sql" file in fsys that has not been applied yet, in lexicographic filename order. Each migration runs in its own transaction and its filename is recorded in schema_migrations inside that same transaction, so a failed migration leaves no trace. Running Migrate again is a no-op for already-recorded files. Returns the filenames applied on this run.

Migrate speaks '?' placeholders (SQLite); the Postgres store calls migratePostgres, which runs migrate with postgresMigrations under an advisory lock. applied_at stays TEXT (RFC 3339) in both backends — it is bookkeeping written and read only by this file.

func TokenPrefix added in v0.2.0

func TokenPrefix(token string) string

TokenPrefix is the identifying prefix stored with a token: its first 8 characters, or "" when the token is shorter than 32 characters — a prefix must stay a small fraction of the secret. `tokens create` mints 64 hex characters, so the stored prefix carries 32 of its 256 bits.

Types

type Cluster

type Cluster struct {
	ID         int64     `json:"id"`
	Name       string    `json:"name"`       // unique
	ClusterUID string    `json:"clusterUid"` // inventory.ClusterID
	FirstSeen  time.Time `json:"firstSeen"`
	LastSeen   time.Time `json:"lastSeen"`
}

type ClusterUIDConflictError added in v0.2.0

type ClusterUIDConflictError struct {
	Name      string
	StoredUID string
	PushedUID string
}

ClusterUIDConflictError carries both UIDs so callers can explain the conflict. Is(ErrClusterUIDConflict) holds.

func (*ClusterUIDConflictError) Error added in v0.2.0

func (e *ClusterUIDConflictError) Error() string

func (*ClusterUIDConflictError) Is added in v0.2.0

func (e *ClusterUIDConflictError) Is(target error) bool

type Evaluation

type Evaluation struct {
	ID         int64  `json:"id"`
	ClusterID  int64  `json:"clusterId"`
	SnapshotID int64  `json:"snapshotId"`
	Target     string `json:"target"`
	KBVersion  string `json:"kbVersion"`
	Score      int    `json:"score"`
	Ready      bool   `json:"ready"`
	Blockers   int    `json:"blockers"`
	Warnings   int    `json:"warnings"`
	Report     []byte `json:"-"` // full engine.Report JSON
	// NotAssessed is the report's notAssessed array as JSON, nil when it
	// is absent or empty. Written by the store, never by the caller: every
	// write that stores a Report stores this beside it (notAssessedOf), so
	// a summary that says what a verdict could not cover reads no report.
	NotAssessed []byte    `json:"-"`
	CreatedAt   time.Time `json:"createdAt"`
	// EvaluatedAt is when this result was last confirmed: a re-evaluation
	// with the same verdict, score and finding keys refreshes the row
	// instead of adding a history point. Zero on insert defaults to
	// CreatedAt.
	EvaluatedAt time.Time `json:"evaluatedAt"`
	// TeamMapHash identifies the server --team-map the report was computed
	// with ("" = none), so a changed map triggers a re-evaluation.
	TeamMapHash string `json:"teamMapHash,omitempty"`
	// Teams are the teams the evaluated inventory attributes a namespace to
	// (sorted): the clusters a team-scoped read token reads
	// (ClustersOfTeams). Written with every Report, on insert and refresh
	// (nil is none); reads leave it nil.
	Teams []string `json:"-"`
	// TeamsUnknown is set on read for a row written by a binary that
	// predates the teams column (NULL): no scoped token reads its cluster
	// until the next pass rewrites it, so the server treats it as stale.
	TeamsUnknown bool `json:"-"`
	// CarriesHold is set on read when the report carries a deprecated
	// caller held after an apiserver restart (CarriesHold), summaries
	// included, so the background pass knows which evaluations need their
	// snapshot's inventory without loading a report. Written by the store
	// from the report, never by the caller; true for a row written by a
	// binary that predates the column (NULL), which may carry one.
	CarriesHold bool `json:"-"`
	// Baseline marks an evaluation the server takes as a notification
	// baseline although its verdict is unknown (#380): its required gaps
	// hide no finding (kb-coverage, target), so the pass saw all a
	// blocker could come from. LatestKnownEvaluation returns it, the
	// commit checks it and retention keeps it, as a decided one. A decided
	// evaluation is a baseline whatever Baseline says. Written by the
	// caller, on insert and refresh; false on read for a row written
	// before the column (NULL).
	Baseline bool `json:"-"`
}

type EvaluationBatch added in v0.2.0

type EvaluationBatch struct {
	// Cluster, when non-nil, is upserted first in the commit's transaction
	// (UpsertCluster rules) and its id replaces ClusterID: ingest registers
	// a new cluster only together with its first snapshot.
	// When Cluster.ID is set (the cluster the push looked up), the commit
	// fails with ErrClusterChanged unless the name is still that cluster.
	Cluster   *Cluster
	ClusterID int64
	// IngestToken, with Cluster, is the per-cluster ingest token the push
	// was authenticated with ("" for the shared token, which the store does
	// not know). The commit fails with ErrTokenRevoked unless it is still
	// an active token of Cluster.Name, checked in the commit's transaction
	// so a push authenticated before a revoke cannot land after it.
	IngestToken string
	// Snapshot, when non-nil, is a newly pushed snapshot stored first
	// (InsertSnapshot dedup rules); every Insert gets its id.
	Snapshot *Snapshot
	// SnapshotID is the already-stored snapshot the pass evaluated when
	// Snapshot is nil. It must still be the cluster's latest snapshot.
	SnapshotID int64
	// Current records, per target, the id of the snapshot's current
	// evaluation the pass compared against (0 = it had none). The commit
	// fails with ErrConflict when any of them changed meanwhile.
	Current map[string]int64
	// Insert adds history rows; their SnapshotID is overwritten with the
	// evaluated snapshot's id.
	Insert []Evaluation
	// Refresh updates existing rows by ID with an unchanged result:
	// Report, KBVersion, TeamMapHash, Blockers, Warnings, EvaluatedAt and
	// Baseline.
	// Score, Ready and CreatedAt (the history point) stay.
	Refresh []Evaluation
	Outbox  []OutboxMessage
	// Expect, when set, is what the pass computed its notification deltas
	// from. The commit checks it in its transaction (compare-and-swap) and
	// fails with ErrConflict, writing nothing, when another writer has
	// changed it since, so a delta is never committed against a baseline
	// that is no longer the newest. A duplicate writes no evaluation and is
	// not checked.
	Expect *Expectation
}

EvaluationBatch is one evaluation pass over one cluster snapshot.

type Expectation added in v0.2.0

type Expectation struct {
	// LatestSnapshotID is the cluster's latest snapshot when the pass
	// began, 0 for none. Checked only with Snapshot set (a push): the
	// stored snapshot a re-evaluation judges is SnapshotID.
	LatestSnapshotID int64
	// Baselines maps every target whose baseline the pass read to the id
	// of that target's newest baseline, decided or marked Baseline
	// (LatestKnownEvaluation), 0 for none.
	Baselines map[string]int64
}

Expectation is the state one pass read before computing its notification deltas (EvaluationBatch.Expect).

type OutboxMessage added in v0.2.0

type OutboxMessage struct {
	ID            int64
	ClusterID     int64  // set by CommitEvaluations; DeleteCluster drops the cluster's messages
	Sink          string // which configured notifier delivers it
	Payload       []byte // the event, JSON
	Attempts      int    // delivery attempts started so far (claims)
	CreatedAt     time.Time
	NextAttemptAt time.Time
}

OutboxMessage is one notification awaiting delivery to one sink.

type Postgres

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

Postgres is the Store implementation for fleets: same contract as SQLite (pinned by storetest.RunStoreConformance), backed by jackc/pgx via database/sql. Times are TIMESTAMPTZ columns; every time.Time returned is normalized to UTC.

func OpenPostgres

func OpenPostgres(ctx context.Context, dsn string) (*Postgres, error)

OpenPostgres connects to dsn (any pgx-accepted form, e.g. postgres://user:pass@host:5432/db), verifies the connection with a ping, and applies the embedded pgmigrations. Fails fast on unreachable or unauthorized servers instead of deferring the error to the first query: the ping has its own pgPingTimeout.

The wait on the migration lock and the migrations themselves run on ctx with no added deadline, as SQLite's do: a long migration, or a replica queued behind another replica's migrations, takes as long as it takes, and the deployment's startupProbe is the bound. Cancelling ctx (serve's SIGTERM) abandons the in-flight statement promptly, with an error that wraps ctx.Err().

func (*Postgres) ClaimOutbox added in v0.2.0

func (p *Postgres) ClaimOutbox(ctx context.Context, now time.Time, lease time.Duration, limit int) ([]OutboxMessage, error)

ClaimOutbox leases up to limit due messages (next_attempt_at <= now), oldest first. FOR UPDATE SKIP LOCKED lets replicas' workers claim disjoint batches instead of queueing on each other's rows.

func (*Postgres) Close

func (p *Postgres) Close() error

Close closes the underlying connection pool.

func (*Postgres) ClusterByName added in v0.2.0

func (p *Postgres) ClusterByName(ctx context.Context, name string) (Cluster, error)

ClusterByName returns the cluster registered under name, or ErrNotFound.

func (*Postgres) ClustersOfTeams added in v0.2.0

func (p *Postgres) ClustersOfTeams(ctx context.Context, teams []string, teamMapHash string) ([]int64, error)

ClustersOfTeams returns the clusters whose current evaluations, written with teamMapHash, name one of teams, in one query; the teams travel as one JSON parameter, as the SQLite store's do.

func (*Postgres) CommitEvaluations added in v0.2.0

func (p *Postgres) CommitEvaluations(ctx context.Context, b EvaluationBatch) (int64, bool, error)

CommitEvaluations writes b in one transaction.

Concurrency: the duplicate check and the Current/SnapshotID/Expect checks read state that must not change before the commit, and READ COMMITTED gives no such protection — two racing pushes of one hash would both miss the duplicate, two racing passes would both insert. Locking the parent clusters row FOR UPDATE first serializes writers of one cluster (across replicas too) without blocking other clusters. With b.Cluster set, the upsert takes that row lock (ON CONFLICT locks the row even when its guard refuses the update).

func (*Postgres) CreateReadToken added in v0.2.0

func (p *Postgres) CreateReadToken(ctx context.Context, teams []string, token string) (int64, error)

CreateReadToken stores a new active read token scoped to teams and returns its id; only the sha256 of token (plus TokenPrefix) is persisted.

func (*Postgres) CreateToken

func (p *Postgres) CreateToken(ctx context.Context, clusterName, token string) (int64, error)

CreateToken stores a new active ingest token for clusterName and returns its id; only the sha256 of token (plus TokenPrefix) is persisted. Fails if the token is already issued.

func (*Postgres) CurrentEvaluation added in v0.2.0

func (p *Postgres) CurrentEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)

CurrentEvaluation returns the newest evaluation for target of the cluster's latest snapshot (highest id), or ErrNotFound.

func (*Postgres) CurrentEvaluationSummary added in v0.2.0

func (p *Postgres) CurrentEvaluationSummary(ctx context.Context, clusterID int64, target string) (Evaluation, error)

CurrentEvaluationSummary is CurrentEvaluation without the report.

func (*Postgres) DeferOutbox added in v0.2.0

func (p *Postgres) DeferOutbox(ctx context.Context, id int64, next time.Time) error

DeferOutbox puts a claimed message back for later without counting the claim as an attempt, or returns ErrNotFound.

func (*Postgres) DeleteCluster added in v0.2.0

func (p *Postgres) DeleteCluster(ctx context.Context, name string) error

DeleteCluster removes the named cluster, its evaluations, snapshots, queued notifications and ingest tokens in one transaction, or returns ErrNotFound. The clusters row is locked first so a concurrent ingest of the same cluster cannot add a snapshot between the deletes.

func (*Postgres) DeleteOutbox added in v0.2.0

func (p *Postgres) DeleteOutbox(ctx context.Context, id int64) error

DeleteOutbox removes message id, or returns ErrNotFound.

func (*Postgres) GetCluster

func (p *Postgres) GetCluster(ctx context.Context, id int64) (Cluster, error)

GetCluster returns the cluster by id, or ErrNotFound.

func (*Postgres) IngestTokenCluster added in v0.2.0

func (p *Postgres) IngestTokenCluster(ctx context.Context, token string) (string, int64, bool, error)

IngestTokenCluster resolves a presented plaintext token to its cluster name and the id registered under that name (0 for none yet), in one statement, so one snapshot sees both: a rename moves them together.

func (*Postgres) InsertEvaluation

func (p *Postgres) InsertEvaluation(ctx context.Context, e Evaluation) (int64, error)

InsertEvaluation stores e. Zero CreatedAt defaults to now (UTC); zero EvaluatedAt to CreatedAt.

func (*Postgres) InsertSnapshot

func (p *Postgres) InsertSnapshot(ctx context.Context, snap Snapshot) (int64, bool, error)

InsertSnapshot stores snap unless its hash equals the hash of the cluster's LATEST snapshot, in which case it returns (latestID, true, nil) without writing. An older same-hash snapshot superseded by a different one does NOT count as a duplicate. Zero ReceivedAt defaults to now (UTC). It is CommitEvaluations with nothing but the snapshot.

func (*Postgres) Kind added in v0.2.0

func (p *Postgres) Kind() string

Kind names the store in metrics: "postgres".

func (*Postgres) LatestEvaluation

func (p *Postgres) LatestEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)

LatestEvaluation returns the newest evaluation for (cluster, target) by insertion order (highest id; never created_at, which a clock step can reorder), or ErrNotFound.

func (*Postgres) LatestKnownEvaluation added in v0.2.0

func (p *Postgres) LatestKnownEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)

LatestKnownEvaluation returns the newest evaluation for (cluster, target) that is ready, has a blocker, or is marked a baseline, or ErrNotFound.

func (*Postgres) LatestSnapshot

func (p *Postgres) LatestSnapshot(ctx context.Context, clusterID int64) (Snapshot, error)

LatestSnapshot returns the most recently inserted snapshot for the cluster (highest id), or ErrNotFound.

func (*Postgres) LatestSnapshotHead added in v0.2.0

func (p *Postgres) LatestSnapshotHead(ctx context.Context, clusterID int64) (Snapshot, error)

LatestSnapshotHead is LatestSnapshot without the inventory.

func (*Postgres) LatestSnapshotHeads added in v0.2.0

func (p *Postgres) LatestSnapshotHeads(ctx context.Context) (map[int64]Snapshot, error)

LatestSnapshotHeads returns every cluster's latest snapshot without its inventory, in one query: per cluster, one step down idx_snapshots_cluster_id from its end (a LATERAL lookup), so the cost follows the clusters, not every snapshot kept. DISTINCT ON (cluster_id) ... ORDER BY cluster_id, id DESC sorted every snapshot row instead: the (cluster_id, id) index gives neither direction of that order.

func (*Postgres) ListClusters

func (p *Postgres) ListClusters(ctx context.Context) ([]Cluster, error)

ListClusters returns all clusters, ascending by name.

func (*Postgres) ListReadTokens added in v0.2.0

func (p *Postgres) ListReadTokens(ctx context.Context) ([]ReadToken, error)

ListReadTokens returns every read token's metadata, ascending by id.

func (*Postgres) ListTokens added in v0.2.0

func (p *Postgres) ListTokens(ctx context.Context, clusterName string) ([]Token, error)

ListTokens returns token metadata, ascending by id, for clusterName or for every cluster when clusterName is "".

func (*Postgres) Ping added in v0.2.0

func (p *Postgres) Ping(ctx context.Context) error

Ping checks the server answers (the server's /readyz).

func (*Postgres) Prune added in v0.2.0

func (p *Postgres) Prune(ctx context.Context, cutoff time.Time, baselines PruneBaselines) (PruneResult, error)

Prune deletes evaluations created before cutoff, then the snapshots received before it that no evaluation refers to any more, sparing each cluster's latest snapshot and its evaluations and each (cluster, target)'s newest notification baseline (decided or Baseline), then those baselines baselines does not spare, in bounded batches of one transaction each (prune.go). A snapshot that becomes non-latest between the statements keeps its evaluations, so it stays until the next run.

func (*Postgres) RenameCluster added in v0.2.0

func (p *Postgres) RenameCluster(ctx context.Context, name, newName string) error

RenameCluster renames the cluster and re-binds its ingest tokens to the new name in one transaction. The row is locked first; a taken name is the clusters.name unique violation, which also covers a cluster registering newName concurrently.

func (*Postgres) RescheduleOutbox added in v0.2.0

func (p *Postgres) RescheduleOutbox(ctx context.Context, id int64, next time.Time, lastErr string) error

RescheduleOutbox records a failed attempt and when to try again, or returns ErrNotFound.

func (*Postgres) RevokeReadToken added in v0.2.0

func (p *Postgres) RevokeReadToken(ctx context.Context, id int64) error

RevokeReadToken revokes the active read token id, or ErrNotFound when there is none (unknown id, or already revoked).

func (*Postgres) RevokeToken

func (p *Postgres) RevokeToken(ctx context.Context, clusterName string) error

RevokeToken revokes every active token of clusterName, or ErrNotFound when the cluster has none.

func (*Postgres) RevokeTokenID added in v0.2.0

func (p *Postgres) RevokeTokenID(ctx context.Context, clusterName string, id int64) error

RevokeTokenID revokes the active token id of clusterName, or ErrNotFound when there is none (unknown id, another cluster's token, or already revoked). The cluster check guards against a mistyped id.

func (*Postgres) ScoreHistory

func (p *Postgres) ScoreHistory(ctx context.Context, clusterID int64, target string, limit int) ([]ScorePoint, error)

ScoreHistory returns score points for (cluster, target), oldest-first in insertion order (id). limit > 0 selects the most recent N rows (still returned oldest-first); limit <= 0 returns all. An unknown cluster or target yields an empty slice and nil error.

func (*Postgres) SetPruneTestHook added in v0.2.0

func (p *Postgres) SetPruneTestHook(batchRows int, onBatch func(PruneBatch))

SetPruneTestHook implements PruneTestHookSetter. Tests only.

func (*Postgres) UpsertCluster

func (p *Postgres) UpsertCluster(ctx context.Context, c Cluster) (int64, error)

UpsertCluster inserts the cluster or, if a row with the same name exists, bumps last_seen (first_seen never moves) and adopts c.ClusterUID when the stored one is empty. Once bound, any other UID is refused, an empty one included (no wildcard: a UID-less push may be another cluster). Zero LastSeen defaults to time.Now().UTC(), zero FirstSeen to LastSeen.

func (*Postgres) ValidReadToken added in v0.2.0

func (p *Postgres) ValidReadToken(ctx context.Context, token string) ([]string, bool, error)

ValidReadToken resolves a presented plaintext read token to its teams. Unknown or revoked tokens are (nil, false, nil) — not an error.

func (*Postgres) ValidToken

func (p *Postgres) ValidToken(ctx context.Context, token string) (string, bool, error)

ValidToken resolves a presented plaintext token to its cluster name. Unknown or revoked tokens are ("", false, nil) — not an error.

type PruneBaselines added in v0.2.0

type PruneBaselines map[int64][]string

PruneBaselines says, per cluster id, which targets' notification baselines (the newest decided or Baseline evaluation of a cluster and target) a Prune spares however old they are: a cluster's entry lists the targets its server still evaluates or may look back to for an upgrade; the baselines of its other targets age out like any evaluation. A cluster without an entry keeps every target's, as does a nil PruneBaselines.

type PruneBatch added in v0.2.0

type PruneBatch struct {
	Table string
	Rows  int64
}

PruneBatch is one committed retention transaction: the table it deleted from ("evaluations" or "snapshots") and how many rows. See PruneTestHookSetter.

type PruneResult added in v0.2.0

type PruneResult struct {
	Snapshots   int64
	Evaluations int64
}

PruneResult counts the rows one Prune deleted.

type PruneTestHookSetter added in v0.2.0

type PruneTestHookSetter interface {
	SetPruneTestHook(batchRows int, onBatch func(PruneBatch))
}

PruneTestHookSetter is implemented by SQLite and Postgres for tests only, and nothing outside a test should call it: SetPruneTestHook sets how many rows one retention transaction deletes (0 restores the default) and a hook called after each transaction that deleted rows has committed. Call it before Prune, not concurrently with it.

type ReadToken added in v0.2.0

type ReadToken struct {
	ID        int64      `json:"id"`
	Teams     []string   `json:"teams"` // sorted; [ReadScopeFleet] for fleet-wide
	Prefix    string     `json:"prefix"`
	CreatedAt time.Time  `json:"createdAt"`
	RevokedAt *time.Time `json:"revokedAt,omitempty"` // nil = active
}

ReadToken is a read token's metadata. The plaintext is never stored; Prefix is TokenPrefix of it, as for an ingest token.

type SQLite

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

SQLite is the Store implementation backed by a single SQLite database file (modernc.org/sqlite — pure Go, CGO-free).

func Open

func Open(path string) (*SQLite, error)

Open opens (creating if needed) the database at path and applies all embedded migrations. Every pooled connection gets WAL journaling, a 5s busy timeout and foreign-key enforcement via DSN pragmas.

The file opened is exactly path: the driver takes a "file:" URI, where '%', '?' and '#' are special, so sqliteDSN escapes them. A path with a NUL byte is refused, since SQLite would stop reading it at the NUL.

func (*SQLite) ClaimOutbox added in v0.2.0

func (s *SQLite) ClaimOutbox(ctx context.Context, now time.Time, lease time.Duration, limit int) ([]OutboxMessage, error)

ClaimOutbox leases up to limit due messages (next_attempt_at <= now), oldest first, in one statement.

func (*SQLite) Close

func (s *SQLite) Close() error

Close closes the underlying database.

func (*SQLite) ClusterByName added in v0.2.0

func (s *SQLite) ClusterByName(ctx context.Context, name string) (Cluster, error)

ClusterByName returns the cluster registered under name, or ErrNotFound.

func (*SQLite) ClustersOfTeams added in v0.2.0

func (s *SQLite) ClustersOfTeams(ctx context.Context, teams []string, teamMapHash string) ([]int64, error)

ClustersOfTeams returns the clusters whose current evaluations, written with teamMapHash, name one of teams, in one query: the teams travel as one JSON parameter, so their number is not bound by SQLite's parameter limit.

func (*SQLite) CommitEvaluations added in v0.2.0

func (s *SQLite) CommitEvaluations(ctx context.Context, b EvaluationBatch) (int64, bool, error)

CommitEvaluations writes b in one BEGIN IMMEDIATE transaction (the DSN's _txlock), which also serializes it against every other writer: the duplicate check and the Current/SnapshotID/Expect checks read state no one can change before the commit.

func (*SQLite) CreateReadToken added in v0.2.0

func (s *SQLite) CreateReadToken(ctx context.Context, teams []string, token string) (int64, error)

CreateReadToken stores a new active read token scoped to teams and returns its id; only the sha256 of token (plus TokenPrefix) is persisted.

func (*SQLite) CreateToken

func (s *SQLite) CreateToken(ctx context.Context, clusterName, token string) (int64, error)

CreateToken stores a new active ingest token for clusterName and returns its id; only the sha256 of token (plus TokenPrefix) is persisted. Fails if the token is already issued.

func (*SQLite) CurrentEvaluation added in v0.2.0

func (s *SQLite) CurrentEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)

CurrentEvaluation returns the newest evaluation for target of the cluster's latest snapshot (highest id), or ErrNotFound.

func (*SQLite) CurrentEvaluationSummary added in v0.2.0

func (s *SQLite) CurrentEvaluationSummary(ctx context.Context, clusterID int64, target string) (Evaluation, error)

CurrentEvaluationSummary is CurrentEvaluation without the report.

func (*SQLite) DeferOutbox added in v0.2.0

func (s *SQLite) DeferOutbox(ctx context.Context, id int64, next time.Time) error

DeferOutbox puts a claimed message back for later without counting the claim as an attempt, or returns ErrNotFound.

func (*SQLite) DeleteCluster added in v0.2.0

func (s *SQLite) DeleteCluster(ctx context.Context, name string) error

DeleteCluster removes the named cluster, its evaluations, snapshots, queued notifications and ingest tokens in one transaction, or returns ErrNotFound.

func (*SQLite) DeleteOutbox added in v0.2.0

func (s *SQLite) DeleteOutbox(ctx context.Context, id int64) error

DeleteOutbox removes message id, or returns ErrNotFound.

func (*SQLite) GetCluster

func (s *SQLite) GetCluster(ctx context.Context, id int64) (Cluster, error)

GetCluster returns the cluster by id, or ErrNotFound.

func (*SQLite) IngestTokenCluster added in v0.2.0

func (s *SQLite) IngestTokenCluster(ctx context.Context, token string) (string, int64, bool, error)

IngestTokenCluster resolves a presented plaintext token to its cluster name and the id registered under that name (0 for none yet), in one read: a rename moves the token and the name together.

func (*SQLite) InsertEvaluation

func (s *SQLite) InsertEvaluation(ctx context.Context, e Evaluation) (int64, error)

InsertEvaluation stores e. Zero CreatedAt defaults to now (UTC); zero EvaluatedAt to CreatedAt.

func (*SQLite) InsertSnapshot

func (s *SQLite) InsertSnapshot(ctx context.Context, snap Snapshot) (int64, bool, error)

InsertSnapshot stores snap unless its hash equals the hash of the cluster's LATEST snapshot, in which case it returns (latestID, true, nil) without writing. An older same-hash snapshot superseded by a different one does NOT count as a duplicate. Zero ReceivedAt defaults to now (UTC). It is CommitEvaluations with nothing but the snapshot.

func (*SQLite) Kind added in v0.2.0

func (s *SQLite) Kind() string

Kind names the store in metrics: "sqlite".

func (*SQLite) LatestEvaluation

func (s *SQLite) LatestEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)

LatestEvaluation returns the newest evaluation for (cluster, target) by insertion order (highest id; never created_at, which a clock step can reorder), or ErrNotFound.

func (*SQLite) LatestKnownEvaluation added in v0.2.0

func (s *SQLite) LatestKnownEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)

LatestKnownEvaluation returns the newest evaluation for (cluster, target) that is ready, has a blocker, or is marked a baseline, or ErrNotFound.

func (*SQLite) LatestSnapshot

func (s *SQLite) LatestSnapshot(ctx context.Context, clusterID int64) (Snapshot, error)

LatestSnapshot returns the most recently inserted snapshot for the cluster (highest id), or ErrNotFound.

func (*SQLite) LatestSnapshotHead added in v0.2.0

func (s *SQLite) LatestSnapshotHead(ctx context.Context, clusterID int64) (Snapshot, error)

LatestSnapshotHead is LatestSnapshot without the inventory.

func (*SQLite) LatestSnapshotHeads added in v0.2.0

func (s *SQLite) LatestSnapshotHeads(ctx context.Context) (map[int64]Snapshot, error)

LatestSnapshotHeads returns every cluster's latest snapshot without its inventory, in one query: per cluster, one step down idx_snapshots_cluster_id from its end, so the cost follows the clusters, not every snapshot kept.

func (*SQLite) ListClusters

func (s *SQLite) ListClusters(ctx context.Context) ([]Cluster, error)

ListClusters returns all clusters, ascending by name.

func (*SQLite) ListReadTokens added in v0.2.0

func (s *SQLite) ListReadTokens(ctx context.Context) ([]ReadToken, error)

ListReadTokens returns every read token's metadata, ascending by id.

func (*SQLite) ListTokens added in v0.2.0

func (s *SQLite) ListTokens(ctx context.Context, clusterName string) ([]Token, error)

ListTokens returns token metadata, ascending by id, for clusterName or for every cluster when clusterName is "".

func (*SQLite) Ping added in v0.2.0

func (s *SQLite) Ping(ctx context.Context) error

Ping checks the database answers (the server's /readyz).

func (*SQLite) Prune added in v0.2.0

func (s *SQLite) Prune(ctx context.Context, cutoff time.Time, baselines PruneBaselines) (PruneResult, error)

Prune deletes evaluations created before cutoff, then the snapshots received before it that no evaluation refers to any more, sparing each cluster's latest snapshot and its evaluations and each (cluster, target)'s newest baseline (decided or Baseline), then those baselines baselines does not spare, in bounded batches of one transaction each (prune.go). Stored times are fixed-width UTC strings, so string order is instant order.

It does not run PRAGMA incremental_vacuum or VACUUM: the file keeps its size and SQLite reuses the freed pages (docs/operations/retention-and-backup.md).

func (*SQLite) RenameCluster added in v0.2.0

func (s *SQLite) RenameCluster(ctx context.Context, name, newName string) error

RenameCluster renames the cluster and re-binds its ingest tokens to the new name in one transaction. The write lock (BEGIN IMMEDIATE) makes the taken-name check race-free.

func (*SQLite) RescheduleOutbox added in v0.2.0

func (s *SQLite) RescheduleOutbox(ctx context.Context, id int64, next time.Time, lastErr string) error

RescheduleOutbox records a failed attempt and when to try again, or returns ErrNotFound.

func (*SQLite) RevokeReadToken added in v0.2.0

func (s *SQLite) RevokeReadToken(ctx context.Context, id int64) error

RevokeReadToken revokes the active read token id, or ErrNotFound when there is none (unknown id, or already revoked).

func (*SQLite) RevokeToken

func (s *SQLite) RevokeToken(ctx context.Context, clusterName string) error

RevokeToken revokes every active token of clusterName, or ErrNotFound when the cluster has none.

func (*SQLite) RevokeTokenID added in v0.2.0

func (s *SQLite) RevokeTokenID(ctx context.Context, clusterName string, id int64) error

RevokeTokenID revokes the active token id of clusterName, or ErrNotFound when there is none (unknown id, another cluster's token, or already revoked). The cluster check guards against a mistyped id.

func (*SQLite) ScoreHistory

func (s *SQLite) ScoreHistory(ctx context.Context, clusterID int64, target string, limit int) ([]ScorePoint, error)

ScoreHistory returns score points for (cluster, target), oldest-first in insertion order (id). limit > 0 selects the most recent N rows (still returned oldest-first); limit <= 0 returns all. An unknown cluster or target yields an empty slice and nil error.

func (*SQLite) SetPruneTestHook added in v0.2.0

func (s *SQLite) SetPruneTestHook(batchRows int, onBatch func(PruneBatch))

SetPruneTestHook implements PruneTestHookSetter. Tests only.

func (*SQLite) UpsertCluster

func (s *SQLite) UpsertCluster(ctx context.Context, c Cluster) (int64, error)

UpsertCluster inserts the cluster or, if a row with the same name exists, bumps last_seen (first_seen never moves) and adopts c.ClusterUID when the stored one is empty. Once bound, any other UID is refused, an empty one included (no wildcard: a UID-less push may be another cluster). Zero LastSeen defaults to time.Now().UTC(), zero FirstSeen to LastSeen.

func (*SQLite) ValidReadToken added in v0.2.0

func (s *SQLite) ValidReadToken(ctx context.Context, token string) ([]string, bool, error)

ValidReadToken resolves a presented plaintext read token to its teams. Unknown or revoked tokens are (nil, false, nil) — not an error.

func (*SQLite) ValidToken

func (s *SQLite) ValidToken(ctx context.Context, token string) (string, bool, error)

ValidToken resolves a presented plaintext token to its cluster name. Unknown or revoked tokens are ("", false, nil) — not an error.

type ScorePoint

type ScorePoint struct {
	At    time.Time `json:"at"`
	Score int       `json:"score"`
	Ready bool      `json:"ready"`
	// Verdict is the evaluation's verdict: ready, blocked (at least one
	// blocker) or unknown (no blocker, but not ready). A score alone cannot
	// tell unknown from ready: an evaluation whose required check did not
	// run can score 100. Derived from the row (engine.StoredVerdict), so every
	// stored evaluation has one; a client of an older server gets none.
	Verdict string `json:"verdict,omitempty"`
}

ScorePoint is one evaluation in a cluster's score history.

type Snapshot

type Snapshot struct {
	ID           int64     `json:"id"`
	ClusterID    int64     `json:"clusterId"`
	Hash         string    `json:"hash"` // sha256 of canonical inventory JSON
	KBVersion    string    `json:"kbVersion"`
	AgentVersion string    `json:"agentVersion"`
	ReceivedAt   time.Time `json:"receivedAt"`
	// ServerVersion is the Kubernetes version the snapshot is judged at:
	// its inventory's own serverVersion, or — for a degraded push that
	// reported none — the version of the snapshot before it, so the
	// cluster keeps its default target. "" on rows stored before the
	// column existed (read the inventory's) and when no version was ever
	// known.
	ServerVersion string `json:"serverVersion,omitempty"`
	Inventory     []byte `json:"-"` // the inventory JSON exactly as pushed
}

type Store

type Store interface {
	// UpsertCluster registers or touches a cluster by name and returns its
	// id. A name is bound to the first non-empty ClusterUID pushed under
	// it: a different non-empty UID fails with *ClusterUIDConflictError and
	// writes nothing, and so does an empty UID once one is bound (a push that
	// cannot say which cluster it is must not join a bound history).
	UpsertCluster(ctx context.Context, c Cluster) (int64, error)
	// ClusterByName returns the cluster registered under name, or
	// ErrNotFound. It never creates one.
	ClusterByName(ctx context.Context, name string) (Cluster, error)
	// DeleteCluster removes the named cluster with everything that is its
	// own: snapshots, evaluations, queued notifications and the ingest
	// tokens minted for its name (ErrNotFound when unknown). A rebuilt
	// cluster that re-registers the name needs a new token.
	DeleteCluster(ctx context.Context, name string) error
	// RenameCluster renames a cluster; its history and its ingest tokens
	// move with it. ErrNotFound when name is unknown, ErrClusterNameTaken
	// when newName is registered to another cluster. Renaming a cluster to
	// its own name is a no-op.
	RenameCluster(ctx context.Context, name, newName string) error
	// Prune is retention: it deletes evaluations created before cutoff and
	// then snapshots received before it that no evaluation refers to any
	// more, except each cluster's latest snapshot and its evaluations (the
	// cluster's current state, however old) and each (cluster, target)'s
	// newest notification baseline (LatestKnownEvaluation: decided, or
	// marked Baseline; of the target itself or of an upgrade), with its
	// snapshot.
	// baselines limits that last exception to the targets still in use
	// (PruneBaselines); nil spares every baseline. Tokens, clusters and the
	// outbox are not touched.
	Prune(ctx context.Context, cutoff time.Time, baselines PruneBaselines) (PruneResult, error)

	InsertSnapshot(ctx context.Context, s Snapshot) (int64, bool, error) // (id, duplicate, err) — duplicate iff same cluster+hash as latest
	LatestSnapshot(ctx context.Context, clusterID int64) (Snapshot, error)
	// LatestSnapshotHead is LatestSnapshot without Inventory (nil): a
	// push compares its hash and reads its server version, and the
	// inventory is up to --max-snapshot-bytes.
	LatestSnapshotHead(ctx context.Context, clusterID int64) (Snapshot, error)
	// LatestSnapshotHeads returns every cluster's latest snapshot, keyed by
	// cluster id, without Inventory (nil): fleet views need the id and
	// server version of each, not hundreds of inventory blobs. Clusters
	// without a snapshot are absent.
	LatestSnapshotHeads(ctx context.Context) (map[int64]Snapshot, error)
	ListClusters(ctx context.Context) ([]Cluster, error)
	GetCluster(ctx context.Context, id int64) (Cluster, error)
	InsertEvaluation(ctx context.Context, e Evaluation) (int64, error)
	// LatestEvaluation is the newest evaluation for (cluster, target) from
	// any snapshot — history, not the cluster's current state.
	LatestEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)
	// CurrentEvaluation is the newest evaluation for target of the
	// cluster's LATEST snapshot, or ErrNotFound — an evaluation of an
	// older snapshot describes an inventory the cluster no longer has.
	CurrentEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)
	// CurrentEvaluationSummary is CurrentEvaluation without the report
	// (Report nil): the columns and NotAssessed. The read API's summaries
	// of every cluster (cluster list, fleet matrix, metrics) use it, so
	// their cost never depends on how large a report is.
	CurrentEvaluationSummary(ctx context.Context, clusterID int64, target string) (Evaluation, error)
	// LatestKnownEvaluation is the newest notification baseline for
	// (cluster, target): an evaluation whose verdict was decided — ready,
	// or at least one blocker — or one written with Baseline set, skipping
	// the other "unknown" ones (no blockers, and a required check not
	// assessed that may hide one).
	LatestKnownEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)
	ScoreHistory(ctx context.Context, clusterID int64, target string, limit int) ([]ScorePoint, error)

	// CommitEvaluations writes one evaluation pass atomically: the snapshot
	// (when b.Snapshot is set), every insert and refresh, and the outbox
	// messages, or nothing. It returns the evaluated snapshot's id.
	// duplicate is true when b.Snapshot has the same hash as the cluster's
	// latest snapshot: then no snapshot, evaluation or outbox row is
	// written, the push's envelope (KBVersion, AgentVersion) is recorded
	// on the latest snapshot, and the latest id is returned. With
	// b.Cluster set, the cluster is registered or touched in the same
	// transaction, so a failed commit leaves no cluster row and no
	// last-seen bump behind. ErrConflict means another writer moved the
	// cluster on (b.SnapshotID is no longer latest, b.Current no longer
	// matches, or b.Expect no longer holds); *ClusterUIDConflictError that
	// b.Cluster's UID is refused.
	CommitEvaluations(ctx context.Context, b EvaluationBatch) (snapshotID int64, duplicate bool, err error)

	// Notification outbox: messages committed with their evaluations,
	// delivered by a worker after commit. ClaimOutbox returns up to limit
	// messages due at now, oldest first, and leases them (attempts+1,
	// next attempt at now+lease) so a crashed delivery is retried and
	// concurrent workers do not deliver one message twice.
	ClaimOutbox(ctx context.Context, now time.Time, lease time.Duration, limit int) ([]OutboxMessage, error)
	DeleteOutbox(ctx context.Context, id int64) error                                     // delivered or given up; ErrNotFound when gone
	RescheduleOutbox(ctx context.Context, id int64, next time.Time, lastErr string) error // failed attempt; ErrNotFound when gone
	// DeferOutbox puts a claimed message back, due at next, for a delivery
	// that was never tried: the attempt the claim counted is given back
	// (attempts-1, never below 0) and last_error is left alone. ErrNotFound
	// when gone.
	DeferOutbox(ctx context.Context, id int64, next time.Time) error

	// Per-cluster ingest tokens (P3, spec §8). Tokens are keyed by cluster
	// NAME (not id): a token may be minted before the cluster's first push
	// registers it. Only the sha256 of the plaintext is ever stored.
	CreateToken(ctx context.Context, clusterName, token string) (int64, error) // returns the token id; errors if the token is already issued (any cluster)
	ValidToken(ctx context.Context, token string) (string, bool, error)        // (clusterName, true) for active; ("", false, nil) for unknown/revoked
	ListTokens(ctx context.Context, clusterName string) ([]Token, error)       // active and revoked, ascending id; "" = every cluster
	RevokeTokenID(ctx context.Context, clusterName string, id int64) error     // revokes one active token of clusterName; ErrNotFound otherwise
	RevokeToken(ctx context.Context, clusterName string) error                 // revokes ALL active tokens; ErrNotFound when none are active
	// IngestTokenCluster is ValidToken plus, in the same read, the id of
	// the cluster registered under the token's name: 0 when none is yet
	// (a token minted before the first push). Ingest authenticates with
	// it, so a push knows from the start which cluster it may write to,
	// and a rename or delete after that is a conflict, not a revoke.
	IngestTokenCluster(ctx context.Context, token string) (clusterName string, clusterID int64, ok bool, err error)

	// Read tokens: bearer tokens for the read API, each scoped to a set of
	// team names, or to ReadScopeFleet ("*") for the whole fleet. Like
	// ingest tokens, only the sha256 of the plaintext and its prefix are
	// stored, in a table of their own: an ingest token never reads, and a
	// read token never pushes. Never deleted, only revoked, so the server
	// can tell a database where read tokens were ever minted (it then
	// requires one) from one where none were.
	CreateReadToken(ctx context.Context, teams []string, token string) (int64, error) // returns the token id; errors on no teams, or if the token is already issued
	ValidReadToken(ctx context.Context, token string) ([]string, bool, error)         // (teams, sorted, true) for active; (nil, false, nil) for unknown/revoked
	ListReadTokens(ctx context.Context) ([]ReadToken, error)                          // active and revoked, ascending id
	RevokeReadToken(ctx context.Context, id int64) error                              // revokes one active read token; ErrNotFound otherwise

	// ClustersOfTeams returns, ascending, the ids of the clusters whose
	// current evaluations (each target's newest of the cluster's latest
	// snapshot) were written with teamMapHash (Evaluation.TeamMapHash, the
	// server's current --team-map) and name at least one of teams in their
	// Teams: the clusters a read token scoped to those teams reads. An
	// evaluation written with another team map says which teams owned the
	// cluster's namespaces then, not now: the row of a target no longer
	// evaluated (a removed --targets entry) is never rewritten, and a
	// current target's is until the next pass rewrites it, so neither
	// counts. One query, whatever the fleet's size; nothing is returned
	// for no teams.
	ClustersOfTeams(ctx context.Context, teams []string, teamMapHash string) ([]int64, error)

	Close() error
}

Store is the persistence contract. SQLite implements it in P2; P3 adds Postgres. Behavioral semantics are pinned by storetest.RunStoreConformance.

type Token added in v0.2.0

type Token struct {
	ID          int64      `json:"id"`
	ClusterName string     `json:"clusterName"`
	Prefix      string     `json:"prefix"`
	CreatedAt   time.Time  `json:"createdAt"`
	RevokedAt   *time.Time `json:"revokedAt,omitempty"` // nil = active
}

Token is a per-cluster ingest token's metadata. The plaintext is never stored; Prefix lets an operator match a listed token to the secret they deployed (see TokenPrefix).

Directories

Path Synopsis
Package storetest pins the behavioral contract of store.Store.
Package storetest pins the behavioral contract of store.Store.

Jump to

Keyboard shortcuts

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