db

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package db is the PostgreSQL persistence layer (pgx), running embedded migrations on startup.

Index

Constants

This section is empty.

Variables

View Source
var ErrSessionNotFound = errors.New("session not found")

ErrSessionNotFound is returned when a session does not exist or has expired.

Functions

This section is empty.

Types

type AuthSession

type AuthSession struct {
	ID        string    `json:"id"`
	Email     string    `json:"email"`
	Name      string    `json:"name"`
	Picture   string    `json:"picture"`
	CreatedAt time.Time `json:"createdAt"`
	ExpiresAt time.Time `json:"expiresAt"`
}

AuthSession represents a user authentication session.

type ConfigStore

type ConfigStore interface {
	Get(ctx context.Context, key string) (json.RawMessage, error)
	Set(ctx context.Context, key string, value json.RawMessage) error
	GetAll(ctx context.Context) (map[string]json.RawMessage, error)
	GetAppConfig(ctx context.Context) (config.AppConfig, error)
	UpdateAppConfig(ctx context.Context, c config.AppConfig) error
}

ConfigStore manages key-value application configuration.

func NewConfigStore

func NewConfigStore(pool *pgxpool.Pool) ConfigStore

NewConfigStore creates a new ConfigStore backed by PostgreSQL.

type Connector

type Connector struct {
	ID            uuid.UUID       `json:"id"`
	Name          string          `json:"name"`
	Type          string          `json:"type"`
	Description   string          `json:"description"`
	SecretGroupID *uuid.UUID      `json:"secretGroupId,omitempty"`
	Config        json.RawMessage `json:"config"`
	Enabled       bool            `json:"enabled"`
	IsDefault     bool            `json:"isDefault"`
	CreatedBy     string          `json:"createdBy"`
	UpdatedBy     string          `json:"updatedBy"`
	CreatedAt     time.Time       `json:"createdAt"`
	UpdatedAt     time.Time       `json:"updatedAt"`
}

Connector represents an external system connector (alert source or cloud target).

type ConnectorStore

type ConnectorStore interface {
	Save(ctx context.Context, name, connectorType, description string, secretGroupID *uuid.UUID, config json.RawMessage, isDefault bool, createdBy string) (*Connector, error)
	Get(ctx context.Context, id uuid.UUID) (*Connector, error)
	GetByName(ctx context.Context, name string) (*Connector, error)
	GetDefault(ctx context.Context, connectorType string) (*Connector, error)
	List(ctx context.Context) ([]Connector, error)
	Update(ctx context.Context, id uuid.UUID, name, description string, secretGroupID *uuid.UUID, config json.RawMessage, enabled bool, isDefault bool, updatedBy string) error
	Delete(ctx context.Context, id uuid.UUID) error
}

ConnectorStore manages connector persistence.

func NewConnectorStore

func NewConnectorStore(pool *pgxpool.Pool) ConnectorStore

NewConnectorStore creates a new ConnectorStore backed by PostgreSQL.

type DB

type DB struct {
	Pool *pgxpool.Pool
}

DB wraps a PostgreSQL connection pool.

func New

func New(ctx context.Context, databaseURL string) (*DB, error)

New creates a new DB connection pool and runs migrations.

func (*DB) Close

func (d *DB) Close()

Close closes the connection pool.

func (*DB) Migrate

func (d *DB) Migrate(databaseURL string) error

Migrate runs all pending database migrations.

type LatestAssertionResult

type LatestAssertionResult struct {
	AlertName string    `json:"alertName"`
	Passed    bool      `json:"passed"`
	RunID     uuid.UUID `json:"runId"`
	CreatedAt time.Time `json:"createdAt"`
}

LatestAssertionResult holds the most recent pass/fail for a given alert name.

type ListRunsFilters

type ListRunsFilters struct {
	// Name is an ILIKE %name% match against saved_scenarios.name.
	Name string
	// Types restricts saved_scenarios.type to the listed values.
	Types []string
	// Since restricts runs to created_at >= Since.
	Since *time.Time
	// ScenarioID restricts runs to the given saved_scenarios.id.
	ScenarioID *uuid.UUID
}

ListRunsFilters narrows the result set for RunStore.List. Zero values mean "no constraint on this dimension".

Note: filters that reference saved_scenarios columns (Name, Types) silently exclude ad-hoc runs whose scenario_id is NULL, because NULL never matches an equality/LIKE predicate.

type ListScenariosFilters

type ListScenariosFilters struct {
	// Name is an ILIKE %name% match against saved_scenarios.name.
	Name string
	// Types restricts saved_scenarios.type to the listed values.
	Types []string
	// Since restricts scenarios to updated_at >= Since.
	Since *time.Time
}

ListScenariosFilters narrows the result set for ScenarioStore.List. Zero values mean "no constraint on this dimension".

type Pack

type Pack struct {
	ID          uuid.UUID      `json:"id"`
	Name        string         `json:"name"`
	Type        string         `json:"type"`
	Source      string         `json:"source"`
	Version     string         `json:"version,omitempty"`
	Status      string         `json:"status"`
	Parameters  map[string]any `json:"parameters,omitempty"`
	InstalledBy string         `json:"installedBy"`
	CreatedAt   time.Time      `json:"createdAt"`
	UpdatedAt   time.Time      `json:"updatedAt"`
}

Pack represents an installed simulation pack.

type PackStore

type PackStore interface {
	Upsert(ctx context.Context, pack *Pack, installedBy string) error
	Get(ctx context.Context, name string) (*Pack, error)
	List(ctx context.Context) ([]Pack, error)
	Delete(ctx context.Context, name string) error
	UpdateParameters(ctx context.Context, name string, parameters map[string]any) error
}

PackStore manages pack persistence.

func NewPackStore

func NewPackStore(pool *pgxpool.Pool) PackStore

NewPackStore creates a new PackStore backed by PostgreSQL.

type Run

type Run struct {
	ID           uuid.UUID  `json:"id"`
	Status       string     `json:"status"`
	StartTime    time.Time  `json:"startTime"`
	EndTime      *time.Time `json:"endTime,omitempty"`
	Total        int        `json:"total"`
	Succeeded    int        `json:"succeeded"`
	Failed       int        `json:"failed"`
	ScenarioID   *uuid.UUID `json:"scenarioId,omitempty"`
	ScenarioName *string    `json:"scenarioName,omitempty"`
	ScenarioType *string    `json:"scenarioType,omitempty"`
	ScheduleID   *uuid.UUID `json:"scheduleId,omitempty"`
	ScheduleName *string    `json:"scheduleName,omitempty"`
	CreatedBy    string     `json:"createdBy"`
	CreatedAt    time.Time  `json:"createdAt"`
}

Run represents a single simrun execution.

type RunPage

type RunPage struct {
	Runs  []Run `json:"runs"`
	Total int   `json:"total"`
}

RunPage is a paginated slice of runs together with the total row count.

type RunStore

type RunStore interface {
	Create(ctx context.Context, run *Run) error
	Get(ctx context.Context, id uuid.UUID) (*Run, error)
	List(ctx context.Context, filters ListRunsFilters, limit, offset int) (RunPage, error)
	// ListExpired returns the IDs of runs created before cutoff whose status is
	// not "running" — the assessment-retention sweeper's deletion candidates.
	ListExpired(ctx context.Context, cutoff time.Time) ([]uuid.UUID, error)
	Update(ctx context.Context, id uuid.UUID, status string, total, succeeded, failed int, endTime *time.Time) error
	Delete(ctx context.Context, id uuid.UUID) error
	AddScenarioResult(ctx context.Context, runID uuid.UUID, result *ScenarioResult) error
	GetScenarioResults(ctx context.Context, runID uuid.UUID) ([]ScenarioResult, error)
	GetScenarioResult(ctx context.Context, id uuid.UUID) (*ScenarioResult, error)

	// Run lifecycle
	CompleteRun(ctx context.Context, id uuid.UUID, endTime *time.Time) error

	// Scenario status tracking
	CreateScenarioStatus(ctx context.Context, runID uuid.UUID, name string) (uuid.UUID, error)
	UpdateScenarioPhase(ctx context.Context, id uuid.UUID, phase string) error
	CompleteScenarioResult(ctx context.Context, id uuid.UUID, result *ScenarioResult) error
	IncrementRunCounters(ctx context.Context, id uuid.UUID, successDelta, failDelta int) error

	// GetLatestAssertionResults returns the most recent pass/fail for each alert name.
	GetLatestAssertionResults(ctx context.Context) ([]LatestAssertionResult, error)
}

RunStore manages run and scenario result persistence.

func NewRunStore

func NewRunStore(pool *pgxpool.Pool) RunStore

NewRunStore creates a new RunStore backed by PostgreSQL.

type SavedScenario

type SavedScenario struct {
	ID        uuid.UUID `json:"id"`
	Name      string    `json:"name"`
	Type      string    `json:"type"`
	YAML      string    `json:"yaml"`
	CreatedBy string    `json:"createdBy"`
	UpdatedBy string    `json:"updatedBy"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

SavedScenario represents a saved scenario configuration.

type ScenarioPage

type ScenarioPage struct {
	Scenarios []SavedScenario `json:"scenarios"`
	Total     int             `json:"total"`
}

ScenarioPage is a paginated slice of saved scenarios with the total row count.

type ScenarioResult

type ScenarioResult struct {
	ID                uuid.UUID       `json:"id"`
	RunID             uuid.UUID       `json:"runId"`
	Name              string          `json:"name"`
	Status            string          `json:"status"`
	Phase             *string         `json:"phase,omitempty"`
	IsSuccess         *bool           `json:"isSuccess"`
	ErrorMessage      string          `json:"errorMessage,omitempty"`
	DurationSecs      float64         `json:"durationSecs"`
	MatchingDurSecs   float64         `json:"matchingDurSecs"`
	TimeExecuted      *time.Time      `json:"timeExecuted,omitempty"`
	ExecutorName      string          `json:"executorName"`
	ExecutorType      string          `json:"executorType"`
	ExecutionID       string          `json:"executionId"`
	SimulationID      string          `json:"simulationId,omitempty"`
	Assertions        json.RawMessage `json:"assertions,omitempty"`
	Indicators        json.RawMessage `json:"indicators,omitempty"`
	Metadata          json.RawMessage `json:"metadata,omitempty"`
	CollectedLogPath  *string         `json:"collectedLogPath,omitempty"`
	CollectedDocCount int             `json:"collectedDocCount,omitempty"`
	DiscoveredAlerts  json.RawMessage `json:"discoveredAlerts,omitempty"`
	CreatedAt         time.Time       `json:"createdAt"`
}

ScenarioResult represents the result of a single scenario execution.

type ScenarioStore

type ScenarioStore interface {
	Save(ctx context.Context, name, scenarioType, yaml, createdBy string) (*SavedScenario, error)
	Get(ctx context.Context, id uuid.UUID) (*SavedScenario, error)
	// List returns a filtered, paginated slice of scenarios for the UI.
	List(ctx context.Context, filters ListScenariosFilters, limit, offset int) (ScenarioPage, error)
	// ListAll returns every scenario in updated_at DESC order. For internal
	// callers (e.g. coverage maps) that need the full set in one shot.
	ListAll(ctx context.Context) ([]SavedScenario, error)
	Update(ctx context.Context, id uuid.UUID, name, scenarioType, yaml, updatedBy string) error
	Delete(ctx context.Context, id uuid.UUID) error
}

ScenarioStore manages saved scenario YAML persistence.

func NewScenarioStore

func NewScenarioStore(pool *pgxpool.Pool) ScenarioStore

NewScenarioStore creates a new ScenarioStore backed by PostgreSQL.

type Schedule

type Schedule struct {
	ID             uuid.UUID  `json:"id"`
	ScenarioID     uuid.UUID  `json:"scenarioId"`
	CronExpression string     `json:"cronExpression"`
	Enabled        bool       `json:"enabled"`
	Parallelism    int        `json:"parallelism"`
	LastRunAt      *time.Time `json:"lastRunAt,omitempty"`
	CreatedBy      string     `json:"createdBy"`
	UpdatedBy      string     `json:"updatedBy"`
	CreatedAt      time.Time  `json:"createdAt"`
	UpdatedAt      time.Time  `json:"updatedAt"`
}

Schedule represents a cron schedule for a saved scenario.

type ScheduleStore

type ScheduleStore interface {
	Create(ctx context.Context, scenarioID uuid.UUID, cronExpr string, enabled bool, parallelism int, createdBy string) (*Schedule, error)
	Get(ctx context.Context, id uuid.UUID) (*Schedule, error)
	GetByScenarioID(ctx context.Context, scenarioID uuid.UUID) (*Schedule, error)
	List(ctx context.Context) ([]Schedule, error)
	ListEnabled(ctx context.Context) ([]Schedule, error)
	Update(ctx context.Context, id uuid.UUID, cronExpr string, enabled bool, parallelism int, updatedBy string) error
	Delete(ctx context.Context, id uuid.UUID) error
	UpdateLastRun(ctx context.Context, id uuid.UUID, lastRunAt time.Time) error
}

ScheduleStore manages schedule persistence.

func NewScheduleStore

func NewScheduleStore(pool *pgxpool.Pool) ScheduleStore

NewScheduleStore creates a new ScheduleStore backed by PostgreSQL.

type SecretGroup

type SecretGroup struct {
	ID          uuid.UUID       `json:"id"`
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Entries     json.RawMessage `json:"entries"`
	CreatedBy   string          `json:"createdBy"`
	UpdatedBy   string          `json:"updatedBy"`
	CreatedAt   time.Time       `json:"createdAt"`
	UpdatedAt   time.Time       `json:"updatedAt"`
}

SecretGroup represents a named group of encrypted key-value secrets.

type SecretStore

type SecretStore interface {
	Save(ctx context.Context, name, description string, entries json.RawMessage, createdBy string) (*SecretGroup, error)
	Get(ctx context.Context, id uuid.UUID) (*SecretGroup, error)
	List(ctx context.Context) ([]SecretGroup, error)
	Update(ctx context.Context, id uuid.UUID, name, description string, entries json.RawMessage, updatedBy string) error
	Delete(ctx context.Context, id uuid.UUID) error
}

SecretStore manages secret group persistence.

func NewSecretStore

func NewSecretStore(pool *pgxpool.Pool) SecretStore

NewSecretStore creates a new SecretStore backed by PostgreSQL.

type SessionStore

type SessionStore interface {
	Create(ctx context.Context, email, name, picture string, ttl time.Duration) (string, error)
	Get(ctx context.Context, sessionID string) (*AuthSession, error)
	Delete(ctx context.Context, sessionID string) error
	DeleteExpired(ctx context.Context) error
}

SessionStore manages authentication session persistence.

func NewSessionStore

func NewSessionStore(pool *pgxpool.Pool) SessionStore

NewSessionStore creates a new SessionStore backed by PostgreSQL.

Jump to

Keyboard shortcuts

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