Files
pages/internal/store/namespace_mysql_test.go
T
Anya Tokugawa 6a67fd9afe 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.
2026-11-30 23:03:24 +09:00

365 lines
13 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
"pageswiki/internal/db"
)
// Bootstrap is fixture-only. The public facade intentionally cannot create a
// Domain until built-in groups and inherited permissions are ported together.
func testNamespaceCoreStore(t *testing.T, backend storeSQLBackend) *Store {
t.Helper()
if backend != storeMySQL {
return testNamespaceStore(t, backend)
}
s, _ := mlTestStore(t, backend)
r := &MySQLNamespaceRepository{store: s}
ctx := context.Background()
if e := r.PrepareSchema(ctx); e != nil {
t.Fatal(e)
}
if e := r.PrepareSchema(ctx); e != nil {
t.Fatal("repeat prepare", e)
}
if status, e := r.InspectSchema(ctx); e != nil || status.Pending != 0 || status.Dirty {
t.Fatal("inspect", status, e)
}
if e := r.CreateCampus(ctx, "default", "Default Campus", "en", "standalone", "localhost", true); e != nil {
t.Fatal(e)
}
campus, e := s.GetDefaultCampus()
if e != nil {
t.Fatal(e)
}
seedNamespaceDomain(t, s, campus.UUID, "default", "")
return s
}
func TestNamespaceCoreThreeBackendContract(t *testing.T) {
for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
t.Run(fmt.Sprint(backend), func(t *testing.T) {
s := testNamespaceCoreStore(t, backend)
ctx := context.Background()
create, update := s.CreateCampusContext, s.UpdateCampusContext
read, write := s.GetConfigInDomainContext, s.SetConfigInDomainContext
resolve, effective := s.GetDomainByHostContext, s.GetDomainEffectiveHostContext
if backend == storeMySQL {
r := &MySQLNamespaceRepository{store: s}
create, update, read, write, resolve, effective = r.CreateCampus, r.UpdateCampus, r.Config, r.SetConfig, r.ResolveHost, r.EffectiveHost
}
campus, e := s.GetDefaultCampus()
if e != nil {
t.Fatal(e)
}
domain, e := s.GetDefaultDomain()
if e != nil {
t.Fatal(e)
}
if e := update(ctx, campus.ID, "default", "キャンパス 🏫", "ja", "standalone", "pages.example.test", true); e != nil {
t.Fatal(e)
}
if e := create(ctx, "OTHER", "別キャンパス", "en", "standalone", "other.example.test", true); e != nil {
t.Fatal(e)
}
campuses, e := s.ListCampusesContext(ctx)
if e != nil || len(campuses) != 2 {
t.Fatal(campuses, e)
}
var other Campus
for _, c := range campuses {
if c.UUID != campus.UUID {
other = c
}
}
short := seedNamespaceDomain(t, s, campus.UUID, "short", "www")
absolute := seedNamespaceDomain(t, s, other.UUID, "absolute", "www.example.test")
for host, want := range map[string]string{"PAGES.EXAMPLE.TEST:443": domain.UUID, "www.pages.example.test": short.UUID, "www.example.test": absolute.UUID} {
got, e := resolve(ctx, host)
if e != nil || got.UUID != want {
t.Fatal("host resolution", host, e)
}
}
if got, e := effective(ctx, short.UUID); e != nil || got != "www.pages.example.test" {
t.Fatal(got, e)
}
if _, e := resolve(ctx, "absent.example.test"); !errors.Is(e, sql.ErrNoRows) {
t.Fatal("fallback", e)
}
if e := update(ctx, campus.ID, "default", "must rollback", "en", "standalone", "example.test", true); e == nil {
t.Fatal("host collision accepted")
}
current, e := s.GetCampusByUUIDContext(ctx, campus.UUID)
if e != nil || current.Title != "キャンパス 🏫" || current.FQDN != "pages.example.test" {
t.Fatal("failed update persisted", current, e)
}
if e := update(ctx, campus.ID, "default", "disabled", "en", "standalone", "pages.example.test", false); e == nil {
t.Fatal("referenced Campus disabled")
}
if e := create(ctx, "managed", "Managed", "en", "managed", "managed.example.test", true); e == nil {
t.Fatal("managed creation bypassed enrollment")
}
keys := []string{"Key", "key", "key ", "日本語", "é", "e\u0301"}
for i, key := range keys {
for _, id := range []string{short.UUID, absolute.UUID} {
v := fmt.Sprintf("%s-%d-本文 🗒️\n? ' \"", id, i)
if e := write(ctx, id, key, "old"); e != nil {
t.Fatal(e)
}
if e := write(ctx, id, key, v); e != nil {
t.Fatal(e)
}
}
}
for i, key := range keys {
for _, id := range []string{short.UUID, absolute.UUID} {
want := fmt.Sprintf("%s-%d-本文 🗒️\n? ' \"", id, i)
if got, e := read(ctx, id, key); e != nil || got != want {
t.Fatal("config isolation/normalization", key, got, e)
}
}
}
if got, e := read(ctx, short.UUID, "missing"); e != nil || got != "" {
t.Fatal(got, e)
}
// Two distinct names claiming the same FQDN must not both commit.
start, results := make(chan struct{}), make(chan error, 2)
for i := 0; i < 2; i++ {
go func(i int) {
<-start
results <- create(ctx, fmt.Sprintf("race-%d", i), "Race", "en", "standalone", "race.example.test", true)
}(i)
}
close(start)
success := 0
for i := 0; i < 2; i++ {
if <-results == nil {
success++
}
}
if success != 1 {
t.Fatal("topology serialization", success)
}
cancelled, cancel := context.WithCancel(ctx)
cancel()
if e := create(cancelled, "cancelled", "Canceled", "en", "standalone", "cancelled.example.test", true); !errors.Is(e, context.Canceled) {
t.Fatal("create cancellation", e)
}
if e := update(cancelled, campus.ID, "default", "Canceled", "en", "standalone", "pages.example.test", true); !errors.Is(e, context.Canceled) {
t.Fatal("update cancellation", e)
}
if e := write(cancelled, short.UUID, "cancelled", "private"); !errors.Is(e, context.Canceled) {
t.Fatal("config cancellation", e)
}
if _, e := resolve(cancelled, "pages.example.test"); !errors.Is(e, context.Canceled) {
t.Fatal("read cancellation", e)
}
s.ReadOnly = true
if e := create(ctx, "readonly", "Readonly", "en", "standalone", "readonly.example.test", true); !errors.Is(e, ErrReadOnly) {
t.Fatal("readonly create", e)
}
if e := update(ctx, campus.ID, "default", "Readonly", "en", "standalone", "pages.example.test", true); !errors.Is(e, ErrReadOnly) {
t.Fatal("readonly update", e)
}
})
}
}
func TestMySQLNamespaceBoundaryAndRollback(t *testing.T) {
s := testNamespaceCoreStore(t, storeMySQL)
r := &MySQLNamespaceRepository{store: s}
ctx := context.Background()
domain, e := s.GetDefaultDomain()
if e != nil {
t.Fatal(e)
}
for _, bad := range []string{domain.UUID + " ", strings.ToUpper(domain.UUID), "invalid"} {
if e := r.SetConfig(ctx, bad, "key", "secret"); e == nil {
t.Fatal("noncanonical UUID", bad)
}
}
if e := r.SetConfig(ctx, uuid.NewString(), "key", "secret"); !errors.Is(e, sql.ErrNoRows) {
t.Fatal("orphan config", e)
}
if e := r.SetConfig(ctx, domain.UUID, machineLearningConfigKey, "{}"); e == nil {
t.Fatal("CAS bypass")
}
if e := r.SetConfig(ctx, domain.UUID, strings.Repeat("k", 256), "secret"); e == nil {
t.Fatal("oversize key")
}
campus, e := s.GetDefaultCampus()
if e != nil {
t.Fatal(e)
}
if e := r.UpdateCampus(ctx, campus.ID, "default", "Inherited", "en", " MANAGED ", "controller.example.test", true); e == nil {
t.Fatal("enrollment bypassed by update")
}
for _, unsupported := range []func() error{
s.EnsureDomainsSchema, s.EnsureCampusesSchema, s.EnsureConfigTable,
func() error { return s.DeleteDomain(domain.ID) },
func() error { return s.DeleteCampus(1) },
} {
if e := unsupported(); !errors.Is(e, ErrBackendFeatureUnavailable) {
t.Fatal("unported operation not refused", e)
}
}
if e := s.CreateDomain(domain.CampusUUID, "no-auth-schema", "No auth schema", "no-auth", "local", "", "", true); e == nil {
t.Fatal("Domain created without auth dependencies")
}
if _, e := s.GetDomainByHost("no-auth.localhost"); !errors.Is(e, sql.ErrNoRows) {
t.Fatal("partial Domain remains", e)
}
if e := r.CreateCampus(ctx, "default", "private-title", "en", "standalone", "private-host.example.test", true); e == nil || strings.Contains(e.Error(), "private") || strings.Contains(e.Error(), "Duplicate") {
t.Fatal("unsafe error", e)
}
// Reserve the topology lock, mutate, then abort. Neither changes nor lock
// survive rollback. This verifies the lock is transactional, not session-only.
e = s.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
if _, e := tx.ExecContext(ctx, `UPDATE domains SET title='must rollback' WHERE uuid=?`, domain.UUID); e != nil {
return e
}
return ErrReadOnly
})
if !errors.Is(e, ErrReadOnly) {
t.Fatal(e)
}
got, e := s.GetDomainByUUID(domain.UUID)
if e != nil || got.Title != domain.Title {
t.Fatal("rollback failed", got, e)
}
deadline, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
if e := r.CreateCampus(deadline, "after-rollback", "Works", "en", "standalone", "after.example.test", true); e != nil {
t.Fatal("retained lock", e)
}
s.ReadOnly = true
if e := r.SetConfig(ctx, domain.UUID, "readonly", "secret"); !errors.Is(e, ErrReadOnly) {
t.Fatal("readonly config", e)
}
s.ReadOnly = false
if _, e := s.DB.Exec(`ALTER TABLE campuses DROP INDEX name`); e != nil {
t.Fatal(e)
}
if _, e := r.InspectSchema(ctx); e == nil {
t.Fatal("missing unique index accepted")
}
}
func TestMySQLNamespaceLockDeadline(t *testing.T) {
s := testNamespaceCoreStore(t, storeMySQL)
r := &MySQLNamespaceRepository{store: s}
ctx := context.Background()
tx, e := s.DB.BeginTx(ctx, nil)
if e != nil {
t.Fatal(e)
}
defer tx.Rollback()
if _, e := tx.ExecContext(ctx, `UPDATE namespace_write_lock SET id=id WHERE id=1`); e != nil {
t.Fatal(e)
}
deadline, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
defer cancel()
if e := r.CreateCampus(deadline, "timeout", "Private", "en", "standalone", "timeout.example.test", true); !errors.Is(e, context.DeadlineExceeded) {
t.Fatal("lock ignored deadline", e)
}
if e := tx.Rollback(); e != nil {
t.Fatal(e)
}
deadline2, cancel2 := context.WithTimeout(ctx, 3*time.Second)
defer cancel2()
if e := r.CreateCampus(deadline2, "timeout", "Works", "en", "standalone", "timeout.example.test", true); e != nil {
t.Fatal("canceled transaction retained lock/data", e)
}
}
func TestMySQLNamespaceSchemaResume(t *testing.T) {
s, _ := mlTestStore(t, storeMySQL)
ctx := context.Background()
r := &MySQLNamespaceRepository{store: s}
if e := r.PrepareSchema(ctx); e != nil {
t.Fatal(e)
}
if _, e := s.DB.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=1 WHERE component='store-namespaces'`); e != nil {
t.Fatal(e)
}
if e := r.PrepareSchema(ctx); !errors.Is(e, db.ErrMySQLMigrationDirty) {
t.Fatal(e)
}
if e := r.ResumeSchema(ctx); e != nil {
t.Fatal(e)
}
}
func TestMySQLConfigVersionOneUpgrade(t *testing.T) {
database := mysqlTestDatabase(t)
ctx := context.Background()
steps := mysqlMLMigrations()
if e := db.ApplyMySQLMigrations(ctx, database, "machine-learning", steps[:1]); e != nil {
t.Fatal(e)
}
domain := uuid.NewString()
if _, e := database.Exec("INSERT INTO config(domain_uuid,`key`,value,updated_at) VALUES(?,'Existing','本文 📝',123)", domain); e != nil {
t.Fatal(e)
}
var originalHash string
if e := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='machine-learning' AND version=1`).Scan(&originalHash); e != nil {
t.Fatal(e)
}
r := NewMySQLNamespaceRepository(database)
status, e := r.InspectSchema(ctx)
if e != nil || status.Pending != 2 || status.Applied != 1 {
t.Fatal(status, e)
}
if e := r.PrepareSchema(ctx); e != nil {
t.Fatal(e)
}
var value, hash string
if e := database.QueryRow("SELECT value FROM config WHERE domain_uuid=? AND `key`='Existing'", domain).Scan(&value); e != nil || value != "本文 📝" {
t.Fatal("data lost", value, e)
}
if e := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='machine-learning' AND version=1`).Scan(&hash); e != nil || hash != originalHash {
t.Fatal("v1 history changed", e)
}
// Simulate ALTER committed before its acknowledgement; the v2 resume
// checks the new collation and must not re-adopt or destroy config data.
if _, e := database.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=0 WHERE component='machine-learning' AND version=2`); e != nil {
t.Fatal(e)
}
if e := r.ResumeSchema(ctx); e == nil {
t.Fatal("dirty prerequisite ignored")
}
status, e = r.InspectSchema(ctx)
if e != nil || !status.Dirty || status.DirtyComponent != "machine-learning" {
t.Fatal(status, e)
}
if e := NewMySQLMLRepository(database).ResumeSchema(ctx); e != nil {
t.Fatal(e)
}
if e := r.ResumeSchema(ctx); e != nil {
t.Fatal(e)
}
// Each pooled connection must refuse truncation, even if the server's
// global defaults are permissive. Hold both open to force two connections.
for i := 0; i < 2; i++ {
connection, e := database.Conn(ctx)
if e != nil {
t.Fatal(e)
}
defer connection.Close()
var mode string
if e := connection.QueryRowContext(ctx, `SELECT @@SESSION.sql_mode`).Scan(&mode); e != nil || !strings.Contains(mode, "STRICT_ALL_TABLES") {
t.Fatal("strict mode not set", e)
}
if _, e := connection.ExecContext(ctx, "INSERT INTO config(domain_uuid,`key`,value,updated_at) VALUES(?,?,?,0)", domain, strings.Repeat("k", 256), "must not truncate"); e == nil {
t.Fatal("silently truncated oversized key")
}
}
}