Help us shape the future of Go! Take the 2026 Go Developer Survey

store

package
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const GitSyncConflictMetric = "gitsync_conflict"

Variables

View Source
var ErrAPIKeyNameTaken = errors.New("api key name already exists for this user")

ErrAPIKeyNameTaken is returned by CreateAPIKey when the user already has a key with the same name. Global sidecars identify keys by (username, name), so duplicates would collapse into one on FS -> DB reconcile.

Functions

func SelectTiers

func SelectTiers(rangeStr string) ([]string, int)

SelectTiers returns the tiers to query (primary + feeder tiers with unrolled data) and the display interval for a range string.

Types

type APIKeyRecord

type APIKeyRecord struct {
	ID         int64
	UserID     int64
	KeyHash    string
	Name       string
	CreatedAt  time.Time
	ExpiresAt  *time.Time
	LastUsedAt *time.Time
}

type ActivityFilter

type ActivityFilter struct {
	AppID         *int64
	AppSlug       string
	Categories    []string
	Before        int64
	Limit         int
	AllowedAppIDs []int64 // nil = unrestricted; empty slice = only system (app_id IS NULL) rows
	ActorUserID   *int64  // when set with AllowedAppIDs, restricts the app_id IS NULL branch to own auth events
	// CurrentAppID scopes rows to the live incarnation of an app. It keeps
	// rows with app_id = CurrentAppID and app_id IS NULL rows that belong to
	// this incarnation: rows not older than the apps row's created_at, and
	// rows from the app's most recent lifecycle/created event onward (that
	// event and the first compose change are recorded before the reconciler
	// inserts the apps row), provided that event is newer than the slug's
	// latest lifecycle/purged row. Rows left behind by a purged app that
	// used the same slug are excluded.
	CurrentAppID *int64
}

ActivityFilter controls which rows ListActivity returns.

type AlertHistory

type AlertHistory struct {
	ID         int64      `json:"id"`
	RuleID     *int64     `json:"rule_id"`
	FiredAt    time.Time  `json:"fired_at"`
	ResolvedAt *time.Time `json:"resolved_at"`
	Value      float64    `json:"value"`
	Metric     string     `json:"metric"`
	AppSlug    string     `json:"app_slug"`
	Operator   string     `json:"operator"`
	Threshold  float64    `json:"threshold"`
}

type AlertRule

type AlertRule struct {
	ID          int64     `json:"id"`
	AppID       *int64    `json:"app_id"`
	AppSlug     string    `json:"app_slug,omitempty"`
	Metric      string    `json:"metric"`
	Operator    string    `json:"operator"`
	Threshold   float64   `json:"threshold"`
	DurationSec int       `json:"duration_sec"`
	WebhookID   int64     `json:"webhook_id"`
	Enabled     bool      `json:"enabled"`
	CreatedAt   time.Time `json:"created_at"`
}

type App

type App struct {
	ID          int64
	Name        string
	Slug        string
	ComposePath string
	Status      string
	Domain      string
	ComposeHash string
	CreatedAt   time.Time
	UpdatedAt   time.Time
	ArchivedAt  sql.NullTime
}

type AuditEntry

type AuditEntry struct {
	ID               int64           `json:"id"`
	AppID            *int64          `json:"app_id"`
	AppSlug          string          `json:"app_slug"`
	ActorUserID      *int64          `json:"actor_user_id"`
	ActorName        string          `json:"actor_name"`
	ActorSource      string          `json:"actor_source"`
	IP               string          `json:"ip"`
	Category         string          `json:"category"`
	Action           string          `json:"action"`
	Target           string          `json:"target"`
	Summary          string          `json:"summary"`
	BeforeJSON       json.RawMessage `json:"before_json,omitempty"`
	AfterJSON        json.RawMessage `json:"after_json,omitempty"`
	Error            string          `json:"error,omitempty"`
	ComposeVersionID *int64          `json:"compose_version_id"`
	// SyncEligible is input-only: set it before calling RecordAudit to request
	// sync tracking (stored as sync_status='pending'). It is NOT a stored column
	// and is never populated on read; inspect SyncStatus directly instead.
	SyncEligible  bool      `json:"-"`
	SyncStatus    *string   `json:"sync_status"`
	SyncCommitSHA string    `json:"sync_commit_sha,omitempty"`
	SyncError     string    `json:"sync_error,omitempty"`
	CreatedAt     time.Time `json:"created_at"`
}

AuditEntry represents a single row in the audit_log table.

type BackupConfig

type BackupConfig struct {
	ID               int64     `json:"id"`
	UUID             string    `json:"uuid"`
	AppID            int64     `json:"app_id"`
	Strategy         string    `json:"strategy"`
	Target           string    `json:"target"`
	ScheduleCron     string    `json:"schedule_cron"`
	TargetConfigJSON string    `json:"target_config_json"`
	RetentionMode    string    `json:"retention_mode"`
	RetentionCount   int       `json:"retention_count"`
	RetentionDays    *int      `json:"retention_days"`
	VerifyUpload     bool      `json:"verify_upload"`
	PreHooks         string    `json:"pre_hooks"`
	PostHooks        string    `json:"post_hooks"`
	Paths            string    `json:"paths"`
	CreatedAt        time.Time `json:"created_at"`
	UpdatedAt        time.Time `json:"updated_at"`
}

type BackupRun

type BackupRun struct {
	ID               int64      `json:"id"`
	BackupConfigID   int64      `json:"backup_config_id"`
	Status           string     `json:"status"`
	SizeBytes        *int64     `json:"size_bytes"`
	Checksum         string     `json:"checksum"`
	FilePath         string     `json:"file_path"`
	ComposeVersionID *int64     `json:"compose_version_id"`
	StartedAt        time.Time  `json:"started_at"`
	FinishedAt       *time.Time `json:"finished_at"`
	ErrorMsg         string     `json:"error_msg"`
}

type BackupRunWithApp

type BackupRunWithApp struct {
	BackupRun
	AppName  string `json:"app_name"`
	AppSlug  string `json:"app_slug"`
	Strategy string `json:"strategy"`
}

BackupRunWithApp extends BackupRun with app and strategy info for cross-app views.

type BackupSummaryApp

type BackupSummaryApp struct {
	AppSlug            string   `json:"app_slug"`
	AppName            string   `json:"app_name"`
	ConfigCount        int      `json:"config_count"`
	Strategies         []string `json:"strategies"`
	LastRunStatus      string   `json:"last_run_status"`
	LastRunFinishedAt  *string  `json:"last_run_finished_at"`
	LastRunSizeBytes   *int64   `json:"last_run_size_bytes"`
	TotalSizeBytes     int64    `json:"total_size_bytes"`
	RecentSuccessCount int      `json:"recent_success_count"`
	RecentFailCount    int      `json:"recent_fail_count"`
	NextCron           string   `json:"next_cron"`
}

BackupSummaryApp holds aggregated backup health for one app.

type ComposeVersion

type ComposeVersion struct {
	ID          int64     `json:"id"`
	AppID       int64     `json:"app_id"`
	Version     int       `json:"version"`
	Content     string    `json:"content"`
	Hash        string    `json:"hash"`
	Name        *string   `json:"name"`
	Notes       *string   `json:"notes"`
	EnvSnapshot *string   `json:"env_snapshot"`
	CreatedAt   time.Time `json:"created_at"`
}

ComposeVersion holds a stored snapshot of a compose file.

type DBBackupRun

type DBBackupRun struct {
	ID        int64  `json:"id"`
	FilePath  string `json:"file_path"`
	SizeBytes int64  `json:"size_bytes"`
	Status    string `json:"status"`
	Compact   bool   `json:"compact"`
	ErrorMsg  string `json:"error_msg,omitempty"`
	CreatedAt string `json:"created_at"`
}

type DBStats

type DBStats struct {
	Apps           int64 `json:"apps"`
	Users          int64 `json:"users"`
	Metrics        int64 `json:"metrics"`
	RequestMetrics int64 `json:"request_metrics"`
	AlertRules     int64 `json:"alert_rules"`
	BackupRuns     int64 `json:"backup_runs"`
	MigrationVer   int64 `json:"migration_version"`
}

DBStats holds aggregate counts for the system info endpoint.

type DeployEvent

type DeployEvent struct {
	ID        int64     `json:"id"`
	AppSlug   string    `json:"app_slug"`
	Action    string    `json:"action"`
	UserID    *int64    `json:"user_id"`
	Detail    string    `json:"detail"`
	CreatedAt time.Time `json:"created_at"`
}

DeployEvent records a deploy/rollback action.

type ListAppsOptions

type ListAppsOptions struct {
	IncludeArchived bool
	OnlyArchived    bool
}

ListAppsOptions controls archive filtering for list queries.

type MutationHook

type MutationHook func(scope MutationScope, slug string)

MutationHook is called after a successful mutating DB operation. scope is Global for cross-app entities, App for per-app entities. slug is the app slug when scope is App, otherwise empty. Implementations must not block (callers may hold locks).

type MutationScope

type MutationScope int

MutationScope describes what kind of entity changed.

const (
	ScopeGlobal MutationScope = iota
	ScopeApp
)

type RecipePullCount

type RecipePullCount struct {
	RecipeID string `json:"recipe_id"`
	Count    int    `json:"count"`
}

type Registry

type Registry struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	URL         string    `json:"url"`
	UsernameEnc string    `json:"-"`
	PasswordEnc string    `json:"-"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

type Store

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

func Open

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

func (*Store) AccessibleAppIDs

func (s *Store) AccessibleAppIDs(ctx context.Context, userID int64) ([]int64, error)

AccessibleAppIDs returns the app IDs the user has explicit access grants for. Does NOT include super_admin bypass; callers must check role separately.

func (*Store) ActivityInAppFeed added in v1.4.3

func (s *Store) ActivityInAppFeed(ctx context.Context, id, appID int64) (bool, error)

ActivityInAppFeed reports whether audit row id is part of the activity feed of app appID as non-admins see it: same slug, scoped to the app's current incarnation (ActivityFilter{AppSlug, CurrentAppID}).

func (*Store) AggregateMetrics

func (s *Store) AggregateMetrics(sourceTier, destTier string, olderThan time.Time) error

AggregateMetrics reads points from sourceTier older than olderThan, groups by app_id, container_id, and time bucket, inserts as destTier. Orphan rows (app_id of an app deleted while foreign keys were not enforced) are not carried into destTier, since that insert would violate the foreign key and abort the rollup; the source DELETE still removes them.

func (*Store) AggregateRequestMetrics

func (s *Store) AggregateRequestMetrics(sourceTier, destTier string, olderThan time.Time) error

AggregateRequestMetrics reads points from sourceTier older than olderThan, groups by app_id and time bucket, inserts as destTier. Orphan rows (app deleted while foreign keys were not enforced) are dropped instead of carried into destTier, where the insert would violate the foreign key.

func (*Store) BackfillBackupConfigUUIDs

func (s *Store) BackfillBackupConfigUUIDs() (int, error)

BackfillBackupConfigUUIDs assigns a UUID to any backup_configs row whose uuid is null or empty. Returns the number of rows updated.

func (*Store) BumpTokenVersion

func (s *Store) BumpTokenVersion(id int64) error

BumpTokenVersion increments the user's token_version, invalidating any outstanding JWT. Called on logout.

func (*Store) ClearAlertHistory

func (s *Store) ClearAlertHistory(resolvedOnly bool) error

func (*Store) Close

func (s *Store) Close() error

func (*Store) CountAudit

func (s *Store) CountAudit(ctx context.Context) (int64, error)

CountAudit returns the current number of rows in audit_log.

func (*Store) CreateAPIKey

func (s *Store) CreateAPIKey(userID int64, keyHash, name string, expiresAt *time.Time) (*APIKeyRecord, error)

CreateAPIKey inserts a new API key record and returns it. expiresAt may be nil for keys that never expire. Returns ErrAPIKeyNameTaken if the user already has a key with this name. No DB unique constraint is added because existing installs may already hold duplicates; the check-and-insert is a single statement so concurrent creates cannot race past it.

func (*Store) CreateAlertHistory

func (s *Store) CreateAlertHistory(ruleID int64, value float64, rule *AlertRule) (*AlertHistory, error)

func (*Store) CreateAlertRule

func (s *Store) CreateAlertRule(r *AlertRule) error

func (*Store) CreateBackupConfig

func (s *Store) CreateBackupConfig(cfg *BackupConfig) error

func (*Store) CreateBackupRun

func (s *Store) CreateBackupRun(configID int64) (*BackupRun, error)

func (*Store) CreateComposeVersion

func (s *Store) CreateComposeVersion(appID int64, content, hash string) error

CreateComposeVersion inserts a new version for the app, auto-incrementing the version number per app, then prunes versions beyond the most recent 10.

func (*Store) CreateDBBackupRun

func (s *Store) CreateDBBackupRun(filePath string, sizeBytes int64, compact bool, status string, errMsg string) error

func (*Store) CreateDeployEvent

func (s *Store) CreateDeployEvent(appSlug, action string, userID *int64, detail string) error

CreateDeployEvent records an action (deploy/rollback) for an app.

func (*Store) CreateRegistry

func (s *Store) CreateRegistry(name, url, usernameEnc, passwordEnc string) (*Registry, error)

func (*Store) CreateUser

func (s *Store) CreateUser(username, passwordHash, role, displayName, email string) (*User, error)

CreateUser inserts a new user and returns it.

func (*Store) CreateWebhook

func (s *Store) CreateWebhook(w *Webhook) error

func (*Store) DB

func (s *Store) DB() *sql.DB

func (*Store) DeleteAPIKey

func (s *Store) DeleteAPIKey(id, userID int64) error

DeleteAPIKey deletes the API key with the given ID, scoped to the owning user. super_admin can delete any key by passing userID=0.

func (*Store) DeleteAlertRule

func (s *Store) DeleteAlertRule(id int64) error

func (*Store) DeleteAlertRulesForApp

func (s *Store) DeleteAlertRulesForApp(appID int64) error

DeleteAlertRulesForApp deletes all alert rules for the given app. Used by configsync ImportAppSidecar for full-replace semantics.

func (*Store) DeleteApp

func (s *Store) DeleteApp(slug string) error

DeleteApp deletes the app with the given slug. Returns an error if not found.

func (*Store) DeleteBackupConfig

func (s *Store) DeleteBackupConfig(id int64) error

func (*Store) DeleteBackupConfigsForApp

func (s *Store) DeleteBackupConfigsForApp(appID int64) error

DeleteBackupConfigsForApp deletes all backup configs for the given app. Used by configsync ImportAppSidecar for full-replace semantics.

func (*Store) DeleteComposeVersion

func (s *Store) DeleteComposeVersion(id int64) error

DeleteComposeVersion removes a single version by ID.

func (*Store) DeleteGitSyncConfig

func (s *Store) DeleteGitSyncConfig() error

DeleteGitSyncConfig removes all rows from gitsync_config (disables DB overrides).

func (*Store) DeleteRegistry

func (s *Store) DeleteRegistry(id string) error

func (*Store) DeleteUser

func (s *Store) DeleteUser(id int64) error

DeleteUser deletes the user with the given ID.

func (*Store) DeleteWebhook

func (s *Store) DeleteWebhook(id int64) error

func (*Store) EmailTaken

func (s *Store) EmailTaken(email string, excludeID int64) (bool, error)

EmailTaken returns true if the email is already used by another user.

func (*Store) GetAPIKeyByHash

func (s *Store) GetAPIKeyByHash(hash string) (*APIKeyRecord, *User, error)

GetAPIKeyByHash returns the key record and associated user for the given hash.

func (*Store) GetActiveAlert

func (s *Store) GetActiveAlert(ruleID int64) (*AlertHistory, error)

func (*Store) GetActivity

func (s *Store) GetActivity(ctx context.Context, id int64) (AuditEntry, error)

GetActivity returns a single audit_log row by id, including before/after JSON.

func (*Store) GetAppByID

func (s *Store) GetAppByID(id int64) (*App, error)

GetAppByID returns the app with the given id or an error if not found.

func (*Store) GetAppBySlug

func (s *Store) GetAppBySlug(slug string) (*App, error)

GetAppBySlug returns the app with the given slug or an error if not found.

func (*Store) GetAppLabels

func (s *Store) GetAppLabels(slug string) (map[string]string, error)

GetAppLabels returns all labels for the app with the given slug.

func (*Store) GetAuditRetentionDays

func (s *Store) GetAuditRetentionDays(ctx context.Context) (int, error)

GetAuditRetentionDays returns the configured audit log retention in days. Returns 365 if not set.

func (*Store) GetBackupConfig

func (s *Store) GetBackupConfig(id int64) (*BackupConfig, error)

func (*Store) GetBackupRun

func (s *Store) GetBackupRun(id int64) (*BackupRun, error)

func (*Store) GetBackupSummary

func (s *Store) GetBackupSummary() ([]BackupSummaryApp, error)

func (*Store) GetComposeVersion

func (s *Store) GetComposeVersion(id int64) (*ComposeVersion, error)

GetComposeVersion returns a single version by its primary key.

func (*Store) GetDBBackupConfig

func (s *Store) GetDBBackupConfig() (map[string]string, error)

func (*Store) GetDBStats

func (s *Store) GetDBStats() (DBStats, error)

GetDBStats returns aggregate row counts and the current migration version.

func (*Store) GetGitSyncConfig

func (s *Store) GetGitSyncConfig() (map[string]string, error)

GetGitSyncConfig returns all key/value pairs from gitsync_config. Returns an empty map (not nil) when no rows exist.

func (*Store) GetMeta

func (s *Store) GetMeta(key string) (string, bool, error)

GetMeta returns the value for the given key. The bool is false when the key does not exist.

func (*Store) GetMetricsTierStats

func (s *Store) GetMetricsTierStats() ([]TierStat, error)

GetMetricsTierStats returns row counts grouped by tier for the metrics table.

func (*Store) GetRegistry

func (s *Store) GetRegistry(id string) (*Registry, error)

func (*Store) GetRegistryByName

func (s *Store) GetRegistryByName(name string) (*Registry, error)

func (*Store) GetRequestMetricsTierStats

func (s *Store) GetRequestMetricsTierStats() ([]TierStat, error)

GetRequestMetricsTierStats returns row counts grouped by tier for the request_metrics table.

func (*Store) GetUserAppSlugs

func (s *Store) GetUserAppSlugs(userID int64) ([]string, error)

GetUserAppSlugs returns the list of app slugs accessible to the given user.

func (*Store) GetUserByID

func (s *Store) GetUserByID(id int64) (*User, error)

GetUserByID returns the user with the given ID.

func (*Store) GetUserByUsername

func (s *Store) GetUserByUsername(username string) (*User, error)

GetUserByUsername returns the user with the given username.

func (*Store) GetWebhook

func (s *Store) GetWebhook(id int64) (*Webhook, error)

func (*Store) GrantAppAccess

func (s *Store) GrantAppAccess(userID, appID int64) error

GrantAppAccess grants a user access to an app.

func (*Store) HasAppAccess

func (s *Store) HasAppAccess(userID int64, appSlug string) (bool, error)

HasAppAccess returns true if the user has access to the app (by slug). super_admins always return true.

func (*Store) HasAppAccessByID

func (s *Store) HasAppAccessByID(userID int64, appID int64) (bool, error)

HasAppAccessByID returns true if the user has access to the app (by id). super_admins always return true.

func (*Store) IncrementalVacuum

func (s *Store) IncrementalVacuum() error

IncrementalVacuum reclaims free pages from the database file. It is a no-op on databases whose auto_vacuum mode is NONE (created before auto_vacuum was applied correctly) until VacuumDB converts them.

func (*Store) InsertConflictAlert

func (s *Store) InsertConflictAlert(path, remoteSHA, description string) error

InsertConflictAlert records a gitsync conflict in alert_history with a NULL rule_id (no real alert rule). The metric column is set to GitSyncConflictMetric so callers can filter by it.

func (*Store) InsertMetrics

func (s *Store) InsertMetrics(points []metrics.MetricPoint) error

InsertMetrics batch-inserts metric points in a single transaction. Points whose app no longer exists (deleted between collection and flush) are skipped: inserting them would fail the foreign key and, with it, the whole batch. Points with a nil AppID (system metrics) are always kept.

func (*Store) InsertRequestMetrics

func (s *Store) InsertRequestMetrics(points []metrics.RequestMetricPoint) error

InsertRequestMetrics batch-inserts request metric points in a single transaction. Points whose app no longer exists (deleted between the request and the flush) are skipped so one stale point cannot fail the whole batch on the foreign key.

func (*Store) ListAPIKeysByUser

func (s *Store) ListAPIKeysByUser(userID int64) ([]APIKeyRecord, error)

ListAPIKeysByUser returns all API keys for the given user.

func (*Store) ListAccessForApp

func (s *Store) ListAccessForApp(appID int64) ([]string, error)

ListAccessForApp returns usernames of users with explicit access to appID. Used by configsync to export access grants to disk.

func (*Store) ListActiveAlertRules

func (s *Store) ListActiveAlertRules() ([]AlertRule, error)

func (*Store) ListActivity

func (s *Store) ListActivity(ctx context.Context, f ActivityFilter) (entries []AuditEntry, nextBefore int64, err error)

ListActivity returns audit_log rows matching the filter, ordered by id DESC. before_json and after_json are always NULL in list results (use GetActivity for full row). Returns entries and a cursor (nextBefore) for the next page; 0 means no more pages.

func (*Store) ListAlertHistory

func (s *Store) ListAlertHistory(ruleID *int64, limit int) ([]AlertHistory, error)

func (*Store) ListAlertRules

func (s *Store) ListAlertRules(appID *int64) ([]AlertRule, error)

func (*Store) ListApps

func (s *Store) ListApps() ([]App, error)

ListApps returns all non-archived apps ordered by name.

func (*Store) ListAppsWithOptions

func (s *Store) ListAppsWithOptions(opts ListAppsOptions) ([]App, error)

ListAppsWithOptions returns apps filtered by archive state.

func (*Store) ListArchivedApps

func (s *Store) ListArchivedApps() ([]App, error)

ListArchivedApps returns only archived apps ordered by name.

func (*Store) ListBackupConfigs

func (s *Store) ListBackupConfigs(appID *int64) ([]BackupConfig, error)

func (*Store) ListBackupRuns

func (s *Store) ListBackupRuns(configID int64) ([]BackupRun, error)

func (*Store) ListComposeVersions

func (s *Store) ListComposeVersions(appID int64) ([]ComposeVersion, error)

ListComposeVersions returns versions for an app ordered newest first.

func (*Store) ListDBBackupRuns

func (s *Store) ListDBBackupRuns(limit int) ([]DBBackupRun, error)

func (*Store) ListDeployEvents

func (s *Store) ListDeployEvents(appSlug string) ([]DeployEvent, error)

ListDeployEvents returns the 50 most recent events for an app.

func (*Store) ListOldBackupRuns

func (s *Store) ListOldBackupRuns(configID int64, keepCount int) ([]BackupRun, error)

func (*Store) ListOldBackupRunsByTime

func (s *Store) ListOldBackupRunsByTime(configID int64, maxAgeDays int) ([]BackupRun, error)

func (*Store) ListRecentBackupRuns

func (s *Store) ListRecentBackupRuns(limit int) ([]BackupRunWithApp, error)

func (*Store) ListRegistries

func (s *Store) ListRegistries() ([]Registry, error)

func (*Store) ListUsers

func (s *Store) ListUsers() ([]User, error)

ListUsers returns all users ordered by username, excluding password_hash.

func (*Store) ListUsersWithHashes

func (s *Store) ListUsersWithHashes() ([]User, error)

ListUsersWithHashes returns all users including password_hash, ordered by username. Used by configsync to export full user records to disk.

func (*Store) ListWebhooks

func (s *Store) ListWebhooks() ([]Webhook, error)

func (*Store) MarkAppArchived

func (s *Store) MarkAppArchived(slug string, at time.Time) error

MarkAppArchived sets archived_at on the app with the given slug.

func (*Store) MarkSyncFailed

func (s *Store) MarkSyncFailed(ctx context.Context, ids []int64, errMsg string) error

MarkSyncFailed sets sync_status='failed' and records the error message for the given ids.

func (*Store) MarkSyncSynced

func (s *Store) MarkSyncSynced(ctx context.Context, ids []int64, commitSHA string) error

MarkSyncSynced sets sync_status='synced' and records the commit SHA for the given ids.

func (*Store) PendingSyncAuditIDs

func (s *Store) PendingSyncAuditIDs(ctx context.Context) ([]int64, error)

PendingSyncAuditIDs returns ids of audit_log rows with sync_status='pending', ordered by id.

func (*Store) PruneAudit

func (s *Store) PruneAudit(ctx context.Context, olderThan time.Time) (int64, error)

PruneAudit deletes audit_log rows with created_at before olderThan. Returns the number of rows deleted.

func (*Store) PruneDBBackupRuns

func (s *Store) PruneDBBackupRuns(keepCount int) ([]string, error)

func (*Store) PruneMetrics

func (s *Store) PruneMetrics(tier string, before time.Time) (int64, error)

PruneMetrics deletes metric points with the given tier older than before.

func (*Store) PruneRequestMetrics

func (s *Store) PruneRequestMetrics(tier string, before time.Time) (int64, error)

PruneRequestMetrics deletes request metric points with the given tier older than before.

func (*Store) PurgeApp

func (s *Store) PurgeApp(slug string) error

PurgeApp deletes an app and every related history row (audit, deploy events, compose versions, backups, alerts, labels, access). Use when removing an app for good. Runs in a single transaction.

func (*Store) PurgeAudit

func (s *Store) PurgeAudit(ctx context.Context) error

PurgeAudit deletes all rows from audit_log.

func (*Store) QueryMetrics

func (s *Store) QueryMetrics(appID *int64, rangeStr string) ([]metrics.MetricPoint, int, error)

QueryMetrics returns metric points for the given app and range string. Returns the points, the interval in seconds, and any error.

func (*Store) QueryRequestMetrics

func (s *Store) QueryRequestMetrics(appID int64, rangeStr string) ([]metrics.RequestMetricPoint, int, error)

QueryRequestMetrics returns request metric points for the given app and range. Returns the points, interval in seconds, and any error.

func (*Store) RecipePullCounts

func (s *Store) RecipePullCounts(ctx context.Context, limit int) ([]RecipePullCount, error)

RecipePullCounts returns top-N recipe pull counts. limit <= 0 means no limit.

func (*Store) RecordAudit

func (s *Store) RecordAudit(ctx context.Context, e AuditEntry) (int64, error)

RecordAudit inserts a new audit_log row and returns its id.

func (*Store) RecordRecipePull

func (s *Store) RecordRecipePull(ctx context.Context, recipeID string) error

RecordRecipePull logs a community-recipe pull event. Best-effort: errors are returned but callers may choose to log-and-continue.

func (*Store) ReplaceAppAccess

func (s *Store) ReplaceAppAccess(appID int64, usernames []string) error

ReplaceAppAccess atomically replaces all access grants for appID with the given usernames. Users that do not exist in the DB are silently skipped. Used by configsync ImportAppSidecar.

func (*Store) ResolveAlert

func (s *Store) ResolveAlert(historyID int64) error

func (*Store) ResolveAlertsByRule

func (s *Store) ResolveAlertsByRule(ruleID int64) error

func (*Store) RevokeAppAccess

func (s *Store) RevokeAppAccess(userID, appID int64) error

RevokeAppAccess revokes a user's access to an app.

func (*Store) SetAuditRetentionDays

func (s *Store) SetAuditRetentionDays(ctx context.Context, days int) error

SetAuditRetentionDays persists the audit log retention in days.

func (*Store) SetDBBackupConfig

func (s *Store) SetDBBackupConfig(key, value string) error

func (*Store) SetGitSyncConfig

func (s *Store) SetGitSyncConfig(kvs map[string]string) error

SetGitSyncConfig atomically upserts every key/value pair in kvs.

func (*Store) SetMeta

func (s *Store) SetMeta(key, value string) error

SetMeta upserts a key/value pair into system_meta.

func (*Store) SetMutationHook

func (s *Store) SetMutationHook(h MutationHook)

SetMutationHook installs a callback. Nil disables it. Safe to change at runtime.

func (*Store) UpdateAlertRule

func (s *Store) UpdateAlertRule(r *AlertRule) error

func (*Store) UpdateAppDisplayName

func (s *Store) UpdateAppDisplayName(slug, name string) error

UpdateAppDisplayName updates the name (display) field of the app with the given slug. No-op if the name already matches. Used by configsync ApplyAppSidecar.

func (*Store) UpdateAppStatus

func (s *Store) UpdateAppStatus(slug, status string) error

UpdateAppStatus updates the status field of the app with the given slug.

func (*Store) UpdateBackupConfig

func (s *Store) UpdateBackupConfig(cfg *BackupConfig) error

func (*Store) UpdateBackupRunFailed

func (s *Store) UpdateBackupRunFailed(id int64, errMsg string) error

func (*Store) UpdateBackupRunSuccess

func (s *Store) UpdateBackupRunSuccess(id int64, sizeBytes int64, filePath, checksum string) error

func (*Store) UpdateComposeVersion

func (s *Store) UpdateComposeVersion(id int64, name, notes, envSnapshot string) error

UpdateComposeVersion updates the name, notes, and env_snapshot for a version.

func (*Store) UpdatePassword

func (s *Store) UpdatePassword(id int64, newHash string) error

UpdatePassword updates the user's password hash and bumps token_version so existing JWT cookies are invalidated immediately.

func (*Store) UpdateProfile

func (s *Store) UpdateProfile(id int64, displayName, email string) error

UpdateProfile updates the user's display name and email.

func (*Store) UpdateRegistry

func (s *Store) UpdateRegistry(id, name, url, usernameEnc, passwordEnc string) error

func (*Store) UpdateUserFromRedacted

func (s *Store) UpdateUserFromRedacted(username, role, displayName, email string) error

UpdateUserFromRedacted updates display_name, email, and role for an existing user, leaving password_hash untouched. If the user does not exist, creates them with an empty password_hash (they cannot log in until an admin sets a password).

func (*Store) UpdateUserRole

func (s *Store) UpdateUserRole(id int64, role string) error

UpdateUserRole updates the user's role.

func (*Store) UpdateWebhook

func (s *Store) UpdateWebhook(w *Webhook) error

func (*Store) UpsertAPIKey

func (s *Store) UpsertAPIKey(username, keyHash, name string, expiresAt *time.Time) error

UpsertAPIKey inserts or updates an API key by key_hash. Used by configsync ImportGlobal.

func (*Store) UpsertApp

func (s *Store) UpsertApp(app *App, labels map[string]string) error

UpsertApp inserts or updates an app by slug and replaces its labels atomically.

func (*Store) UpsertRegistryByID

func (s *Store) UpsertRegistryByID(r *Registry) error

UpsertRegistryByID inserts or updates a registry by its string ID. Used by configsync ImportGlobal to restore encrypted registry credentials.

func (*Store) UpsertRegistryFromRedacted

func (s *Store) UpsertRegistryFromRedacted(id, name, url string) error

UpsertRegistryFromRedacted updates name+url if the registry exists; inserts with empty encrypted credentials if new. Preserves username_enc/password_enc on update.

func (*Store) UpsertUserByUsername

func (s *Store) UpsertUserByUsername(u *User) error

UpsertUserByUsername inserts or updates a user by username. Used by configsync ImportGlobal.

func (*Store) UpsertWebhookByName

func (s *Store) UpsertWebhookByName(w *Webhook) error

UpsertWebhookByName inserts or updates a webhook by name. If a webhook with this name already exists it is updated in-place. Used by configsync ImportGlobal.

func (*Store) UpsertWebhookFromRedacted

func (s *Store) UpsertWebhookFromRedacted(name, kind string) error

UpsertWebhookFromRedacted updates type if webhook exists; inserts with empty URL if new. Preserves URL, headers_json, and template_override on update.

func (*Store) UserCount

func (s *Store) UserCount() (int, error)

UserCount returns the total number of users.

func (*Store) VacuumDB

func (s *Store) VacuumDB() error

VacuumDB runs VACUUM on the SQLite database to reclaim unused space.

It also converts databases created before auto_vacuum was set up correctly to auto_vacuum=INCREMENTAL, so the daily IncrementalVacuum can reclaim free pages from then on. SQLite only changes the auto_vacuum mode of an existing file during a VACUUM, and only when the pragma was set on the same connection first, hence the dedicated conn. VACUUM rewrites the whole file anyway, so the conversion adds no extra cost.

func (*Store) VacuumInto

func (s *Store) VacuumInto(destPath string) error

func (*Store) WipeConfigForRestore

func (s *Store) WipeConfigForRestore() error

WipeConfigForRestore truncates config tables (children first) while leaving historical/operational tables (metrics, deploy_events, etc.) untouched. Intended for DR import --wipe. Foreign keys are enforced, so the deletes cascade: alert_history rows go with their alert_rules, backup_runs with their backup_configs, and audit_log.actor_user_id is set NULL for deleted users. Deleting children first keeps each statement's cascade small.

type TierStat

type TierStat struct {
	Tier  string `json:"tier"`
	Count int64  `json:"count"`
}

TierStat holds the row count for a single tier in a time-series table.

type User

type User struct {
	ID           int64
	Username     string
	PasswordHash string
	Role         string
	DisplayName  string
	Email        string
	CreatedAt    time.Time
	// TokenVersion is bumped on logout, password change, and role change.
	// JWTs embed the value at issue; the middleware rejects tokens whose
	// claim does not match. Provides server-side session invalidation
	// without a denylist.
	TokenVersion int64
}

type Webhook

type Webhook struct {
	ID               int64     `json:"id"`
	Name             string    `json:"name"`
	Type             string    `json:"type"`
	URL              string    `json:"url"`
	TemplateOverride string    `json:"template_override"`
	HeadersJSON      string    `json:"headers_json"`
	CreatedAt        time.Time `json:"created_at"`
}

Jump to

Keyboard shortcuts

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