internal/jobs keeps named locks as leases in the database (schema 31: locks, instances), taken with one conditional UPDATE on SQLite or Postgres, renewed while the work runs and lapsing if its copy stops. Each background loop's turn, sending an email, audits, discovery runs and imports run under a lock; OAuth sign-ins under way are kept in the database. Copies check in, and work marked running is recovered at start only when no other copy is alive. Settings -> About lists the copies and work under way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
116 lines
4.1 KiB
Go
116 lines
4.1 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
// Migration is a change to the schema from schema 30 on, for both
|
|
// databases. It's written once, in SQLite's SQL; Postgres gets the same
|
|
// statements with SQLite's types and defaults translated (see PostgresSQL).
|
|
// A migration that changes data with SQL only SQLite has gives Postgres
|
|
// its own.
|
|
//
|
|
// Never edit or reorder one that has shipped: add a new one instead.
|
|
type Migration struct {
|
|
Note string // what it does, for the record (Postgres' schema_migrations)
|
|
SQLite string
|
|
Postgres string // empty: PostgresSQL(SQLite)
|
|
}
|
|
|
|
// both are the migrations after schema 29, on both databases: schema 30
|
|
// is both[0]. (migrations, before them, are SQLite's own; Postgres starts
|
|
// from postgres.sql, which is schema 29 as a whole.)
|
|
var both = []Migration{
|
|
// 30
|
|
{
|
|
Note: "secrets kept in the database, encrypted (server and multi-tenant editions)",
|
|
SQLite: `
|
|
CREATE TABLE secrets (
|
|
name TEXT PRIMARY KEY,
|
|
value TEXT NOT NULL, -- v1:<base64 of the nonce and the sealed value>, AES-256-GCM
|
|
key_id TEXT NOT NULL, -- which key sealed it: a fingerprint, never the key
|
|
updated_at TEXT NOT NULL
|
|
);
|
|
`,
|
|
},
|
|
// 31
|
|
{
|
|
Note: "copies of the app, and the locks that let only one of them do a job",
|
|
SQLite: `
|
|
CREATE TABLE instances (
|
|
id TEXT PRIMARY KEY, -- a copy of the app, while it runs
|
|
host TEXT NOT NULL DEFAULT '',
|
|
version TEXT NOT NULL DEFAULT '',
|
|
started_at TEXT NOT NULL,
|
|
seen_at TEXT NOT NULL -- its last check-in (every 30 seconds)
|
|
);
|
|
CREATE TABLE locks (
|
|
name TEXT PRIMARY KEY, -- the work, e.g. job:seo, outreach:send, audit:<site>
|
|
holder TEXT NOT NULL DEFAULT '', -- <instance>:<random>, or '' when free
|
|
taken_at TEXT NOT NULL DEFAULT '',
|
|
expires_at TEXT NOT NULL DEFAULT '' -- renewed while the work runs; free after it
|
|
);
|
|
`,
|
|
},
|
|
}
|
|
|
|
// Schema is the schema version this build migrates databases to.
|
|
func Schema() int { return len(migrations) + len(both) }
|
|
|
|
// sqliteStep is the SQL that takes SQLite from schema i to i+1.
|
|
func sqliteStep(i int) string {
|
|
if i < len(migrations) {
|
|
return migrations[i]
|
|
}
|
|
return both[i-len(migrations)].SQLite
|
|
}
|
|
|
|
// postgresStep is the migration that takes Postgres from schema i to i+1
|
|
// (i is pgBaseline or later).
|
|
func postgresStep(i int) (Migration, string) {
|
|
m := both[i-pgBaseline]
|
|
if m.Postgres != "" {
|
|
return m, m.Postgres
|
|
}
|
|
return m, PostgresSQL(m.SQLite)
|
|
}
|
|
|
|
var (
|
|
ddlIntegerKey = regexp.MustCompile(`(?i)\bINTEGER\s+PRIMARY\s+KEY\b`)
|
|
ddlInteger = regexp.MustCompile(`(?i)\bINTEGER\b`)
|
|
ddlReal = regexp.MustCompile(`(?i)\bREAL\b`)
|
|
ddlBlob = regexp.MustCompile(`(?i)\bBLOB\b`)
|
|
ddlNow = regexp.MustCompile(`(?i)strftime\('%Y-%m-%dT%H:%M:%SZ',\s*'now'\)`)
|
|
// A column whose COLLATE comes after its constraints: Postgres wants it
|
|
// right after the type.
|
|
ddlCollateLate = regexp.MustCompile(`(?i)\bTEXT((?:\s+(?:NOT\s+NULL|UNIQUE|PRIMARY\s+KEY|DEFAULT\s+(?:'(?:[^']|'')*'|\([^)]*\)|[^\s,]+)))+)\s+COLLATE\s+NOCASE\b`)
|
|
ddlCollate = regexp.MustCompile(`(?i)\bCOLLATE\s+NOCASE\b`)
|
|
)
|
|
|
|
// PostgresSQL translates SQLite's DDL (CREATE TABLE, CREATE INDEX, ALTER
|
|
// TABLE … ADD COLUMN) to Postgres': 64-bit integers, identity keys,
|
|
// doubles, the nocase collation in its place, and timestamps from now().
|
|
func PostgresSQL(sqlite string) string {
|
|
s := ddlIntegerKey.ReplaceAllString(sqlite, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY")
|
|
s = ddlInteger.ReplaceAllString(s, "BIGINT")
|
|
s = ddlReal.ReplaceAllString(s, "DOUBLE PRECISION")
|
|
s = ddlBlob.ReplaceAllString(s, "BYTEA")
|
|
s = ddlNow.ReplaceAllString(s, `to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`)
|
|
s = ddlCollateLate.ReplaceAllString(s, "TEXT COLLATE nocase$1")
|
|
s = ddlCollate.ReplaceAllString(s, "COLLATE nocase")
|
|
return s
|
|
}
|
|
|
|
// checkMigrations catches a mistake in the list before it reaches a
|
|
// database: an empty step.
|
|
func checkMigrations() error {
|
|
for i, m := range both {
|
|
if strings.TrimSpace(m.SQLite) == "" || strings.TrimSpace(m.Note) == "" {
|
|
return fmt.Errorf("migration %d needs its SQLite SQL and a note", len(migrations)+i+1)
|
|
}
|
|
}
|
|
return nil
|
|
}
|