database

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT 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 database provides the SQLite-backed persistence layer for the takt server.

The database stores desired state — what the operator asked for — and the events the server recorded while converging towards it. What is actually running is observed from the driver on demand, so no row here describes the present and none can go stale against reality. An event says what was true when it was written, which is a claim about the past and stays true.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoSnapshotSource is returned when there is no database at the path to
	// snapshot.
	ErrNoSnapshotSource = errors.New("database to snapshot does not exist")
	// ErrSnapshotExists is returned when something is already at the destination.
	ErrSnapshotExists = errors.New("snapshot already exists")
)
View Source
var (
	// ErrNoCurrentKey is returned when the database records no current encryption
	// key.
	ErrNoCurrentKey = errors.New("no current encryption key")
	// ErrSecretsSealed is returned when the current key cannot be replaced because
	// secrets are sealed under it.
	ErrSecretsSealed = errors.New("secrets are sealed under the current encryption key")
)
View Source
var (
	// ErrNoPolicy is returned when no policy document has been applied yet.
	ErrNoPolicy = errors.New("no policy")
	// ErrPolicyChanged is returned when the policy an apply was conditioned on
	// is not the policy the database holds.
	ErrPolicyChanged = errors.New("policy changed since it was read")
)
View Source
var (
	// ErrSecretNotFound is returned when no secret exists with the requested name.
	ErrSecretNotFound = errors.New("secret not found")
	// ErrSecretsChanged is returned when the secrets a rekey was asked to rewrite
	// are not the secrets the database holds.
	ErrSecretsChanged = errors.New("secrets changed during the rekey")
	// ErrSecretChanged is returned when the secret a set was conditioned on is not
	// the secret the database holds.
	ErrSecretChanged = errors.New("secret changed since it was read")
)
View Source
var (
	// ErrServiceNotFound is returned when no service exists with the requested name.
	ErrServiceNotFound = errors.New("service not found")
	// ErrServiceChanged is returned when the service an apply was conditioned on is
	// not the service the database holds.
	ErrServiceChanged = errors.New("service changed since it was read")
)
View Source
var (
	// ErrTokenNotFound is returned when no token exists with the requested
	// identifier or hash.
	ErrTokenNotFound = errors.New("token not found")
	// ErrTokenAlreadyExists is returned when a token collides with one the
	// database already holds, which in practice means a second recovery token.
	ErrTokenAlreadyExists = errors.New("token already exists")
)
View Source
var (
	// ErrVariableNotFound is returned when no variable exists with the requested name.
	ErrVariableNotFound = errors.New("variable not found")
	// ErrVariableChanged is returned when the variable a set was conditioned on is
	// not the variable the database holds.
	ErrVariableChanged = errors.New("variable changed since it was read")
)
View Source
var (
	// ErrVolumeNotFound is returned when no volume exists with the requested name.
	ErrVolumeNotFound = errors.New("volume not found")
	// ErrVolumeChanged is returned when the volume an apply was conditioned on is
	// not the volume the database holds.
	ErrVolumeChanged = errors.New("volume changed since it was read")
)
View Source
var (
	// ErrWorkloadNotFound is returned when no workload exists with the requested name.
	ErrWorkloadNotFound = errors.New("workload not found")
	// ErrWorkloadDeleting is returned when a write reaches a workload that is
	// marked for deletion.
	ErrWorkloadDeleting = errors.New("workload is being deleted")
	// ErrWorkloadReferenced is returned when a delete is refused because another
	// workload references the one being deleted.
	ErrWorkloadReferenced = errors.New("workload is referenced")
	// ErrWorkloadChanged is returned when the workload an apply was conditioned on
	// is not the workload the database holds.
	ErrWorkloadChanged = errors.New("workload changed since it was read")
)
View Source
var (
	// ErrHostPortTaken is returned when a host port is already allocated to another
	// workload.
	ErrHostPortTaken = errors.New("host port already allocated")
)
View Source
var (
	// ErrInvalidQueryPath is returned when a query names a path SQLite cannot parse.
	ErrInvalidQueryPath = errors.New("invalid query path")
)

Functions

func IsUniqueError

func IsUniqueError(err error) bool

IsUniqueError reports whether err is a unique-key or primary-key constraint violation.

func Open

func Open(ctx context.Context, config Config) (*sql.DB, error)

Open opens (or creates) the SQLite database at the path in config and runs any pending migrations. The returned pool must be closed by the caller when no longer needed.

func Snapshot

func Snapshot(ctx context.Context, source, destination string) error

Snapshot writes a consistent copy of the database at source to destination.

A running server keeps its committed state spread across the database, its write-ahead log and its shared-memory index, so copying the database file alone produces one that is stale or torn. It fails quietly: SQLite opens the result happily and the missing transactions are noticed later, if at all. VACUUM INTO is one statement that produces a single consistent, compacted file from a live connection.

The destination must not exist. SQLite refuses to overwrite one, and left to surface on its own that reads as an unexplained failure on the second run rather than as the safety property it is.

Types

type Config

type Config struct {
	// The logger used for database lifecycle events.
	Logger *slog.Logger
	// The filesystem path to the SQLite database file.
	Path string
	// The provider connection pool metrics are created from. May be nil, in
	// which case nothing is recorded.
	MeterProvider metric.MeterProvider
	// The provider query spans are created from. May be nil, in which case no
	// spans are recorded.
	TracerProvider trace.TracerProvider
}

The Config type contains fields used to open the database.

type EncryptionKey

type EncryptionKey struct {
	// The identifier naming the key in the keyring.
	ID string
	// Whether new secrets are sealed under this key. Exactly one key is
	// current, enforced by the schema.
	IsCurrent bool
	// The time the key was recorded.
	CreatedAt time.Time
}

The EncryptionKey type records a key a secret's value is sealed under.

The key itself is not here. The database records which key sealed what, and the keyring on disk holds the bytes, which is what keeps a copy of the database useless to anyone without the keys.

type EncryptionKeyRepository

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

The EncryptionKeyRepository type provides persistence operations for the encryption key domain.

func NewEncryptionKeyRepository

func NewEncryptionKeyRepository(db *sql.DB) *EncryptionKeyRepository

NewEncryptionKeyRepository returns an EncryptionKeyRepository backed by the given database.

func (*EncryptionKeyRepository) Adopt

Adopt records the given key as the current one, which is how a server with an empty database takes ownership of the key it just generated.

Refused when a current key is already recorded. Two servers starting against one database would otherwise each generate a key and seal secrets under different ones.

func (*EncryptionKeyRepository) Current

Current returns the key new secrets are sealed under, reporting ErrNoCurrentKey when the database records none.

func (*EncryptionKeyRepository) List

List returns every key the database records, newest first.

func (*EncryptionKeyRepository) Replace added in v0.12.0

func (r *EncryptionKeyRepository) Replace(ctx context.Context, id string) error

Replace records the given key as the current one in place of the key recorded now, which is how a server whose keyring lost the current key starts again when nothing was sealed under it.

Refused when any secret exists. A secret is sealed under the current key, so replacing that key while one is held would leave the value unopenable and the database saying otherwise. The count is taken inside the transaction, so a secret set between the caller's check and here is refused rather than orphaned. The replaced key's row is kept, demoted, the way a rekey keeps the key it retired.

type Policy added in v0.5.0

type Policy struct {
	// The canonical form of the document, as the server stores and
	// returns it.
	Document []byte
	// How many times the policy has been written. This is the entity tag a
	// conditional apply compares against, and it moves only when an apply
	// changed the document. Before any apply there is no row, which a
	// caller reads as version zero.
	Version int
	// The time the document was last applied.
	UpdatedAt time.Time
}

The Policy type represents the applied access-control policy document.

type PolicyRepository added in v0.5.0

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

The PolicyRepository type provides persistence operations for the policy domain.

func NewPolicyRepository added in v0.5.0

func NewPolicyRepository(db *sql.DB) *PolicyRepository

NewPolicyRepository returns a PolicyRepository backed by the given database.

func (*PolicyRepository) Apply added in v0.5.0

func (r *PolicyRepository) Apply(ctx context.Context, document []byte, ifMatch int) (Policy, error)

Apply replaces the policy with the given document, on the condition that the stored version is still ifMatch. Zero names the state before any apply, where no row exists, so a first apply is conditioned the same way every later one is.

Reporting ErrPolicyChanged on a mismatch is what turns two concurrent applies into one winner and one refusal, rather than a silent overwrite.

A document identical to the stored one is not written, so re-applying the same file leaves the version where it is and the tag a pipeline holds stays good. Returns the policy as stored, which is what a get would now report.

func (*PolicyRepository) Get added in v0.5.0

func (r *PolicyRepository) Get(ctx context.Context) (Policy, error)

Get returns the applied policy, reporting ErrNoPolicy when none has been applied yet.

type Port

type Port struct {
	// The identifier of the workload the port belongs to.
	WorkloadID string
	// The index of the workload instance the port is allocated to. Instances
	// are numbered from zero, so a workload running one instance allocates
	// only instance zero.
	Instance int
	// What the specification called the port, which is how the rest of a
	// manifest refers to it. Empty for a port the specification did not name.
	Name string
	// The port the workload listens on inside its runtime.
	Container int
	// The host port that reaches it.
	Host int
	// The transport protocol the port is published on. TCP and UDP are separate
	// address spaces, so it is part of the allocation's identity rather than a
	// detail of it.
	Protocol string
	// Whether the host port was allocated by the server rather than pinned by
	// the specification. A dynamic port may be reallocated if it proves
	// unusable. A pinned one may not.
	Dynamic bool
}

The Port type represents a host port allocated to a workload.

An allocation is desired state: it records the decision that a given host port should reach a given port inside the workload, which is why it is persisted rather than observed. The port a runtime happens to have bound is observed from the driver, and the two agreeing is what the reconciler converges on.

type PortRepository

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

The PortRepository type provides persistence operations for the port allocation domain.

func NewPortRepository

func NewPortRepository(db *sql.DB) *PortRepository

NewPortRepository returns a PortRepository backed by the given database.

func (*PortRepository) Allocated

func (r *PortRepository) Allocated(ctx context.Context) (map[string][]int, error)

Allocated returns every host port currently allocated to any workload, keyed by the protocol it is allocated on, which the allocator uses to avoid handing out a port takt already promised.

Keyed rather than flat, because the two protocols are separate address spaces: a single list would have 20000/tcp rule out 20000/udp, and takt would refuse a port that is genuinely free.

func (*PortRepository) Claim

func (r *PortRepository) Claim(ctx context.Context, workloadID string, ports []Port) error

Claim records the given ports as allocated to the workload with the given identifier, replacing whatever was allocated to it before.

Replacing wholesale rather than merging keeps the stored allocation an exact description of the workload's current port list: a port removed from a specification releases its allocation as a consequence of no longer being claimed. Returns ErrHostPortTaken when one of the host ports is allocated to a different workload.

func (*PortRepository) HolderOf

func (r *PortRepository) HolderOf(ctx context.Context, host int, protocol string) (string, bool, error)

HolderOf returns the name of the workload the given host port is allocated to, reporting false when no workload holds it.

The name rather than the identifier, because the answer exists to be reported to whoever asked for the port: an identifier they never see would tell them nothing.

This is what lets a pinned host port be rejected while the request is still in flight, rather than the workload being accepted and then failing to start.

func (*PortRepository) List

func (r *PortRepository) List(ctx context.Context, workloadID string) ([]Port, error)

List returns the ports allocated to the workload with the given identifier, ordered by the port inside the workload so that the result is stable.

func (*PortRepository) ListAll

func (r *PortRepository) ListAll(ctx context.Context) (map[string][]Port, error)

ListAll returns the ports allocated to every workload, keyed by workload identifier.

This exists so that listing workloads costs one query rather than one per workload: the per-workload form is fine for a single read but turns a list of two hundred workloads into two hundred round trips.

func (*PortRepository) Release

func (r *PortRepository) Release(ctx context.Context, workloadID string) error

Release removes every port allocated to the workload with the given identifier.

Deleting a workload releases its ports by cascade, so this exists for releasing them while the workload itself stays.

type Query

type Query struct {
	// The JSON path into the resource, such as "$.labels.app".
	Path string
	// The value the path must hold, compared as text.
	Value string
}

The Query type matches rows whose stored JSON has the given value at the given path.

The path is a SQLite JSON path. For a workload it is a path into the whole stored specification, so a query can reach anything the specification holds — including labels, which live under $.labels. A volume, secret or variable stores only labels, and its queries reach them under the same $.labels root. One path syntax then works across every resource.

type Secret

type Secret struct {
	// The identifier the server assigns to the secret.
	ID string
	// The name that identifies the secret, and which a manifest references.
	Name string
	// The encrypted value. Empty on a secret that was read without it, since
	// most reads have no business decrypting one.
	Value []byte
	// The identifier of the key the value is sealed under.
	KeyID string
	// Changes whenever the value changes, and never otherwise.
	//
	// This is what a referencing workload's specification hash is mixed with, so
	// that rotating a secret replaces the instances reading it. The value itself
	// is not part of that hash: a hash is reported by the API, and one computed
	// over a value would confirm a guess at it.
	Revision string
	// Arbitrary key-value pairs attached to the secret.
	//
	// Readable back, where the value deliberately is not. A label on a secret is
	// as public as the secret's name.
	Labels map[string]string
	// How many times the secret has been written, by its value or its labels.
	// This is the entity tag a conditional set compares against. A rekey does not
	// move it, for the same reason it does not move the revision: it changes how
	// the value is stored, not what the caller set.
	Version int
	// The time the secret was created.
	CreatedAt time.Time
	// The time the secret last changed, by its value or its labels. The revision
	// is what says the value moved.
	UpdatedAt time.Time
}

The Secret type represents a value a workload can read but an operator cannot, stored encrypted.

The value never leaves the database in the clear except to be handed to a workload that is starting. Nothing reports it back to a caller, which is what makes the encrypted column the only copy takt keeps.

type SecretRepository

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

The SecretRepository type provides persistence operations for the secret domain.

func NewSecretRepository

func NewSecretRepository(db *sql.DB) *SecretRepository

NewSecretRepository returns a SecretRepository backed by the given database.

func (*SecretRepository) Delete

func (r *SecretRepository) Delete(ctx context.Context, name string) error

Delete removes the secret with the given name, reporting ErrSecretNotFound when no such secret exists.

The links naming it are left behind. A workload that references a deleted secret still has to report what it is missing, and re-creating the secret has to move that workload's hash again.

func (*SecretRepository) Get

func (r *SecretRepository) Get(ctx context.Context, name string) (Secret, error)

Get returns the secret with the given name, including its encrypted value, reporting ErrSecretNotFound when no such secret exists.

func (*SecretRepository) List

func (r *SecretRepository) List(ctx context.Context, queries ...Query) ([]Secret, error)

List returns the secrets matching every one of the given queries, ordered by name so that the result is stable. Passing no queries returns every secret.

A query's path reaches the secret's labels under $.labels, the same way a workload query does. The filter never sees a value. A query can reach only the labels, so it cannot probe what a secret holds. Returns ErrInvalidQueryPath when a query names a path SQLite cannot parse.

The values are left behind. Listing secrets is how an operator finds out what exists, which needs no decryption, and a read that does not carry a value cannot leak one.

func (*SecretRepository) ListSealed

func (r *SecretRepository) ListSealed(ctx context.Context) ([]Secret, error)

ListSealed returns every secret including its value and the key that sealed it, ordered by name.

Unlike List, this carries the ciphertext. Only a rekey has business reading every sealed value at once, which is why the ordinary listing leaves it out.

func (*SecretRepository) Rekey

func (r *SecretRepository) Rekey(ctx context.Context, keyID string, sealed map[string][]byte) error

Rekey replaces every secret's sealed value with the one given for it and records keyID as the key they are now sealed under, in one transaction.

This is what makes a rekey safe to interrupt. The re-sealed values and the pointer to the current key move together, so a process that dies leaves either every secret under the old key or every secret under the new one. There is no state where the database and the keyring disagree about which key opens what, and so nothing to reconcile afterwards.

The sealed values are keyed by secret name. A name with no entry is left alone, which cannot happen when the caller passes back what ListSealed gave it, and would mean a partial rekey if it did — so it is refused rather than skipped.

The revision does not move. A rekey changes how a value is stored, not what it is, so nothing referencing a secret is redeployed by one.

func (*SecretRepository) Revisions

func (r *SecretRepository) Revisions(ctx context.Context, names []string) (map[string]string, error)

Revisions returns the current revision of each named secret, keyed by name.

A name that no secret holds is absent from the result rather than an error: the caller knows which names it asked about, and deciding what a missing secret means is its business. One query rather than one per name, so that hashing a workload costs the same however many secrets it reads.

func (*SecretRepository) Upsert

func (r *SecretRepository) Upsert(ctx context.Context, secret Secret, ifMatch int) (Secret, error)

Upsert stores the given secret, returning it as stored. The given secret's identifier, version and timestamps are ignored: all of them are this repository's to hand out.

The write is unconditional on the content: whether the value actually changed is the caller's to decide, because only the caller can decrypt what is already there to compare. Calling this at all therefore means the secret moved, and the revision on it is the one the value now carries.

A non-zero ifMatch conditions the write on the stored version still being that one, reporting ErrSecretChanged when it is not and ErrSecretNotFound when there is no row to have the version at all. Zero writes unconditionally, which is what a caller creating a secret has to do: there is no version yet to name.

The creation time is preserved on a secret that already existed, so rotating one does not read as creating it again.

func (*SecretRepository) UsedBy

func (r *SecretRepository) UsedBy(ctx context.Context, name string) ([]string, error)

UsedBy returns the names of the workloads referencing the secret with the given name.

Read from the recorded links rather than by matching the reference text inside each stored specification, so the answer does not depend on how a reference is written or on where in a manifest one is allowed.

A workload being deleted still counts. Its instances run until the reconciler has torn them down, so a secret it reads is still in use.

type Service

type Service struct {
	// The identifier the server assigns to the service.
	ID string
	// The name that identifies the service.
	Name string
	// Arbitrary key-value pairs attached to the service.
	Labels map[string]string
	// The labels a workload must carry for its instances to be selected.
	TargetLabels map[string]string
	// The port the selected instances listen on, written as the port inside
	// the workload.
	TargetPort int
	// The transport protocol of the target port.
	TargetProtocol string
	// How many times the service has been written. This is the entity tag a
	// conditional apply compares against, and it moves only when an apply
	// changed something.
	Version int
	// The time the service was created.
	CreatedAt time.Time
	// The time the service was last modified.
	UpdatedAt time.Time
}

The Service type represents a named selection of workload instances to balance requests across.

A service is desired state like a workload, but there is nothing running to observe for one: its backends are computed from the workloads its target labels select, so the row holds only the selection.

type ServiceRepository

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

The ServiceRepository type provides persistence operations for the service domain.

func NewServiceRepository

func NewServiceRepository(db *sql.DB) *ServiceRepository

NewServiceRepository returns a ServiceRepository backed by the given database.

func (*ServiceRepository) Delete

func (r *ServiceRepository) Delete(ctx context.Context, name string) error

Delete removes the service with the given name, reporting ErrServiceNotFound when no such service exists.

func (*ServiceRepository) Get

func (r *ServiceRepository) Get(ctx context.Context, name string) (Service, error)

Get returns the service with the given name, reporting ErrServiceNotFound when no such service exists.

func (*ServiceRepository) List

func (r *ServiceRepository) List(ctx context.Context, queries ...Query) ([]Service, error)

List returns the services matching every one of the given queries, ordered by name so that the result is stable. Passing no queries returns every service.

A query's path reaches the service's labels under $.labels, the same way a volume query does. The target labels are not queryable: they say what the service selects rather than what it is, and a caller asking what selects a workload reads the services back and looks.

func (*ServiceRepository) Upsert

func (r *ServiceRepository) Upsert(ctx context.Context, service Service, ifMatch int) (Service, bool, error)

Upsert records the service under its name, replacing what a service already holding the name says. The second return value reports whether the service was created rather than updated.

An upsert rather than an insert-or-fail, because a service holds no data of its own: applying the same manifest twice means the file is the truth, which is how a workload's apply already behaves.

A non-zero ifMatch conditions the write on the stored version still being that one, reporting ErrServiceChanged when it is not and ErrServiceNotFound when there is no row to have the version at all. Zero applies unconditionally, which is what a caller creating a service has to do: there is no version yet to name.

Like a workload's apply, a write that would change nothing is skipped, so re-applying an unchanged manifest leaves the version where it is. That is what lets a pipeline apply the same file repeatedly without invalidating the tag it is holding.

type Token added in v0.5.0

type Token struct {
	// The identifier the server assigns to the token, which is what a
	// delete names.
	ID string
	// The hash the presented credential is looked up by.
	Hash string
	// Whether the token is the recovery token or a client token.
	Type string
	// What minted the token: "init", "static", "oidc" or "session".
	Source string
	// The principal the token authenticates as. Empty for the recovery
	// token.
	Principal string
	// The groups the identity provider asserted when the token was
	// minted.
	Groups []string
	// The time after which the token no longer authenticates. Zero when
	// the token does not expire.
	ExpiresAt time.Time
	// The time the token was created.
	CreatedAt time.Time
	// The time the token last authenticated a request. Zero when it never
	// has.
	LastUsedAt time.Time
	// The workload the token was minted for. Empty for every token that
	// was not minted for one.
	WorkloadID string
	// The instance the token was minted for. Nil for a token every
	// instance of the workload shares, and for a token not minted for a
	// workload at all.
	WorkloadInstance *int
	// The workload version the token was minted for. Set for a shared
	// token, whose file is kept per version, so a rolling replacement
	// leaves the old version's instances a valid credential until the
	// version is reclaimed. Nil for an instance-bound token.
	WorkloadVersion *int
}

The Token type represents a credential that authenticates an API caller.

The credential itself is not here. The database records only its hash, so a copy of the database holds nothing a caller could present.

type TokenRepository added in v0.5.0

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

The TokenRepository type provides persistence operations for the token domain.

func NewTokenRepository added in v0.5.0

func NewTokenRepository(db *sql.DB) *TokenRepository

NewTokenRepository returns a TokenRepository backed by the given database.

func (*TokenRepository) Create added in v0.5.0

func (r *TokenRepository) Create(ctx context.Context, token Token) (Token, error)

Create records a token, assigning its identifier and creation time. The ExpiresAt, LastUsedAt and ID fields of the input are ignored.

func (*TokenRepository) Delete added in v0.5.0

func (r *TokenRepository) Delete(ctx context.Context, id string) error

Delete removes the token with the given identifier, reporting ErrTokenNotFound when no such token exists. Revocation is immediate: the next request presenting the credential finds nothing to hash to.

func (*TokenRepository) DeleteExpired added in v0.5.0

func (r *TokenRepository) DeleteExpired(ctx context.Context, now time.Time) (int64, error)

DeleteExpired removes every token whose expiry has passed, returning how many were removed. An expired token already refuses to authenticate, so this is hygiene for the list rather than security.

func (*TokenRepository) DeleteForInstance added in v0.6.0

func (r *TokenRepository) DeleteForInstance(ctx context.Context, workloadID string, instance int) error

DeleteForInstance removes every token minted for one instance of the workload, leaving the tokens its instances share alone. Deleting when none exists is not an error, as it is not for DeleteForWorkload.

func (*TokenRepository) DeleteForWorkload added in v0.6.0

func (r *TokenRepository) DeleteForWorkload(ctx context.Context, workloadID string) error

DeleteForWorkload removes every token minted for the workload. Deleting when none exists is not an error: revocation asks for a state, not an action, and the reconciler asks again on every pass until the workload is gone.

func (*TokenRepository) DeleteMinted added in v0.6.0

func (r *TokenRepository) DeleteMinted(ctx context.Context, workloadID, principal string, instance, version *int) error

DeleteMinted removes the token previously minted for the workload, principal, instance and version, if one exists. Deleting when none exists is not an error: a mint replaces whatever its predecessor was, including nothing.

func (*TokenRepository) DeleteRecovery added in v0.5.0

func (r *TokenRepository) DeleteRecovery(ctx context.Context) error

DeleteRecovery removes the recovery token if one exists, which is what consuming the reset file does. Deleting when none exists is not an error: the reset file asks for a state, not an action.

func (*TokenRepository) DeleteSuperseded added in v0.6.0

func (r *TokenRepository) DeleteSuperseded(ctx context.Context, workloadID string, version int) (int64, error)

DeleteSuperseded removes every shared token minted for a version of the workload other than the given one, returning how many were removed. This is how a rolling replacement retires the credentials of the versions it replaced, once nothing that reads them remains.

func (*TokenRepository) ExpireMinted added in v0.12.0

func (r *TokenRepository) ExpireMinted(ctx context.Context, workloadID, principal string, version int, except string, at time.Time) error

ExpireMinted gives every shared token minted for the workload, principal and version other than the one named by except an expiry of at, unless it already expires sooner. This is how a rotation retires the credential it replaced: the workload still holds the old one until it reads the file and handles the signal, so the old one stays valid for a grace period rather than dying before the new one is written.

func (*TokenRepository) Get added in v0.12.0

func (r *TokenRepository) Get(ctx context.Context, id string) (Token, error)

Get returns the token with the given identifier, reporting ErrTokenNotFound when the database holds no such token.

func (*TokenRepository) GetByHash added in v0.5.0

func (r *TokenRepository) GetByHash(ctx context.Context, hash string) (Token, error)

GetByHash returns the token a presented credential hashes to, reporting ErrTokenNotFound when the database holds no such token.

func (*TokenRepository) GetForWorkload added in v0.6.0

func (r *TokenRepository) GetForWorkload(ctx context.Context, workloadID string, version int, principal string) (Token, error)

GetForWorkload returns the token minted for the workload, version and principal that every instance shares, reporting ErrTokenNotFound when none exists. This is what the rotation check reads the expiry from. A rotation leaves its predecessor alive for a grace period, so the newest is the one returned while both exist.

func (*TokenRepository) HasRecovery added in v0.9.0

func (r *TokenRepository) HasRecovery(ctx context.Context) (bool, error)

HasRecovery reports whether a recovery token exists, which is what says the policy has been initialised and init is no longer permitted.

func (*TokenRepository) List added in v0.5.0

func (r *TokenRepository) List(ctx context.Context) ([]Token, error)

List returns every token the database records, newest first. This is half of the audit the layer promises: with the policy, it answers who can touch the server.

func (*TokenRepository) Touch added in v0.5.0

func (r *TokenRepository) Touch(ctx context.Context, id string, at time.Time) error

Touch records that the token authenticated a request at the given time.

type Variable

type Variable struct {
	// The identifier the server assigns to the variable.
	ID string
	// The name that identifies the variable, and which a manifest references.
	Name string
	// The value the variable holds.
	//
	// Read on every path that reads a variable at all, unlike a secret's, which is
	// left behind by everything but a workload starting.
	Value string
	// Arbitrary key-value pairs attached to the variable.
	Labels map[string]string
	// How many times the variable has been written, by its value or its labels.
	// This is the entity tag a conditional set compares against.
	Version int
	// The time the variable was created.
	CreatedAt time.Time
	// The time the variable last changed, by its value or its labels.
	UpdatedAt time.Time
}

The Variable type represents a value a workload reads, stored in the clear.

This is the counterpart to Secret, and the difference is the whole point of having both. A variable is reported by the API with its value, so it is the thing to reach for when an operator wants to see what a workload is configured with. Anything that would be damaging to report belongs in a Secret instead.

type VariableRepository

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

The VariableRepository type provides persistence operations for the variable domain.

func NewVariableRepository

func NewVariableRepository(db *sql.DB) *VariableRepository

NewVariableRepository returns a VariableRepository backed by the given database.

func (*VariableRepository) Delete

func (r *VariableRepository) Delete(ctx context.Context, name string) error

Delete removes the variable with the given name, reporting ErrVariableNotFound when no such variable exists.

The links naming it are left behind, as they are for a secret. A workload that references a deleted variable still has to report what it is missing, and re-creating the variable has to move that workload's hash again.

func (*VariableRepository) Get

func (r *VariableRepository) Get(ctx context.Context, name string) (Variable, error)

Get returns the variable with the given name, reporting ErrVariableNotFound when no such variable exists.

func (*VariableRepository) List

func (r *VariableRepository) List(ctx context.Context, queries ...Query) ([]Variable, error)

List returns the variables matching every one of the given queries, ordered by name so that the result is stable. Passing no queries returns every variable.

A query's path reaches the variable's labels under $.labels, the same way a workload query does. Returns ErrInvalidQueryPath when a query names a path SQLite cannot parse.

The values come with them, which is where this differs from the secret repository. Listing secrets deliberately leaves the values behind because a read that does not carry one cannot leak one. A variable's value is reported by the API anyway, so withholding it here would only mean reading each one again.

func (*VariableRepository) Upsert

func (r *VariableRepository) Upsert(ctx context.Context, variable Variable, ifMatch int) (Variable, error)

Upsert stores the given variable, returning it as stored. The given variable's identifier, version and timestamps are ignored: all of them are this repository's to hand out.

A non-zero ifMatch conditions the write on the stored version still being that one, reporting ErrVariableChanged when it is not and ErrVariableNotFound when there is no row to have the version at all. Zero writes unconditionally, which is what a caller creating a variable has to do: there is no version yet to name.

The creation time is preserved on a variable that already existed, so changing one does not read as creating it again.

func (*VariableRepository) UsedBy

func (r *VariableRepository) UsedBy(ctx context.Context, name string) ([]string, error)

UsedBy returns the names of the workloads referencing the variable with the given name.

Read from the recorded links rather than by matching the reference text inside each stored specification, so the answer does not depend on how a reference is written or on where in a manifest one is allowed.

A workload being deleted still counts. Its instances run until the reconciler has torn them down, so a variable it reads is still in use.

func (*VariableRepository) Values

func (r *VariableRepository) Values(ctx context.Context, names []string) (map[string]string, error)

Values returns the current value of each named variable, keyed by name.

This is the counterpart to SecretRepository.Revisions, and it returns the values themselves because that is what a variable contributes to a workload's hash. A secret contributes a revision instead, since its hash is reported and one computed over a value would confirm a guess at it. A variable's value is reported anyway.

A name that no variable holds is absent from the result rather than an error: the caller knows which names it asked about, and deciding what a missing variable means is its business. One query rather than one per name, so that hashing a workload costs the same however many variables it reads.

type Volume

type Volume struct {
	// The identifier the server assigns to the volume. The directory holding the
	// volume's data is named for this rather than for the name, which is the
	// operator's handle and is never used as a path component.
	ID string
	// The name that identifies the volume.
	Name string
	// Arbitrary key-value pairs attached to the volume.
	Labels map[string]string
	// Who owns the volume's directory, as a numeric "uid" or "uid:gid".
	// Empty leaves the directory owned by the user running the server.
	Owner string
	// The permission bits on the volume's directory, as an octal string.
	// Empty leaves the directory readable only by the user running the
	// server.
	Mode string
	// How many times the volume has been written. This is the entity tag a
	// conditional apply compares against, and it moves only when an apply
	// changed something.
	Version int
	// The time the volume was created.
	CreatedAt time.Time
	// The time the volume was last changed by an apply.
	UpdatedAt time.Time
}

The Volume type represents storage that outlives the workloads mounting it.

A volume is desired state like a workload, but there is nothing running to observe for one: it is a directory, and it either exists or it does not. What makes it its own resource rather than a field on a workload is its lifetime. Deleting the workload that mounts a volume leaves the volume, so removing stored data is always something asked for.

type VolumeRepository

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

The VolumeRepository type provides persistence operations for the volume domain.

func NewVolumeRepository

func NewVolumeRepository(db *sql.DB) *VolumeRepository

NewVolumeRepository returns a VolumeRepository backed by the given database.

func (*VolumeRepository) Delete

func (r *VolumeRepository) Delete(ctx context.Context, name string) error

Delete removes the volume with the given name, reporting ErrVolumeNotFound when no such volume exists.

Only the row. The directory holding the data is the service's to remove, so that nothing here touches the filesystem.

func (*VolumeRepository) Get

func (r *VolumeRepository) Get(ctx context.Context, name string) (Volume, error)

Get returns the volume with the given name, reporting ErrVolumeNotFound when no such volume exists.

func (*VolumeRepository) List

func (r *VolumeRepository) List(ctx context.Context, queries ...Query) ([]Volume, error)

List returns the volumes matching every one of the given queries, ordered by name so that the result is stable. Passing no queries returns every volume.

A query's path reaches the volume's labels under $.labels, the same way a workload query does. Filtering happens in the database rather than in the caller, so a query that matches little doesn't cost a read of everything it discards. Returns ErrInvalidQueryPath when a query names a path SQLite cannot parse.

func (*VolumeRepository) Upsert added in v0.3.0

func (r *VolumeRepository) Upsert(ctx context.Context, volume Volume, ifMatch int) (Volume, bool, error)

Upsert stores the volume, creating it when no volume holds the name and replacing the labels, the owner and the mode when one does. The second return reports whether it was created. The given volume's identifier, version and timestamps are ignored: all of them are this repository's to hand out.

An upsert rather than an insert-or-fail, because applying the same manifest twice means the file is the truth, which is how a workload's apply already behaves. The name identifies the volume, the directory holding its data is named for the identifier it keeps across an update, and its contents are the workloads' to write — so these fields are the whole of what an apply can change.

A non-zero ifMatch conditions the write on the stored version still being that one, reporting ErrVolumeChanged when it is not and ErrVolumeNotFound when there is no row to have the version at all. Zero applies unconditionally, which is what a caller creating a volume has to do: there is no version yet to name.

Like a workload's apply, a write that would change nothing is skipped, so re-applying an unchanged manifest leaves the version where it is. That is what lets a pipeline apply the same file repeatedly without invalidating the tag it is holding.

func (*VolumeRepository) UsedBy

func (r *VolumeRepository) UsedBy(ctx context.Context, name string) ([]string, error)

UsedBy returns the names of the workloads whose specifications mount the volume with the given name.

The search runs in the database rather than by reading every workload and inspecting it here. A volume's mounts are an array in the stored specification, so json_each expands them and the comparison happens where the rows are.

A workload being deleted still counts. Its containers are still running until the reconciler has torn them down, so a volume it mounts is still in use.

type Workload

type Workload struct {
	// The identifier the server assigns to the workload. It exists so that rows
	// referring to a workload do not depend on its name, which is the operator's
	// handle and could otherwise never change. It is not exposed by the API.
	ID string
	// The name that identifies the workload.
	Name string
	// Incremented every time the workload's specification changes.
	Version int
	// Which runtime block the specification names, and so which driver runs it.
	Runtime string
	// The canonical JSON encoding of the workload's specification.
	Spec []byte
	// The hash of Spec, used to detect drift between desired and running state.
	SpecHash string
	// Arbitrary key-value pairs attached to the workload.
	Labels map[string]string
	// The names of the secrets the workload's specification references.
	//
	// Written with the workload and not read back: what needs the recorded links
	// is the other direction, finding the workloads to redeploy when a secret
	// moves. Reading them here would cost a join on every pass of the reconciler
	// to answer a question the specification already answers.
	Secrets []string
	// The names of the variables the workload's specification references, written
	// and read back on the same terms as Secrets.
	Variables []string
	// The names of the other workloads the workload's specification references,
	// written and read back on the same terms as Secrets.
	//
	// The port a reference names is not recorded. What the links answer is which
	// workloads to rehash when one of them moves, and that question is asked of a
	// workload rather than of one of its ports.
	Workloads []string
	// The time the workload was first applied.
	CreatedAt time.Time
	// The time the workload's specification last changed. Resuming a suspended
	// workload also moves it, so a schedule counts occurrences from the resume.
	UpdatedAt time.Time
	// The time the workload was marked for deletion, or the zero time when it
	// has not been. A workload being deleted keeps its row until the driver
	// reports its work is gone, so that the teardown is observable and the
	// reconciler is the only thing that removes running work.
	DeletedAt time.Time
	// The time the workload was suspended, or the zero time when it is not.
	// A suspended workload keeps its row and its specification. The reconciler
	// stops its instances and starts nothing until the mark is cleared.
	SuspendedAt time.Time
}

The Workload type represents the desired state of a workload as persisted by the server. The spec is stored as canonical JSON so that the wire format remains the single description of a workload's shape.

type WorkloadEvent added in v0.7.0

type WorkloadEvent struct {
	// The identifier the server assigns to the event.
	ID string
	// The identifier of the workload the event was recorded against.
	WorkloadID string
	// Why the event was recorded, as a stable code rather than a sentence. The
	// prose an operator reads is rendered from this and Data when the event is
	// read, so the wording is not frozen into the row.
	Reason event.Reason
	// The canonical JSON encoding of the values the reason needs to be rendered,
	// such as the image reference a pull is fetching.
	Data []byte
	// How many times the event has been seen since FirstSeen.
	Count int
	// When the current episode of the event was first seen.
	FirstSeen time.Time
	// When the event was last seen.
	LastSeen time.Time
}

The WorkloadEvent type represents something the server observed about a workload while converging it.

Repeated sightings of the same reason and data coalesce into one row rather than accumulating, so the row carries a count and the two times that bound it. It says a thing was true as of LastSeen, which is a claim about the past rather than about the workload now.

type WorkloadEventRepository added in v0.7.0

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

The WorkloadEventRepository type provides persistence operations for the workload event domain.

func NewWorkloadEventRepository added in v0.7.0

func NewWorkloadEventRepository(db *sql.DB, maxEvents int) *WorkloadEventRepository

NewWorkloadEventRepository returns a WorkloadEventRepository backed by the given database, keeping at most maxEvents events for any one workload.

func (*WorkloadEventRepository) List added in v0.7.0

func (r *WorkloadEventRepository) List(ctx context.Context, name string, since time.Time, limit int) ([]WorkloadEvent, error)

List returns the events recorded against the named workload, most recently seen first, up to limit rows. A non-zero since drops the events last seen at or before it.

A workload that does not exist has no events, and so reads as empty rather than as a failure. Callers that need to tell the two apart ask for the workload first.

Since filters on the last sighting rather than the first, so an event that recurs is returned again with its new count. That is what a caller polling for what changed wants: the count is part of the event, and coalescing moved it.

func (*WorkloadEventRepository) Record added in v0.7.0

func (r *WorkloadEventRepository) Record(ctx context.Context, name string, reason event.Reason, data []byte) error

Record stores an event against the named workload, coalescing it with an existing event carrying the same reason and data.

Coalescing is what makes this safe to call from the reconciler, which runs a pass every few seconds and would otherwise write a row per pass for as long as a condition lasts. A repeat of an event already stored increments its count and moves its last seen time, which is one update to an indexed row.

A workload that no longer exists records nothing and reports no error. The reconciler can be converging a workload the operator has just deleted, and a lost event is the right outcome there rather than a failed pass.

type WorkloadRepository

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

The WorkloadRepository type provides persistence operations for the workload domain.

func NewWorkloadRepository

func NewWorkloadRepository(db *sql.DB) *WorkloadRepository

NewWorkloadRepository returns a WorkloadRepository backed by the given database.

func (*WorkloadRepository) Delete

func (r *WorkloadRepository) Delete(ctx context.Context, name string) error

Delete removes the workload with the given name, returning ErrWorkloadNotFound when no such workload exists.

This is the final removal of desired state, and is the reconciler's to call once the driver reports the workload's work is gone. Callers wanting to delete a workload should use MarkDeleting.

func (*WorkloadRepository) Get

func (r *WorkloadRepository) Get(ctx context.Context, name string) (Workload, error)

Get returns the workload with the given name, returning ErrWorkloadNotFound when no such workload exists.

func (*WorkloadRepository) List

func (r *WorkloadRepository) List(ctx context.Context, queries ...Query) ([]Workload, error)

List returns the workloads matching every one of the given queries, ordered by name. Passing no queries returns every workload.

Filtering happens in the database rather than in the caller, so a query that matches little doesn't cost a read of everything it discards. Returns ErrInvalidQueryPath when a query names a path SQLite cannot parse.

func (*WorkloadRepository) MarkDeleting

func (r *WorkloadRepository) MarkDeleting(ctx context.Context, name string, force bool) (Workload, []string, error)

MarkDeleting records that the workload with the given name should be deleted, returning the marked workload and the names of the workloads that reference it.

The row is deliberately kept: the reconciler is the only thing that stops running work, so the desired state has to survive long enough for it to notice and act. Marking is idempotent — a workload already marked keeps its original timestamp — so a repeated request neither fails nor restarts the clock. Returns ErrWorkloadNotFound when no such workload exists.

The references are read in the same transaction as the mark, so a reference written between the two cannot slip past. Unless force is set, a workload another one references is left unmarked and ErrWorkloadReferenced is returned, with the referencing names beside it so the caller can say which.

func (*WorkloadRepository) ReferencedBy

func (r *WorkloadRepository) ReferencedBy(ctx context.Context, name string) ([]string, error)

ReferencedBy returns the names of the workloads referencing the workload with the given name.

Read from the recorded links rather than by matching the reference text inside each stored specification, for the reason a secret's users are: the answer must not depend on how a reference is written.

A workload being deleted still counts, as it does for a secret. Its instances run until the reconciler has torn them down, so the address it reads is still one it is using.

The workload itself is left out. A workload referencing its own address is fine, but it is not something a change to that workload has to redeploy: it is already being rewritten by whatever moved it.

func (*WorkloadRepository) Resume

func (r *WorkloadRepository) Resume(ctx context.Context, name string) (Workload, error)

Resume clears the workload's suspension, returning the resumed workload.

UpdatedAt moves to the resume time. A schedule counts its next occurrence from that field when nothing has run yet, so moving it makes a resumed workload wait for its next occurrence rather than run the last one it missed. The version and hash stay put, so nothing is replaced. Resuming is idempotent — a workload that is not suspended is returned unchanged. Returns ErrWorkloadNotFound when no such workload exists.

func (*WorkloadRepository) Suspend

func (r *WorkloadRepository) Suspend(ctx context.Context, name string) (Workload, error)

Suspend records that the workload with the given name should not run, returning the suspended workload.

Suspension is desired state: the reconciler stops the workload's instances and starts nothing for it until Resume clears the mark. The specification, version and hash are untouched, so a resumed workload adopts what was running rather than replacing it. Suspending is idempotent — a workload already suspended keeps its original timestamp. Returns ErrWorkloadNotFound when no such workload exists.

func (*WorkloadRepository) Upsert

func (r *WorkloadRepository) Upsert(ctx context.Context, w Workload, ifMatch int, ports ...Port) (Workload, bool, error)

Upsert stores w as the desired state for its name, returning the stored workload and whether it was newly created.

The write is conditional on the specification actually having changed: when the incoming SpecHash matches what is already stored, the row is left untouched and the existing workload is returned, so re-applying an unchanged manifest neither bumps the version nor moves UpdatedAt. When the hash differs the version is incremented, which is what causes the reconciler to replace running instances.

A non-zero ifMatch conditions the write on the stored version still being that one, reporting ErrWorkloadChanged when it is not and ErrWorkloadNotFound when there is no row to have the version at all. Zero applies unconditionally, which is what a caller creating a workload has to do: there is no version yet to name.

The Version, CreatedAt and UpdatedAt fields of w are ignored. The repository assigns them.

Jump to

Keyboard shortcuts

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