storage

package
v0.0.0-...-bf48186 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound reports a missing persisted record.
	ErrNotFound = errors.New("storage record not found")
	// ErrConflict reports a uniqueness or state-transition conflict during persistence.
	ErrConflict = errors.New("storage conflict")
	// ErrNestedTransact is returned when a TxFn calls Transact on the tx
	// argument. Transactions are not reentrant — see P2-ARCH-01.
	ErrNestedTransact = errors.New("storage: nested Transact call not allowed")
)

Functions

This section is empty.

Types

type AgentCertificateRecoveryGrantRecord

type AgentCertificateRecoveryGrantRecord struct {
	AgentID   string
	IssuedBy  string
	IssuedAt  time.Time
	ExpiresAt time.Time
	UsedAt    *time.Time
	RevokedAt *time.Time
}

AgentCertificateRecoveryGrantRecord stores one administrator-approved certificate recovery window.

type AgentCertificateRecoveryGrantStore

type AgentCertificateRecoveryGrantStore interface {
	PutAgentCertificateRecoveryGrant(ctx context.Context, grant AgentCertificateRecoveryGrantRecord) error
	ListAgentCertificateRecoveryGrants(ctx context.Context) ([]AgentCertificateRecoveryGrantRecord, error)
	GetAgentCertificateRecoveryGrant(ctx context.Context, agentID string) (AgentCertificateRecoveryGrantRecord, error)
	UseAgentCertificateRecoveryGrant(ctx context.Context, agentID string, usedAt time.Time) (AgentCertificateRecoveryGrantRecord, error)
	RevokeAgentCertificateRecoveryGrant(ctx context.Context, agentID string, revokedAt time.Time) (AgentCertificateRecoveryGrantRecord, error)
}

AgentCertificateRecoveryGrantStore persists administrator-approved certificate recovery windows.

type AgentRecord

type AgentRecord struct {
	ID            string
	NodeName      string
	FleetGroupID  string
	Version       string
	ReadOnly      bool
	LastSeenAt    time.Time
	CertIssuedAt  *time.Time
	CertExpiresAt *time.Time
}

AgentRecord stores one enrolled host agent snapshot.

type AgentRevocationRecord

type AgentRevocationRecord struct {
	AgentID       string
	RevokedAt     time.Time
	CertExpiresAt time.Time
}

AgentRevocationRecord tracks one deregistered agent whose mTLS client certificate may still be cryptographically valid. The record survives control-plane restart so a revoked agent cannot silently reconnect. CertExpiresAt is the cert validity cut-off; once the cert has expired the row is eligible for pruning because the cert can no longer authenticate regardless of the revocation list.

type AgentRevocationStore

type AgentRevocationStore interface {
	PutAgentRevocation(ctx context.Context, revocation AgentRevocationRecord) error
	ListAgentRevocations(ctx context.Context) ([]AgentRevocationRecord, error)
	DeleteExpiredAgentRevocations(ctx context.Context, before time.Time) (int64, error)
}

AgentRevocationStore persists deregistered-agent IDs so the revocation set survives control-plane restart. See AgentRevocationRecord in models.go.

type AuditEventRecord

type AuditEventRecord struct {
	ID        string
	ActorID   string
	Action    string
	TargetID  string
	CreatedAt time.Time
	Details   map[string]any
}

AuditEventRecord stores one immutable control-plane audit event.

type AuditStore

type AuditStore interface {
	AppendAuditEvent(ctx context.Context, event AuditEventRecord) error
	// ListAuditEvents returns the most recent audit events in ascending
	// chronological order. limit caps the number of rows returned; values
	// <= 0 fall back to a hard maximum of 1024.
	ListAuditEvents(ctx context.Context, limit int) ([]AuditEventRecord, error)
	// PruneAuditEvents deletes audit_events rows with created_at strictly
	// before the cutoff and returns the number of deleted rows. Used by the
	// retention worker (P2-REL-04 / finding M-R2) to keep audit_events from
	// growing unbounded.
	PruneAuditEvents(ctx context.Context, before time.Time) (int64, error)
}

AuditStore persists immutable operator and security events.

type CertificateAuthorityRecord

type CertificateAuthorityRecord struct {
	CAPEM         string
	PrivateKeyPEM string
	UpdatedAt     time.Time
}

CertificateAuthorityRecord stores the persisted control-plane root CA material.

type CertificateAuthorityStore

type CertificateAuthorityStore interface {
	PutCertificateAuthority(ctx context.Context, authority CertificateAuthorityRecord) error
	GetCertificateAuthority(ctx context.Context) (CertificateAuthorityRecord, error)
}

CertificateAuthorityStore persists the control-plane root CA required for agent mTLS continuity.

type ClientAssignmentRecord

type ClientAssignmentRecord struct {
	ID           string
	ClientID     string
	TargetType   string
	FleetGroupID string
	AgentID      string
	CreatedAt    time.Time
}

ClientAssignmentRecord stores one desired rollout target for a managed client.

type ClientDeploymentRecord

type ClientDeploymentRecord struct {
	ClientID         string
	AgentID          string
	DesiredOperation string
	Status           string
	LastError        string
	ConnectionLink   string
	LastAppliedAt    *time.Time
	UpdatedAt        time.Time
}

ClientDeploymentRecord stores the current rollout state for one client on one agent.

type ClientIPHistoryRecord

type ClientIPHistoryRecord struct {
	AgentID   string
	ClientID  string
	IPAddress string
	FirstSeen time.Time
	LastSeen  time.Time
}

ClientIPHistoryRecord stores one unique IP seen for a client on an agent.

type ClientRecord

type ClientRecord struct {
	ID                string
	Name              string
	SecretCiphertext  string
	UserADTag         string
	Enabled           bool
	MaxTCPConns       int
	MaxUniqueIPs      int
	DataQuotaBytes    int64
	ExpirationRFC3339 string
	CreatedAt         time.Time
	UpdatedAt         time.Time
	DeletedAt         *time.Time
}

ClientRecord stores one centrally managed Telemt client definition.

type ClientStore

type ClientStore interface {
	PutClient(ctx context.Context, client ClientRecord) error
	GetClientByID(ctx context.Context, clientID string) (ClientRecord, error)
	ListClients(ctx context.Context) ([]ClientRecord, error)
	PutClientAssignment(ctx context.Context, assignment ClientAssignmentRecord) error
	DeleteClientAssignments(ctx context.Context, clientID string) error
	ListClientAssignments(ctx context.Context, clientID string) ([]ClientAssignmentRecord, error)
	PutClientDeployment(ctx context.Context, deployment ClientDeploymentRecord) error
	ListClientDeployments(ctx context.Context, clientID string) ([]ClientDeploymentRecord, error)
	// Per-(client, agent) usage counters. Persisted so the in-memory
	// server.clientUsage map can rehydrate across restarts without losing
	// accumulated traffic totals.
	UpsertClientUsage(ctx context.Context, record ClientUsageRecord) error
	ListClientUsage(ctx context.Context) ([]ClientUsageRecord, error)
	DeleteClientUsageByClient(ctx context.Context, clientID string) error
}

ClientStore persists centrally managed Telemt clients, rollout assignments, and per-node deployment state.

type ClientUsageRecord

type ClientUsageRecord struct {
	ClientID         string
	AgentID          string
	TrafficUsedBytes uint64
	UniqueIPsUsed    int
	ActiveTCPConns   int
	ActiveUniqueIPs  int
	LastSeq          uint64
	ObservedAt       time.Time
}

ClientUsageRecord stores the lifetime traffic + live-gauge counters for one (client, agent) pair. Persisted so the in-memory server.clientUsage map rehydrates across restarts without losing accumulated totals. LastSeq is the per-agent delta cursor (rewinds to 1 on agent restart; the higher value wins).

type DCHealthPointRecord

type DCHealthPointRecord struct {
	AgentID         string
	CapturedAt      time.Time
	DC              int
	CoveragePctAvg  float64
	CoveragePctMin  float64
	RTTMsAvg        float64
	RTTMsMax        float64
	AliveWritersMin int
	RequiredWriters int
	LoadMax         int
	SampleCount     int
}

DCHealthPointRecord stores one aggregated DC health snapshot.

type DiscoveredClientRecord

type DiscoveredClientRecord struct {
	ID                 string
	AgentID            string
	ClientName         string
	Secret             string
	Status             string
	TotalOctets        uint64
	CurrentConnections int
	ActiveUniqueIPs    int
	ConnectionLink     string
	MaxTCPConns        int
	MaxUniqueIPs       int
	DataQuotaBytes     int64
	Expiration         string
	DiscoveredAt       time.Time
	UpdatedAt          time.Time
}

DiscoveredClientRecord stores one Telemt user found on an agent that is not managed by the panel.

type DiscoveredClientStore

type DiscoveredClientStore interface {
	PutDiscoveredClient(ctx context.Context, record DiscoveredClientRecord) error
	ListDiscoveredClients(ctx context.Context) ([]DiscoveredClientRecord, error)
	ListDiscoveredClientsByAgent(ctx context.Context, agentID string) ([]DiscoveredClientRecord, error)
	GetDiscoveredClient(ctx context.Context, id string) (DiscoveredClientRecord, error)
	// GetDiscoveredClientByAgentAndName looks up a discovered_clients row by
	// its natural key (agent_id, client_name). Returns ErrNotFound when no
	// row exists. Used by the reconcile path to dedupe repeated FULL_SNAPSHOT
	// reports from an agent so the pending-review list does not grow unbounded
	// (see P2-LOG-02, finding L-10 / M-C4).
	GetDiscoveredClientByAgentAndName(ctx context.Context, agentID string, clientName string) (DiscoveredClientRecord, error)
	UpdateDiscoveredClientStatus(ctx context.Context, id string, status string, updatedAt time.Time) error
	DeleteDiscoveredClient(ctx context.Context, id string) error
}

DiscoveredClientStore persists Telemt users found on agents that are not managed by the panel.

type EnrollmentStore

type EnrollmentStore interface {
	PutEnrollmentToken(ctx context.Context, token EnrollmentTokenRecord) error
	ListEnrollmentTokens(ctx context.Context) ([]EnrollmentTokenRecord, error)
	GetEnrollmentToken(ctx context.Context, value string) (EnrollmentTokenRecord, error)
	ConsumeEnrollmentToken(ctx context.Context, value string, consumedAt time.Time) (EnrollmentTokenRecord, error)
	RevokeEnrollmentToken(ctx context.Context, value string, revokedAt time.Time) (EnrollmentTokenRecord, error)
}

EnrollmentStore persists one-time agent enrollment tokens.

type EnrollmentTokenRecord

type EnrollmentTokenRecord struct {
	Value        string
	FleetGroupID string
	IssuedAt     time.Time
	ExpiresAt    time.Time
	ConsumedAt   *time.Time
	RevokedAt    *time.Time
}

EnrollmentTokenRecord stores one enrollment token and its consumption state.

type FleetGroupIntegrationRecord

type FleetGroupIntegrationRecord struct {
	ID           string
	FleetGroupID string
	Kind         string
	ProviderID   *string
	Config       []byte
	Enabled      bool
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

FleetGroupIntegrationRecord attaches one integration install to a fleet group. At most one row per (fleet_group_id, kind). ProviderID is nullable: some integrations embed their entire config inline and do not reference a shared provider.

type FleetGroupRecord

type FleetGroupRecord struct {
	ID          string
	Name        string
	Label       string
	Description string
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

FleetGroupRecord stores one fleet group in the global control-plane namespace.

ID is a UUID assigned at creation and never changes. Name is an immutable human-readable slug (unique, used in URLs / CLI / logs). Label is a free-form display name the operator can edit. Description is free text — rendered on the detail page.

type FleetStore

type FleetStore interface {
	// PutFleetGroup upserts a fleet group by id. Used by migration/copy
	// helpers and tests. HTTP-layer CRUD calls the explicit
	// Create/Update/Delete methods below, which enforce uniqueness and
	// bump updated_at.
	PutFleetGroup(ctx context.Context, group FleetGroupRecord) error
	CreateFleetGroup(ctx context.Context, group FleetGroupRecord) error
	UpdateFleetGroup(ctx context.Context, group FleetGroupRecord) error
	GetFleetGroup(ctx context.Context, id string) (FleetGroupRecord, error)
	GetFleetGroupByName(ctx context.Context, name string) (FleetGroupRecord, error)
	ListFleetGroups(ctx context.Context) ([]FleetGroupRecord, error)
	// DeleteFleetGroup removes the row. Callers are responsible for
	// reassigning or detaching dependents first (agents, enrollment
	// tokens, client_assignments); the DB enforces FK integrity so a
	// non-reassigned delete fails with a constraint error.
	DeleteFleetGroup(ctx context.Context, id string) error
	// ReassignFleetGroupMembers moves every FK reference to `fromID`
	// (agents.fleet_group_id, enrollment_tokens.fleet_group_id,
	// client_assignments.fleet_group_id) to `toID` in one transaction.
	// Returns the number of rows touched per table for audit logging.
	ReassignFleetGroupMembers(ctx context.Context, fromID, toID string) (ReassignCounts, error)
	// CountFleetGroupMembers returns how many rows in each dependent
	// table reference `fleetGroupID`. Powers the deletion-preview HTTP
	// endpoint so the operator sees the blast radius before confirming.
	CountFleetGroupMembers(ctx context.Context, fleetGroupID string) (ReassignCounts, error)
	PutAgent(ctx context.Context, agent AgentRecord) error
	// PutAgentsBulk upserts a batch of agents in a single transaction. Semantics
	// match PutAgent per row (UPSERT on id); when the same ID appears twice the
	// last occurrence wins. A nil/empty slice is a no-op that returns nil. Used
	// by the control-plane batch writer (P3-PERF-01a) to avoid N individual
	// INSERTs per flush. See also storage/postgres and storage/sqlite
	// implementations which chunk large batches.
	PutAgentsBulk(ctx context.Context, agents []AgentRecord) error
	ListAgents(ctx context.Context) ([]AgentRecord, error)
	DeleteAgent(ctx context.Context, agentID string) error
	UpdateAgentNodeName(ctx context.Context, agentID string, nodeName string) error
	PutInstance(ctx context.Context, instance InstanceRecord) error
	// PutInstancesBulk upserts a batch of Telemt instances in a single
	// transaction. Same semantics as PutInstance per row; empty slice is a
	// no-op. See P3-PERF-01a.
	PutInstancesBulk(ctx context.Context, instances []InstanceRecord) error
	ListInstances(ctx context.Context) ([]InstanceRecord, error)
	DeleteInstancesByAgent(ctx context.Context, agentID string) error
}

FleetStore persists fleet topology and discovered Telemt runtime state.

type InstanceRecord

type InstanceRecord struct {
	ID                string
	AgentID           string
	Name              string
	Version           string
	ConfigFingerprint string
	ConnectedUsers    int
	ReadOnly          bool
	UpdatedAt         time.Time
}

InstanceRecord stores one Telemt runtime observed through an agent.

type IntegrationProviderRecord

type IntegrationProviderRecord struct {
	ID        string
	Kind      string
	Label     string
	Config    []byte
	CreatedAt time.Time
	UpdatedAt time.Time
}

IntegrationProviderRecord stores credentials for an external integration backend (e.g. a Cloudflare account). A single provider can back FleetGroupIntegrationRecord rows across many groups. Config is opaque JSON — the shape is owned by the integration implementation and validated at install time.

type IntegrationStore

type IntegrationStore interface {
	CreateIntegrationProvider(ctx context.Context, provider IntegrationProviderRecord) error
	UpdateIntegrationProvider(ctx context.Context, provider IntegrationProviderRecord) error
	GetIntegrationProvider(ctx context.Context, id string) (IntegrationProviderRecord, error)
	ListIntegrationProviders(ctx context.Context) ([]IntegrationProviderRecord, error)
	ListIntegrationProvidersByKind(ctx context.Context, kind string) ([]IntegrationProviderRecord, error)
	DeleteIntegrationProvider(ctx context.Context, id string) error

	CreateFleetGroupIntegration(ctx context.Context, integration FleetGroupIntegrationRecord) error
	UpdateFleetGroupIntegration(ctx context.Context, integration FleetGroupIntegrationRecord) error
	GetFleetGroupIntegration(ctx context.Context, id string) (FleetGroupIntegrationRecord, error)
	ListFleetGroupIntegrations(ctx context.Context, fleetGroupID string) ([]FleetGroupIntegrationRecord, error)
	DeleteFleetGroupIntegration(ctx context.Context, id string) error
}

IntegrationStore persists the integration-scaffolding entities: shared provider credentials and per-fleet-group integration installs. The store itself is kind-agnostic — config is an opaque JSON blob. Validation, reconciliation, and kind-specific semantics live in the fleet/integrations registry.

type JobRecord

type JobRecord struct {
	ID             string
	Action         string
	ActorID        string
	Status         string
	CreatedAt      time.Time
	TTL            time.Duration
	IdempotencyKey string
	PayloadJSON    string
}

JobRecord stores one orchestration job.

type JobStore

type JobStore interface {
	PutJob(ctx context.Context, job JobRecord) error
	GetJobByIdempotencyKey(ctx context.Context, idempotencyKey string) (JobRecord, error)
	ListJobs(ctx context.Context) ([]JobRecord, error)
	PutJobTarget(ctx context.Context, target JobTargetRecord) error
	ListJobTargets(ctx context.Context, jobID string) ([]JobTargetRecord, error)
}

JobStore persists orchestration jobs and per-target result state.

type JobTargetRecord

type JobTargetRecord struct {
	JobID      string
	AgentID    string
	Status     string
	ResultText string
	ResultJSON string
	UpdatedAt  time.Time
}

JobTargetRecord stores delivery and result state for one job target.

type LoginLockoutRecord

type LoginLockoutRecord struct {
	Username  string
	Failures  int
	LockedAt  *time.Time
	UpdatedAt time.Time
}

LoginLockoutRecord stores the persistent login-failure state for one account (S7). Failures accumulates until the lockout threshold is reached; at that point LockedAt is set to the wall-clock time the lockout began. A nil LockedAt means "not currently locked". Username is the raw account name as submitted to /auth/login so the auth service can still match it after a restart — the service normalises to lower-case before lookup.

type LoginLockoutStore

type LoginLockoutStore interface {
	UpsertLoginLockout(ctx context.Context, record LoginLockoutRecord) error
	GetLoginLockout(ctx context.Context, username string) (LoginLockoutRecord, error)
	DeleteLoginLockout(ctx context.Context, username string) error
	ListLoginLockouts(ctx context.Context) ([]LoginLockoutRecord, error)
	DeleteExpiredLoginLockouts(ctx context.Context, before time.Time) (int64, error)
}

LoginLockoutStore persists per-account login-failure state so a control-plane restart or fail-over cannot reset the lockout counter (S7). See LoginLockoutRecord.

type MetricSnapshotRecord

type MetricSnapshotRecord struct {
	ID         string
	AgentID    string
	InstanceID string
	CapturedAt time.Time
	Values     map[string]uint64
}

MetricSnapshotRecord stores one aggregated metric capture.

type MetricStore

type MetricStore interface {
	AppendMetricSnapshot(ctx context.Context, snapshot MetricSnapshotRecord) error
	// AppendMetricSnapshotsBulk inserts a batch of metric snapshots in a
	// single transaction. Empty slice is a no-op. See P3-PERF-01a.
	AppendMetricSnapshotsBulk(ctx context.Context, snapshots []MetricSnapshotRecord) error
	ListMetricSnapshots(ctx context.Context) ([]MetricSnapshotRecord, error)
	// PruneMetricSnapshots deletes metric_snapshots rows with captured_at
	// strictly before the cutoff and returns the number of deleted rows.
	// Used by the retention worker (P2-REL-05).
	PruneMetricSnapshots(ctx context.Context, before time.Time) (int64, error)
}

MetricStore persists aggregated control-plane metric snapshots.

type PanelSettingsRecord

type PanelSettingsRecord struct {
	HTTPPublicURL      string
	GRPCPublicEndpoint string
	UpdatedAt          time.Time
}

PanelSettingsRecord stores operator-managed public access settings for the panel.

type PanelSettingsStore

type PanelSettingsStore interface {
	PutPanelSettings(ctx context.Context, settings PanelSettingsRecord) error
	GetPanelSettings(ctx context.Context) (PanelSettingsRecord, error)
}

PanelSettingsStore persists operator-managed panel network and TLS settings.

type ReassignCounts

type ReassignCounts struct {
	Agents            int64
	EnrollmentTokens  int64
	ClientAssignments int64
}

ReassignCounts summarises how many FK references to a fleet group exist (or were moved, depending on the method). Used by the deletion-preview endpoint and the reassignment audit entry.

type RetentionSettings

type RetentionSettings = RetentionSettingsRecord

RetentionSettings is the storage-layer alias used across the Store interface. Callers in the control-plane server wrap it with their own typed RetentionSettings struct; at the storage boundary this alias keeps the interface decoupled from server internals while reusing the same field layout (see RetentionSettingsRecord).

type RetentionSettingsRecord

type RetentionSettingsRecord struct {
	TSRawSeconds          int `json:"ts_raw_seconds"`
	TSHourlySeconds       int `json:"ts_hourly_seconds"`
	TSDCSeconds           int `json:"ts_dc_seconds"`
	IPHistorySeconds      int `json:"ip_history_seconds"`
	EventSeconds          int `json:"event_history_seconds"`
	AuditEventSeconds     int `json:"audit_event_seconds"`
	MetricSnapshotSeconds int `json:"metric_snapshot_seconds"`
}

RetentionSettingsRecord stores operator-managed timeseries/event retention windows. Persisted as an opaque JSON blob in panel_settings.retention_json so adding new retention knobs never needs another migration.

type RetentionSettingsStore

type RetentionSettingsStore interface {
	GetRetentionSettings(ctx context.Context) (RetentionSettings, error)
	PutRetentionSettings(ctx context.Context, settings RetentionSettings) error
}

RetentionSettingsStore persists operator-managed retention windows for timeseries data, runtime events, and client IP history. Returns ErrNotFound when no row has been written yet so the caller can fall back to its own defaults.

type ServerLoadHourlyRecord

type ServerLoadHourlyRecord struct {
	AgentID        string
	BucketHour     time.Time
	CPUPctAvg      float64
	CPUPctMax      float64
	MemPctAvg      float64
	MemPctMax      float64
	ConnectionsAvg float64
	ConnectionsMax int
	ActiveUsersAvg float64
	ActiveUsersMax int
	DCCoverageMin  float64
	DCCoverageAvg  float64
	SampleCount    int
}

ServerLoadHourlyRecord stores one hourly rollup of server load metrics.

type ServerLoadPointRecord

type ServerLoadPointRecord struct {
	AgentID                string
	CapturedAt             time.Time
	CPUPctAvg              float64
	CPUPctMax              float64
	MemPctAvg              float64
	MemPctMax              float64
	DiskPctAvg             float64
	DiskPctMax             float64
	Load1M                 float64
	Load5M                 float64
	Load15M                float64
	ConnectionsAvg         int
	ConnectionsMax         int
	ConnectionsMEAvg       int
	ConnectionsDirectAvg   int
	ActiveUsersAvg         int
	ActiveUsersMax         int
	ConnectionsTotal       uint64
	ConnectionsBadTotal    uint64
	HandshakeTimeoutsTotal uint64
	DCCoverageMinPct       float64
	DCCoverageAvgPct       float64
	HealthyUpstreams       int
	TotalUpstreams         int
	NetBytesSent           uint64
	NetBytesRecv           uint64
	SampleCount            int
}

ServerLoadPointRecord stores one aggregated runtime snapshot for timeseries.

type SessionRecord

type SessionRecord struct {
	ID        string
	UserID    string
	CreatedAt time.Time
}

SessionRecord stores one authenticated user session.

type SessionStore

type SessionStore interface {
	PutSession(ctx context.Context, session SessionRecord) error
	GetSession(ctx context.Context, sessionID string) (SessionRecord, error)
	DeleteSession(ctx context.Context, sessionID string) error
	ListSessions(ctx context.Context) ([]SessionRecord, error)
	DeleteExpiredSessions(ctx context.Context, before time.Time) error
}

SessionStore persists authenticated user sessions.

type Store

type Store interface {
	UserStore
	UserAppearanceStore
	SessionStore
	LoginLockoutStore
	AgentRevocationStore
	FleetStore
	JobStore
	AuditStore
	MetricStore
	TelemetryStore
	EnrollmentStore
	AgentCertificateRecoveryGrantStore
	PanelSettingsStore
	RetentionSettingsStore
	UpdateConfigStore
	CertificateAuthorityStore
	ClientStore
	DiscoveredClientStore
	TimeseriesStore
	IntegrationStore

	// Transact runs fn inside a single database transaction. The tx
	// argument is a Store implementation bound to the transaction:
	// all mutations performed through it either commit as a unit or
	// roll back together.
	//
	// Contract:
	//   - On fn returning nil, the transaction commits.
	//   - On fn returning a non-nil error, the transaction rolls back
	//     and the error is returned to the caller.
	//   - On panic inside fn, the transaction rolls back and the panic
	//     is re-raised.
	//   - Context cancellation during fn aborts the transaction.
	//   - PostgreSQL: serialization failures (SQLSTATE 40001) are
	//     retried up to 3 times automatically. Default isolation is
	//     read-committed.
	//   - SQLite: uses BEGIN IMMEDIATE so the writer lock is acquired
	//     up front. No retry loop (single-writer semantics).
	//   - TxFn MUST NOT call tx.Transact; nested calls return
	//     ErrNestedTransact immediately.
	Transact(ctx context.Context, fn TxFn) error

	// Ping verifies that the database connection is alive.
	Ping(ctx context.Context) error
	Close() error
}

Store aggregates the persistence capabilities required by the control-plane.

type TelemetryDetailBoostRecord

type TelemetryDetailBoostRecord struct {
	AgentID   string
	ExpiresAt time.Time
	UpdatedAt time.Time
}

TelemetryDetailBoostRecord stores one persisted detail boost window for a node.

type TelemetryDiagnosticsCurrentRecord

type TelemetryDiagnosticsCurrentRecord struct {
	AgentID             string
	ObservedAt          time.Time
	State               string
	StateReason         string
	SystemInfoJSON      string
	EffectiveLimitsJSON string
	SecurityPostureJSON string
	MinimalAllJSON      string
	MEPoolJSON          string
	DcsJSON             string
}

TelemetryDiagnosticsCurrentRecord stores the latest slower diagnostics payloads for one node.

type TelemetryRuntimeCurrentRecord

type TelemetryRuntimeCurrentRecord struct {
	AgentID                   string
	ObservedAt                time.Time
	State                     string
	StateReason               string
	ReadOnly                  bool
	AcceptingNewConnections   bool
	MERuntimeReady            bool
	ME2DCFallbackEnabled      bool
	UseMiddleProxy            bool
	StartupStatus             string
	StartupStage              string
	StartupProgressPct        float64
	InitializationStatus      string
	Degraded                  bool
	InitializationStage       string
	InitializationProgressPct float64
	TransportMode             string
	CurrentConnections        int
	CurrentConnectionsME      int
	CurrentConnectionsDirect  int
	ActiveUsers               int
	UptimeSeconds             float64
	ConnectionsTotal          uint64
	ConnectionsBadTotal       uint64
	HandshakeTimeoutsTotal    uint64
	ConfiguredUsers           int
	DCCoveragePct             float64
	HealthyUpstreams          int
	TotalUpstreams            int
}

TelemetryRuntimeCurrentRecord stores one node's latest fast Telemt runtime summary.

type TelemetryRuntimeDCRecord

type TelemetryRuntimeDCRecord struct {
	AgentID            string
	DC                 int
	ObservedAt         time.Time
	AvailableEndpoints int
	AvailablePct       float64
	RequiredWriters    int
	AliveWriters       int
	CoveragePct        float64
	RTTMs              float64
	Load               float64
}

TelemetryRuntimeDCRecord stores one node's latest DC health row.

type TelemetryRuntimeEventRecord

type TelemetryRuntimeEventRecord struct {
	AgentID    string
	Sequence   int64
	ObservedAt time.Time
	Timestamp  time.Time
	EventType  string
	Context    string
	Severity   string
}

TelemetryRuntimeEventRecord stores one recent runtime event observed for a node.

type TelemetryRuntimeUpstreamRecord

type TelemetryRuntimeUpstreamRecord struct {
	AgentID            string
	UpstreamID         int
	ObservedAt         time.Time
	RouteKind          string
	Address            string
	Healthy            bool
	Fails              int
	EffectiveLatencyMs float64
}

TelemetryRuntimeUpstreamRecord stores one node's latest upstream health row.

type TelemetrySecurityInventoryCurrentRecord

type TelemetrySecurityInventoryCurrentRecord struct {
	AgentID      string
	ObservedAt   time.Time
	State        string
	StateReason  string
	Enabled      bool
	EntriesTotal int
	EntriesJSON  string
}

TelemetrySecurityInventoryCurrentRecord stores the latest security inventory payload for one node.

type TelemetryStore

type TelemetryStore interface {
	PutTelemetryRuntimeCurrent(ctx context.Context, record TelemetryRuntimeCurrentRecord) error
	GetTelemetryRuntimeCurrent(ctx context.Context, agentID string) (TelemetryRuntimeCurrentRecord, error)
	ListTelemetryRuntimeCurrent(ctx context.Context) ([]TelemetryRuntimeCurrentRecord, error)
	ReplaceTelemetryRuntimeDCs(ctx context.Context, agentID string, records []TelemetryRuntimeDCRecord) error
	ListTelemetryRuntimeDCs(ctx context.Context, agentID string) ([]TelemetryRuntimeDCRecord, error)
	ReplaceTelemetryRuntimeUpstreams(ctx context.Context, agentID string, records []TelemetryRuntimeUpstreamRecord) error
	ListTelemetryRuntimeUpstreams(ctx context.Context, agentID string) ([]TelemetryRuntimeUpstreamRecord, error)
	AppendTelemetryRuntimeEvents(ctx context.Context, agentID string, records []TelemetryRuntimeEventRecord) error
	ListTelemetryRuntimeEvents(ctx context.Context, agentID string, limit int) ([]TelemetryRuntimeEventRecord, error)
	PruneTelemetryRuntimeEvents(ctx context.Context, olderThan time.Time) (int64, error)
	PutTelemetryDiagnosticsCurrent(ctx context.Context, record TelemetryDiagnosticsCurrentRecord) error
	GetTelemetryDiagnosticsCurrent(ctx context.Context, agentID string) (TelemetryDiagnosticsCurrentRecord, error)
	PutTelemetrySecurityInventoryCurrent(ctx context.Context, record TelemetrySecurityInventoryCurrentRecord) error
	GetTelemetrySecurityInventoryCurrent(ctx context.Context, agentID string) (TelemetrySecurityInventoryCurrentRecord, error)
	PutTelemetryDetailBoost(ctx context.Context, record TelemetryDetailBoostRecord) error
	ListTelemetryDetailBoosts(ctx context.Context) ([]TelemetryDetailBoostRecord, error)
	DeleteTelemetryDetailBoost(ctx context.Context, agentID string) error
}

TelemetryStore persists current Telemt telemetry projections and recent runtime events.

type TimeseriesStore

type TimeseriesStore interface {
	AppendServerLoadPoint(ctx context.Context, record ServerLoadPointRecord) error
	// AppendServerLoadPointsBulk inserts a batch of server-load points in a
	// single transaction. Same ON-CONFLICT DO NOTHING semantics as the
	// single-row variant. Empty slice is a no-op. See P3-PERF-01a.
	AppendServerLoadPointsBulk(ctx context.Context, records []ServerLoadPointRecord) error
	ListServerLoadPoints(ctx context.Context, agentID string, from time.Time, to time.Time) ([]ServerLoadPointRecord, error)
	PruneServerLoadPoints(ctx context.Context, olderThan time.Time) (int64, error)
	AppendDCHealthPoint(ctx context.Context, record DCHealthPointRecord) error
	// AppendDCHealthPointsBulk inserts a batch of DC-health points in a
	// single transaction. Same ON-CONFLICT DO NOTHING semantics. Empty
	// slice is a no-op. See P3-PERF-01a.
	AppendDCHealthPointsBulk(ctx context.Context, records []DCHealthPointRecord) error
	ListDCHealthPoints(ctx context.Context, agentID string, from time.Time, to time.Time) ([]DCHealthPointRecord, error)
	PruneDCHealthPoints(ctx context.Context, olderThan time.Time) (int64, error)
	UpsertClientIPHistory(ctx context.Context, record ClientIPHistoryRecord) error
	// UpsertClientIPHistoryBulk upserts a batch of client-ip history rows in
	// a single transaction. Same semantics as the single-row UPSERT
	// (last_seen is updated on conflict). Empty slice is a no-op. See
	// P3-PERF-01a.
	UpsertClientIPHistoryBulk(ctx context.Context, records []ClientIPHistoryRecord) error
	ListClientIPHistory(ctx context.Context, clientID string, from time.Time, to time.Time) ([]ClientIPHistoryRecord, error)
	CountUniqueClientIPs(ctx context.Context, clientID string) (int, error)
	PruneClientIPHistory(ctx context.Context, olderThan time.Time) (int64, error)
	RollupServerLoadHourly(ctx context.Context, bucketHour time.Time) error
	ListServerLoadHourly(ctx context.Context, agentID string, from time.Time, to time.Time) ([]ServerLoadHourlyRecord, error)
	PruneServerLoadHourly(ctx context.Context, olderThan time.Time) (int64, error)
}

TimeseriesStore persists historical metric points for server load, DC health, and client IPs.

type TxFn

type TxFn func(tx Store) error

TxFn is the callback invoked by Store.Transact. The tx argument implements the full Store interface so that existing methods compose without duplication — see P2-ARCH-01.

NOTE: TxFn MUST NOT call tx.Transact recursively. Nested Transact calls on the same connection would deadlock (SQLite) or escalate isolation requirements unpredictably (PostgreSQL). Both backends detect the nested call and return ErrNestedTransact.

type UpdateConfigStore

type UpdateConfigStore interface {
	PutUpdateSettings(ctx context.Context, settings json.RawMessage) error
	GetUpdateSettings(ctx context.Context) (json.RawMessage, error)
	PutUpdateState(ctx context.Context, state json.RawMessage) error
	GetUpdateState(ctx context.Context) (json.RawMessage, error)
}

UpdateConfigStore persists update settings and cached version state as opaque JSON blobs.

type UserAppearanceRecord

type UserAppearanceRecord struct {
	UserID    string
	Theme     string
	Density   string
	HelpMode  string
	UpdatedAt time.Time
}

UserAppearanceRecord stores one user's persisted appearance preferences.

type UserAppearanceStore

type UserAppearanceStore interface {
	PutUserAppearance(ctx context.Context, appearance UserAppearanceRecord) error
	GetUserAppearance(ctx context.Context, userID string) (UserAppearanceRecord, error)
	ListUserAppearances(ctx context.Context) ([]UserAppearanceRecord, error)
}

UserAppearanceStore persists per-user appearance preferences.

type UserRecord

type UserRecord struct {
	ID           string
	Username     string
	PasswordHash string
	Role         string
	TotpEnabled  bool
	TotpSecret   string
	CreatedAt    time.Time
}

UserRecord stores one local control-plane account.

type UserStore

type UserStore interface {
	PutUser(ctx context.Context, user UserRecord) error
	DeleteUser(ctx context.Context, userID string) error
	GetUserByID(ctx context.Context, userID string) (UserRecord, error)
	GetUserByUsername(ctx context.Context, username string) (UserRecord, error)
	ListUsers(ctx context.Context) ([]UserRecord, error)
}

UserStore persists local control-plane user records.

Directories

Path Synopsis
Package postgres bulk insert helpers (P3-PERF-01a).
Package postgres bulk insert helpers (P3-PERF-01a).
Package sqlite bulk insert helpers (P3-PERF-01a).
Package sqlite bulk insert helpers (P3-PERF-01a).

Jump to

Keyboard shortcuts

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