store

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2026 License: Apache-2.0 Imports: 12 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

This section is empty.

Variables

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

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

Functions

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 migrate with postgresMigrations. applied_at stays TEXT (RFC 3339) in both backends — it is bookkeeping written and read only by this file.

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 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
	CreatedAt  time.Time `json:"createdAt"`
}

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(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.

func (*Postgres) Close

func (p *Postgres) Close() error

Close closes the underlying connection pool.

func (*Postgres) CreateToken

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

CreateToken stores a new active ingest token for clusterName; only the sha256 of token is persisted. Fails if the token is already issued.

func (*Postgres) GetCluster

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

GetCluster returns the cluster by id, or ErrNotFound.

func (*Postgres) InsertEvaluation

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

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

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

Concurrency: the read-latest → insert pair must be serialized per cluster or two racing pushes of the same hash both miss the duplicate and insert twice (READ COMMITTED gives no protection — both SELECTs see the same "latest"). Locking the parent clusters row FOR UPDATE serializes writers of one cluster without blocking other clusters.

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 created_at (ties broken by id), 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) ListClusters

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

ListClusters returns all clusters, ascending by name.

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) 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 ascending by created_at. 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) 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, updates cluster_uid and last_seen (first_seen never moves). Zero FirstSeen/LastSeen default to time.Now().UTC().

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

path must not contain '?' or '#' — it is interpolated into a SQLite URI, where either character corrupts the path.

func (*SQLite) Close

func (s *SQLite) Close() error

Close closes the underlying database.

func (*SQLite) CreateToken

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

CreateToken stores a new active ingest token for clusterName; only the sha256 of token is persisted. Fails if the token is already issued.

func (*SQLite) GetCluster

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

GetCluster returns the cluster by id, or ErrNotFound.

func (*SQLite) InsertEvaluation

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

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

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

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 created_at (ties broken by id), 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) ListClusters

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

ListClusters returns all clusters, ascending by name.

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) 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 ascending by created_at. 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) 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, updates cluster_uid and last_seen (first_seen never moves). Zero FirstSeen/LastSeen default to time.Now().UTC().

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"`
}

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"`
	Inventory    []byte    `json:"-"` // raw canonical JSON
}

type Store

type Store interface {
	UpsertCluster(ctx context.Context, c Cluster) (int64, error)         // by name; returns id
	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)
	ListClusters(ctx context.Context) ([]Cluster, error)
	GetCluster(ctx context.Context, id int64) (Cluster, error)
	InsertEvaluation(ctx context.Context, e Evaluation) (int64, error)
	LatestEvaluation(ctx context.Context, clusterID int64, target string) (Evaluation, error)
	ScoreHistory(ctx context.Context, clusterID int64, target string, limit int) ([]ScorePoint, 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) error   // 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
	RevokeToken(ctx context.Context, clusterName string) error          // revokes ALL active tokens; ErrNotFound when none are active

	Close() error
}

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

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