feat(storage): add native MySQL namespace and identity pilots
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.
This commit is contained in:
1 parent
0c7897d695
commit
6a67fd9afe
40 files changed
+3087
-94
No files matched your search
@@ -0,0 +1,59 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
// MySQL is currently a component-pilot backend, not a Pages serving backend.
|
||||
// Credentials are instance configuration and must never be logged.
|
||||
type MySQLOptions struct {
|
||||
DSN string
|
||||
AllowInsecure bool
|
||||
}
|
||||
|
||||
func OpenMySQL(ctx context.Context, options MySQLOptions) (*sql.DB, error) {
|
||||
c, e := mysql.ParseDSN(options.DSN)
|
||||
if e != nil || options.DSN == "" {
|
||||
return nil, errors.New("invalid MySQL configuration")
|
||||
}
|
||||
if c.DBName == "" || c.Net != "tcp" || c.MultiStatements || c.AllowAllFiles || c.AllowCleartextPasswords || c.AllowFallbackToPlaintext || len(c.Params) != 0 {
|
||||
return nil, errors.New("unsupported MySQL configuration")
|
||||
}
|
||||
if !options.AllowInsecure && c.TLSConfig != "true" {
|
||||
return nil, errors.New("MySQL requires verified TLS (tls=true)")
|
||||
}
|
||||
c.Timeout = 10 * time.Second
|
||||
c.ReadTimeout = 30 * time.Second
|
||||
c.WriteTimeout = 30 * time.Second
|
||||
c.Collation = "utf8mb4_bin"
|
||||
// Set on EVERY new pooled connection. Relying on a server's permissive
|
||||
// sql_mode can silently truncate identifiers or coerce invalid values.
|
||||
// User-supplied session variables remain rejected above.
|
||||
c.Params = map[string]string{"sql_mode": "'STRICT_ALL_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"}
|
||||
c.Logger = log.New(io.Discard, "", 0)
|
||||
connector, e := mysql.NewConnector(c)
|
||||
if e != nil {
|
||||
return nil, errors.New("invalid MySQL connector configuration")
|
||||
}
|
||||
database := sql.OpenDB(connector)
|
||||
database.SetMaxOpenConns(8)
|
||||
database.SetMaxIdleConns(2)
|
||||
database.SetConnMaxLifetime(10 * time.Minute)
|
||||
ping, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
if e = database.PingContext(ping); e != nil {
|
||||
database.Close()
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, errors.New("MySQL connection failed")
|
||||
}
|
||||
return database, nil
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package db
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestMySQLMigrationPlanValidation(t *testing.T) {
|
||||
valid := func() MySQLMigration {
|
||||
return MySQLMigration{Version: 1, Name: "initial", Operations: []MySQLOperation{{SQL: "CREATE TABLE example(id BIGINT)", Check: "SELECT 0", ReplaySafe: true}}, Assertions: []string{"SELECT 1"}}
|
||||
}
|
||||
if e := validateMySQLPlan("machine-learning", []MySQLMigration{valid()}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, component := range []string{"", "../schema", "has space", "MixedCase"} {
|
||||
if e := validateMySQLPlan(component, []MySQLMigration{valid()}); e == nil {
|
||||
t.Fatal("invalid component accepted", component)
|
||||
}
|
||||
}
|
||||
for _, mutate := range []func(*MySQLMigration){
|
||||
func(m *MySQLMigration) { m.Version = 2 },
|
||||
func(m *MySQLMigration) { m.Name = "" },
|
||||
func(m *MySQLMigration) { m.Operations = nil },
|
||||
func(m *MySQLMigration) { m.Operations[0].SQL = " " },
|
||||
func(m *MySQLMigration) { m.Operations[0].Check = " " },
|
||||
func(m *MySQLMigration) { m.Assertions = nil },
|
||||
func(m *MySQLMigration) { m.Assertions[0] = " " },
|
||||
} {
|
||||
m := valid()
|
||||
mutate(&m)
|
||||
if e := validateMySQLPlan("test", []MySQLMigration{m}); e == nil {
|
||||
t.Fatal("invalid plan accepted", m)
|
||||
}
|
||||
}
|
||||
before := valid()
|
||||
after := valid()
|
||||
after.Operations[0].ReplaySafe = false
|
||||
if mysqlMigrationHash(before) == mysqlMigrationHash(after) {
|
||||
t.Fatal("replay policy not covered by checksum")
|
||||
}
|
||||
if mysqlMigrationHash(before) != mysqlMigrationHash(valid()) {
|
||||
t.Fatal("unstable checksum")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMySQLRejectsUnsafeConfiguration(t *testing.T) {
|
||||
for _, dsn := range []string{"", "private-secret@bad", "u:private-secret@tcp(localhost:3306)/pages", "u:p@tcp(localhost:3306)/pages?tls=skip-verify", "u:p@tcp(localhost:3306)/pages?tls=preferred", "u:p@tcp(localhost:3306)/pages?tls=true&multiStatements=true", "u:p@tcp(localhost:3306)/pages?tls=true&allowAllFiles=true", "u:p@tcp(localhost:3306)/pages?tls=true&sql_mode=bad"} {
|
||||
connection, err := OpenMySQL(context.Background(), MySQLOptions{DSN: dsn})
|
||||
if connection != nil {
|
||||
connection.Close()
|
||||
t.Fatal("unexpected connection")
|
||||
}
|
||||
if err == nil || strings.Contains(err.Error(), "private-secret") {
|
||||
t.Fatalf("configuration not safely rejected: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user