Files
cloud-ip-validator/internal/db/db.go
T

177 lines
4.9 KiB
Go
Raw Normal View History

2026-08-21 07:34:45 +03:00
// Package db owns the SQLite connection, schema migrations, and all queries
// used by the Control API. It is the only package in the system that talks
// to the database directly — agents and probers never connect to it.
package db
import (
"context"
"database/sql"
_ "embed"
"fmt"
"strings"
2026-08-21 07:34:45 +03:00
"time"
_ "modernc.org/sqlite"
)
//go:embed migrations/0001_init.sql
var initSchema string
2026-08-23 20:39:22 +03:00
//go:embed migrations/0002_dynamic_config.sql
var dynamicConfigSchema string
2026-08-24 10:29:08 +03:00
//go:embed migrations/0003_fip_settle_delay.sql
var fipSettleDelaySchema string
//go:embed migrations/0004_inbound_checks_admin.sql
var inboundChecksAdminSchema string
//go:embed migrations/0005_unbounded_sites.sql
var unboundedSitesSchema string
//go:embed migrations/0006_prober_heartbeat.sql
var proberHeartbeatSchema string
//go:embed migrations/0007_ip_registry.sql
var ipRegistrySchema string
//go:embed migrations/0008_auto_cycle.sql
var autoCycleSchema string
//go:embed migrations/0009_scale_indexes.sql
var scaleIndexesSchema string
//go:embed migrations/0010_verdict_integrity.sql
var verdictIntegritySchema string
//go:embed migrations/0011_check_runs.sql
var checkRunsSchema string
//go:embed migrations/0012_self_check_failures.sql
var selfCheckFailuresSchema string
//go:embed migrations/0013_drop_redundant_checks_index.sql
var dropChecksIndexSchema string
//go:embed migrations/0014_diagnostic_holds.sql
var diagnosticHoldsSchema string
//go:embed migrations/0015_inbound_tls_checks.sql
var inboundTLSChecksSchema string
2026-08-23 20:39:22 +03:00
// migrations is the ordered list of schema versions. Each entry's SQL is
// applied, in order, for any version greater than the database's current
// PRAGMA user_version — so a fresh database walks the whole list and an
// existing one only picks up what's new.
var migrations = []struct {
version int
sql string
}{
{1, initSchema},
{2, dynamicConfigSchema},
2026-08-24 10:29:08 +03:00
{3, fipSettleDelaySchema},
{4, inboundChecksAdminSchema},
{5, unboundedSitesSchema},
{6, proberHeartbeatSchema},
{7, ipRegistrySchema},
{8, autoCycleSchema},
{9, scaleIndexesSchema},
{10, verdictIntegritySchema},
{11, checkRunsSchema},
{12, selfCheckFailuresSchema},
{13, dropChecksIndexSchema},
{14, diagnosticHoldsSchema},
{15, inboundTLSChecksSchema},
}
// connPragmas are applied to every new connection. A larger WAL checkpoint
// interval and cache cut random writes on the HDD-backed volume.
var connPragmas = []string{
"busy_timeout(5000)",
"journal_mode(WAL)",
"synchronous(NORMAL)",
"foreign_keys(ON)",
"wal_autocheckpoint(10000)",
"journal_size_limit(67108864)",
"cache_size(-65536)",
}
func dsn(path string) string {
q := make([]string, len(connPragmas))
for i, p := range connPragmas {
q[i] = "_pragma=" + p
}
return path + "?" + strings.Join(q, "&")
2026-08-23 20:39:22 +03:00
}
2026-08-21 07:34:45 +03:00
type DB struct {
*sql.DB
}
// Open opens (creating if necessary) the SQLite database at path, applies
// pragmas suited to a single-writer WAL workload, and runs any pending
// schema migrations.
func Open(ctx context.Context, path string) (*DB, error) {
sqlDB, err := sql.Open("sqlite", dsn(path))
2026-08-21 07:34:45 +03:00
if err != nil {
return nil, fmt.Errorf("open sqlite: %w", err)
}
// Control API is the sole writer; one connection avoids SQLITE_BUSY
// entirely for writes while still allowing concurrent reads via WAL.
sqlDB.SetMaxOpenConns(1)
// Pragmas are in the DSN, so they apply to every new connection; this
// ping opens the first one and reports a bad pragma early.
if err := sqlDB.PingContext(ctx); err != nil {
sqlDB.Close()
return nil, fmt.Errorf("open sqlite: %w", err)
2026-08-21 07:34:45 +03:00
}
d := &DB{DB: sqlDB}
if err := d.migrate(ctx); err != nil {
sqlDB.Close()
return nil, fmt.Errorf("migrate: %w", err)
}
if err := d.adoptOrphanQueueRows(ctx); err != nil {
sqlDB.Close()
return nil, fmt.Errorf("adopt queue rows into a run: %w", err)
}
2026-08-21 07:34:45 +03:00
return d, nil
}
2026-08-23 20:39:22 +03:00
// migrate applies every pending migration in order, tracked via
// PRAGMA user_version so repeated startups only apply what's new (and a
// fresh database walks the whole list once).
2026-08-21 07:34:45 +03:00
func (d *DB) migrate(ctx context.Context) error {
var version int
if err := d.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil {
return fmt.Errorf("read user_version: %w", err)
}
2026-08-23 20:39:22 +03:00
for _, m := range migrations {
if m.version <= version {
continue
}
tx, err := d.BeginTx(ctx, nil)
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, m.sql); err != nil {
tx.Rollback()
return fmt.Errorf("apply migration %d: %w", m.version, err)
}
if _, err := tx.ExecContext(ctx, fmt.Sprintf("PRAGMA user_version=%d", m.version)); err != nil {
tx.Rollback()
return fmt.Errorf("set user_version=%d: %w", m.version, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit migration %d: %w", m.version, err)
}
2026-08-21 07:34:45 +03:00
}
2026-08-23 20:39:22 +03:00
return nil
2026-08-21 07:34:45 +03:00
}
// Now returns the current time truncated to millisecond precision, the
// granularity used consistently for all timestamp columns.
func Now() time.Time {
return time.Now().UTC().Truncate(time.Millisecond)
}