Add resumable checked migrations and explicit schema administration commands. Port ML budgets, namespaces, identity and group persistence with three-backend contracts. Keep MySQL unavailable as the full application backend.
304 lines
11 KiB
Go
304 lines
11 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"database/sql/driver"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// MySQLOperation is owned SQL, never user input. Check must return exactly one
|
|
// boolean describing the operation's postcondition. ReplaySafe permits explicit
|
|
// resume when Check is false; never mark non-idempotent data updates replay-safe.
|
|
type MySQLOperation struct {
|
|
SQL, Check string
|
|
ReplaySafe bool
|
|
}
|
|
type MySQLMigration struct {
|
|
Version int
|
|
Name string
|
|
Operations []MySQLOperation
|
|
Assertions []string
|
|
}
|
|
type MySQLMigrationStatus struct {
|
|
Applied int `json:"applied"`
|
|
Pending int `json:"pending"`
|
|
Dirty bool `json:"dirty"`
|
|
NextOperation int `json:"next_operation"`
|
|
DirtyComponent string `json:"dirty_component,omitempty"`
|
|
}
|
|
|
|
var ErrMySQLMigrationDirty = errors.New("MySQL migration interrupted; inspect and explicitly resume")
|
|
var ErrMySQLMigrationMismatch = errors.New("MySQL migration history or schema mismatch")
|
|
|
|
func mysqlMigrationHash(m MySQLMigration) string {
|
|
b, _ := json.Marshal(m)
|
|
h := sha256.Sum256(b)
|
|
return hex.EncodeToString(h[:])
|
|
}
|
|
func validateMySQLPlan(component string, steps []MySQLMigration) error {
|
|
if !regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`).MatchString(component) {
|
|
return errors.New("invalid MySQL migration component")
|
|
}
|
|
for i, s := range steps {
|
|
if s.Version != i+1 || s.Name == "" || len(s.Name) > 128 || len(s.Operations) == 0 || len(s.Assertions) == 0 {
|
|
return errors.New("invalid MySQL migration plan")
|
|
}
|
|
for _, op := range s.Operations {
|
|
if strings.TrimSpace(op.SQL) == "" || strings.TrimSpace(op.Check) == "" {
|
|
return errors.New("missing MySQL operation postcondition")
|
|
}
|
|
}
|
|
for _, assertion := range s.Assertions {
|
|
if strings.TrimSpace(assertion) == "" {
|
|
return errors.New("missing MySQL schema assertion")
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Every operation, including GET_LOCK/RELEASE_LOCK, uses this one connection.
|
|
// MySQL DDL commits implicitly: a transaction cannot replace this lock/journal.
|
|
func mysqlMigrationConnection(ctx context.Context, database *sql.DB) (*sql.Conn, func(), error) {
|
|
c, e := database.Conn(ctx)
|
|
if e != nil {
|
|
return nil, nil, errors.New("MySQL migration connection failed")
|
|
}
|
|
var name string
|
|
if e = c.QueryRowContext(ctx, `SELECT DATABASE()`).Scan(&name); e != nil || name == "" {
|
|
c.Close()
|
|
return nil, nil, errors.New("MySQL migration database required")
|
|
}
|
|
h := sha256.Sum256([]byte(name))
|
|
key := "pages:migration:" + hex.EncodeToString(h[:20])
|
|
var locked sql.NullInt64
|
|
if e = c.QueryRowContext(ctx, `SELECT GET_LOCK(?,10)`, key).Scan(&locked); e != nil || !locked.Valid || locked.Int64 != 1 {
|
|
// An interrupted lock request may have acquired the session lock.
|
|
_ = c.Raw(func(any) error { return driver.ErrBadConn })
|
|
c.Close()
|
|
return nil, nil, errors.New("MySQL migration lock unavailable")
|
|
}
|
|
release := func() {
|
|
releaseCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancel()
|
|
var released sql.NullInt64
|
|
if e := c.QueryRowContext(releaseCtx, `SELECT RELEASE_LOCK(?)`, key).Scan(&released); e != nil || !released.Valid || released.Int64 != 1 {
|
|
_ = c.Raw(func(any) error { return driver.ErrBadConn })
|
|
}
|
|
c.Close()
|
|
}
|
|
return c, release, nil
|
|
}
|
|
|
|
func mysqlCheck(ctx context.Context, c *sql.Conn, q string) (bool, error) {
|
|
rows, e := c.QueryContext(ctx, q)
|
|
if e != nil {
|
|
return false, errors.New("MySQL schema check failed")
|
|
}
|
|
defer rows.Close()
|
|
var yes bool
|
|
if !rows.Next() {
|
|
return false, errors.New("MySQL schema check returned no result")
|
|
}
|
|
if rows.Scan(&yes) != nil || rows.Next() || rows.Err() != nil {
|
|
return false, errors.New("invalid MySQL schema check result")
|
|
}
|
|
return yes, nil
|
|
}
|
|
|
|
func inspectMySQLLocked(ctx context.Context, c *sql.Conn, component string, steps []MySQLMigration) (MySQLMigrationStatus, error) {
|
|
status := MySQLMigrationStatus{Pending: len(steps)}
|
|
var exists int
|
|
if e := c.QueryRowContext(ctx, `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations'`).Scan(&exists); e != nil {
|
|
return status, errors.New("MySQL migration inspection failed")
|
|
}
|
|
if exists == 0 {
|
|
return status, nil
|
|
}
|
|
// The journal itself must remain durable and uniquely keyed. Do not repair
|
|
// a damaged journal automatically, or trust history read from a view.
|
|
valid, e := mysqlCheck(ctx, c, `SELECT
|
|
(SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND engine='InnoDB' AND table_type='BASE TABLE')=1
|
|
AND COALESCE((SELECT GROUP_CONCAT(column_name ORDER BY seq_in_index SEPARATOR ',') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND index_name='PRIMARY'),'')='component,version'
|
|
AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND is_nullable='NO' AND column_name IN ('component','version','name','checksum','state','next_operation','updated_ms'))=7`)
|
|
if e != nil {
|
|
return status, e
|
|
}
|
|
if !valid {
|
|
return status, ErrMySQLMigrationMismatch
|
|
}
|
|
rows, e := c.QueryContext(ctx, `SELECT version,name,checksum,state,next_operation FROM schema_mysql_migrations WHERE component=? ORDER BY version`, component)
|
|
if e != nil {
|
|
return status, errors.New("MySQL migration history unavailable")
|
|
}
|
|
seen := 0
|
|
for rows.Next() {
|
|
var version, next int
|
|
var name, hash, state string
|
|
if rows.Scan(&version, &name, &hash, &state, &next) != nil {
|
|
rows.Close()
|
|
return status, ErrMySQLMigrationMismatch
|
|
}
|
|
if version != seen+1 || version > len(steps) || status.Dirty {
|
|
rows.Close()
|
|
return status, ErrMySQLMigrationMismatch
|
|
}
|
|
s := steps[version-1]
|
|
if name != s.Name || hash != mysqlMigrationHash(s) || next < 0 || next > len(s.Operations) {
|
|
rows.Close()
|
|
return status, ErrMySQLMigrationMismatch
|
|
}
|
|
switch state {
|
|
case "applied":
|
|
if next != len(s.Operations) {
|
|
rows.Close()
|
|
return status, ErrMySQLMigrationMismatch
|
|
}
|
|
status.Applied++
|
|
case "running":
|
|
status.Dirty = true
|
|
status.DirtyComponent = component
|
|
status.NextOperation = next
|
|
default:
|
|
rows.Close()
|
|
return status, ErrMySQLMigrationMismatch
|
|
}
|
|
seen++
|
|
}
|
|
e = rows.Err()
|
|
rows.Close()
|
|
if e != nil {
|
|
return status, errors.New("MySQL migration history read failed")
|
|
}
|
|
status.Pending = len(steps) - status.Applied
|
|
// Later migrations may intentionally replace an older schema. Validate only
|
|
// the latest clean contract, not intermediate versions of a dirty migration.
|
|
if !status.Dirty && status.Applied > 0 {
|
|
for _, q := range steps[status.Applied-1].Assertions {
|
|
ok, e := mysqlCheck(ctx, c, q)
|
|
if e != nil {
|
|
return status, e
|
|
}
|
|
if !ok {
|
|
return status, ErrMySQLMigrationMismatch
|
|
}
|
|
}
|
|
}
|
|
return status, nil
|
|
}
|
|
|
|
// Inspect is read-only: it never creates the ledger or adopts an existing table.
|
|
func InspectMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) (MySQLMigrationStatus, error) {
|
|
if e := validateMySQLPlan(component, steps); e != nil {
|
|
return MySQLMigrationStatus{}, e
|
|
}
|
|
c, release, e := mysqlMigrationConnection(ctx, database)
|
|
if e != nil {
|
|
return MySQLMigrationStatus{}, e
|
|
}
|
|
defer release()
|
|
return inspectMySQLLocked(ctx, c, component, steps)
|
|
}
|
|
|
|
func ApplyMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) error {
|
|
return applyMySQLMigrations(ctx, database, component, steps, false)
|
|
}
|
|
|
|
// Resume is explicitly separate from normal startup. It does not blindly repeat
|
|
// a statement: the postcondition must prove success, or ReplaySafe must be set.
|
|
func ResumeMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) error {
|
|
return applyMySQLMigrations(ctx, database, component, steps, true)
|
|
}
|
|
func applyMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration, resume bool) error {
|
|
if e := validateMySQLPlan(component, steps); e != nil {
|
|
return e
|
|
}
|
|
c, release, e := mysqlMigrationConnection(ctx, database)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
defer release()
|
|
status, e := inspectMySQLLocked(ctx, c, component, steps)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if status.Dirty && !resume {
|
|
return ErrMySQLMigrationDirty
|
|
}
|
|
_, e = c.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_mysql_migrations(component VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,version BIGINT NOT NULL,name VARCHAR(128) NOT NULL,checksum CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,state VARCHAR(16) NOT NULL,next_operation BIGINT NOT NULL,updated_ms BIGINT NOT NULL,PRIMARY KEY(component,version)) ENGINE=InnoDB`)
|
|
if e != nil {
|
|
return errors.New("MySQL migration ledger creation failed")
|
|
}
|
|
for _, s := range steps[status.Applied:] {
|
|
resuming := status.Dirty
|
|
cursor := 0
|
|
if resuming {
|
|
cursor = status.NextOperation
|
|
} else {
|
|
// Do not implicitly adopt an already-existing schema with no history.
|
|
for _, op := range s.Operations {
|
|
ok, e := mysqlCheck(ctx, c, op.Check)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if ok {
|
|
return ErrMySQLMigrationMismatch
|
|
}
|
|
}
|
|
_, e = c.ExecContext(ctx, `INSERT INTO schema_mysql_migrations(component,version,name,checksum,state,next_operation,updated_ms) VALUES(?,?,?,?,'running',0,?)`, component, s.Version, s.Name, mysqlMigrationHash(s), time.Now().UnixMilli())
|
|
if e != nil {
|
|
return errors.New("MySQL migration journal failed")
|
|
}
|
|
}
|
|
for i := cursor; i < len(s.Operations); i++ {
|
|
op := s.Operations[i]
|
|
ok, e := mysqlCheck(ctx, c, op.Check)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if !ok {
|
|
if resuming && i == cursor && !op.ReplaySafe {
|
|
return ErrMySQLMigrationDirty
|
|
}
|
|
if _, e = c.ExecContext(ctx, op.SQL); e != nil {
|
|
return fmt.Errorf("MySQL migration operation %d failed; journal retained", i+1)
|
|
}
|
|
ok, e = mysqlCheck(ctx, c, op.Check)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if !ok {
|
|
return ErrMySQLMigrationMismatch
|
|
}
|
|
}
|
|
_, e = c.ExecContext(ctx, `UPDATE schema_mysql_migrations SET next_operation=?,updated_ms=? WHERE component=? AND version=?`, i+1, time.Now().UnixMilli(), component, s.Version)
|
|
if e != nil {
|
|
return errors.New("MySQL migration progress failed")
|
|
}
|
|
}
|
|
for _, q := range s.Assertions {
|
|
ok, e := mysqlCheck(ctx, c, q)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if !ok {
|
|
return ErrMySQLMigrationMismatch
|
|
}
|
|
}
|
|
_, e = c.ExecContext(ctx, `UPDATE schema_mysql_migrations SET state='applied',updated_ms=? WHERE component=? AND version=?`, time.Now().UnixMilli(), component, s.Version)
|
|
if e != nil {
|
|
return errors.New("MySQL migration completion failed")
|
|
}
|
|
status.Dirty = false
|
|
}
|
|
return nil
|
|
}
|