8d838d9cb4
build / build (push) Successful in 1m45s
执行时真实时钟与持久授权回读(撤销/过期即停并保留预备份)、写集合写前落盘、 租约与 attempt 身份、恢复队列与原发送身份分离、成功收尾必须释放维护后再登记终态。
209 lines
9.6 KiB
Go
209 lines
9.6 KiB
Go
package v071
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"knowledge-governance/internal/librarysnapshot"
|
|
)
|
|
|
|
type migrationCatalog map[string]json.RawMessage
|
|
|
|
// Catalog capture is read-only. Sequence *definitions*, not mutable last_value,
|
|
// belong in the fingerprint; allocating a number must not look like DDL drift.
|
|
func (t *ProductionLibraryTarget) migrationCatalog(ctx context.Context) (migrationCatalog, string, error) {
|
|
tx, err := t.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
defer tx.Rollback(context.WithoutCancel(ctx))
|
|
catalog, digest, err := captureMigrationCatalog(ctx, tx)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return nil, "", err
|
|
}
|
|
return catalog, digest, nil
|
|
}
|
|
|
|
// Source rows and their definitions must come from the same read-only transaction.
|
|
func captureMigrationCatalog(ctx context.Context, tx pgx.Tx) (migrationCatalog, string, error) {
|
|
queries := map[string]string{
|
|
"columns": `SELECT c.relname AS table_name,a.attname AS column_name,format_type(a.atttypid,a.atttypmod) AS type,a.attnotnull AS not_null,a.attidentity AS identity,a.attgenerated AS generated,coalesce(pg_get_expr(d.adbin,d.adrelid),'') AS default_expr FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum WHERE n.nspname='public' AND c.relname=ANY($1) AND a.attnum>0 AND NOT a.attisdropped ORDER BY c.relname,a.attnum`,
|
|
"constraints": `SELECT ns.nspname AS namespace,c.relname AS table_name,x.conname AS name,x.contype AS type,pg_get_constraintdef(x.oid) AS definition,coalesce(r.relname,'') AS referenced_table,coalesce(rns.nspname,'') AS referenced_namespace FROM pg_constraint x JOIN pg_class c ON c.oid=x.conrelid JOIN pg_namespace ns ON ns.oid=c.relnamespace LEFT JOIN pg_class r ON r.oid=x.confrelid LEFT JOIN pg_namespace rns ON rns.oid=r.relnamespace WHERE (ns.nspname='public' AND c.relname=ANY($1)) OR (rns.nspname='public' AND r.relname=ANY($1)) ORDER BY ns.nspname,c.relname,x.conname`,
|
|
"indexes": `SELECT c.relname AS table_name,ic.relname AS name,i.indisunique AS unique_index,i.indisvalid AS valid,pg_get_indexdef(i.indexrelid) AS definition,coalesce(pg_get_expr(i.indpred,i.indrelid),'') AS predicate FROM pg_index i JOIN pg_class c ON c.oid=i.indrelid JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_class ic ON ic.oid=i.indexrelid WHERE n.nspname='public' AND c.relname=ANY($1) ORDER BY c.relname,ic.relname`,
|
|
"triggers": `SELECT c.relname AS table_name,g.tgname AS name,pg_get_triggerdef(g.oid) AS definition FROM pg_trigger g JOIN pg_class c ON c.oid=g.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relname=ANY($1) AND NOT g.tgisinternal ORDER BY c.relname,g.tgname`,
|
|
"relations": `SELECT c.relname AS table_name,c.relkind::text AS kind,c.relispartition AS partition,c.relrowsecurity AS row_security,EXISTS(SELECT 1 FROM pg_inherits i WHERE i.inhrelid=c.oid OR i.inhparent=c.oid) AS inherits FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relname=ANY($1) ORDER BY c.relname`,
|
|
"sequences": `SELECT c.relname AS table_name,a.attname AS column_name,coalesce(s.seqrelid::regclass::text,'') AS sequence,s.seqstart,s.seqincrement,s.seqmin,s.seqmax,s.seqcache,s.seqcycle,coalesce(own.deptype::text,'') AS ownership FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum LEFT JOIN pg_depend dep ON dep.classid='pg_attrdef'::regclass AND dep.objid=d.oid AND dep.refclassid='pg_class'::regclass AND EXISTS(SELECT 1 FROM pg_sequence sq WHERE sq.seqrelid=dep.refobjid) LEFT JOIN pg_depend own ON own.refclassid='pg_class'::regclass AND own.refobjid=c.oid AND own.refobjsubid=a.attnum AND own.classid='pg_class'::regclass AND own.deptype IN ('a','i') AND EXISTS(SELECT 1 FROM pg_sequence sq WHERE sq.seqrelid=own.objid) LEFT JOIN pg_sequence s ON s.seqrelid=coalesce(dep.refobjid,own.objid) WHERE n.nspname='public' AND c.relname=ANY($1) AND a.attnum>0 AND NOT a.attisdropped AND (s.seqrelid IS NOT NULL OR a.attname='seq_id' OR (c.relname='wiki_log_entries' AND a.attname='id')) ORDER BY c.relname,a.attname,s.seqrelid`,
|
|
}
|
|
catalog := migrationCatalog{}
|
|
for key, query := range queries {
|
|
var raw []byte
|
|
if err := tx.QueryRow(ctx, "SELECT coalesce(jsonb_agg(to_jsonb(q)),'[]'::jsonb) FROM ("+query+") q", productionLibraryTables).Scan(&raw); err != nil {
|
|
return nil, "", fmt.Errorf("capture migration catalog %s: %w", key, err)
|
|
}
|
|
catalog[key] = raw
|
|
}
|
|
raw, err := json.Marshal(catalog)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
hash := sha256.Sum256(raw)
|
|
return catalog, hex.EncodeToString(hash[:]), nil
|
|
}
|
|
|
|
func validateMigrationCatalog(catalog migrationCatalog) error {
|
|
var triggers []json.RawMessage
|
|
if err := json.Unmarshal(catalog["triggers"], &triggers); err != nil {
|
|
return err
|
|
}
|
|
if len(triggers) > 0 {
|
|
return errors.New("unreviewed migration trigger effects")
|
|
}
|
|
var relations []struct {
|
|
Table string `json:"table_name"`
|
|
Kind string `json:"kind"`
|
|
Partition bool `json:"partition"`
|
|
RLS bool `json:"row_security"`
|
|
Inherits bool `json:"inherits"`
|
|
}
|
|
if err := json.Unmarshal(catalog["relations"], &relations); err != nil {
|
|
return err
|
|
}
|
|
if len(relations) != len(productionLibraryTables) {
|
|
return errors.New("incomplete migration table catalog")
|
|
}
|
|
for _, r := range relations {
|
|
if r.Kind != "r" || r.Partition || r.RLS || r.Inherits {
|
|
return fmt.Errorf("unsupported migration relation: %s", r.Table)
|
|
}
|
|
}
|
|
var constraints []struct {
|
|
Namespace string `json:"namespace"`
|
|
Table string `json:"table_name"`
|
|
Type string `json:"type"`
|
|
Referenced string `json:"referenced_table"`
|
|
ReferencedNamespace string `json:"referenced_namespace"`
|
|
Definition string `json:"definition"`
|
|
}
|
|
if err := json.Unmarshal(catalog["constraints"], &constraints); err != nil {
|
|
return err
|
|
}
|
|
for _, c := range constraints {
|
|
if c.Type != "f" {
|
|
continue
|
|
}
|
|
// Internal-table membership does not prove the referenced identity survives
|
|
// local-number remapping. v071 has exactly these reviewed FK contracts.
|
|
if !(c.Namespace == "public" && c.ReferencedNamespace == "public" &&
|
|
(c.Table == "resource_bindings" || c.Table == "resource_access_grants") && c.Referenced == "resources" &&
|
|
c.Definition == "FOREIGN KEY (resource_id) REFERENCES resources(id) ON DELETE CASCADE") {
|
|
return fmt.Errorf("unreviewed incoming migration FK: %s.%s", c.Namespace, c.Table)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (t *ProductionLibraryTarget) preflightMigrationCatalog(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) (string, error) {
|
|
catalog, digest, err := t.migrationCatalog(ctx)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if err := validateMigrationCatalog(catalog); err != nil {
|
|
return "", err
|
|
}
|
|
var columns []struct {
|
|
Table string `json:"table_name"`
|
|
Column string `json:"column_name"`
|
|
Type string `json:"type"`
|
|
Generated string `json:"generated"`
|
|
Identity string `json:"identity"`
|
|
}
|
|
if err := json.Unmarshal(catalog["columns"], &columns); err != nil {
|
|
return "", err
|
|
}
|
|
allowed := map[string]map[string]string{}
|
|
for _, c := range columns {
|
|
if c.Generated != "" || c.Identity != "" {
|
|
return "", fmt.Errorf("unsupported generated/identity column: %s.%s", c.Table, c.Column)
|
|
}
|
|
if allowed[c.Table] == nil {
|
|
allowed[c.Table] = map[string]string{}
|
|
}
|
|
allowed[c.Table][c.Column] = c.Type
|
|
}
|
|
for _, part := range manifest.Parts {
|
|
if part.Kind == "schema" {
|
|
if part.Name != "migration-catalog" || part.SHA256 != digest {
|
|
return "", errors.New("captured source/target schema catalog mismatch")
|
|
}
|
|
reader, err := archive.OpenPart(part)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
reader.Close()
|
|
continue
|
|
}
|
|
if part.Kind != "database" && part.Kind != "wiki" {
|
|
continue
|
|
}
|
|
reader, err := archive.OpenPart(part)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var rows []map[string]json.RawMessage
|
|
err = json.NewDecoder(reader).Decode(&rows)
|
|
reader.Close()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
contract := migrationIdentityContracts[part.Name]
|
|
for _, row := range rows {
|
|
for name := range row {
|
|
if _, ok := allowed[part.Name][name]; !ok {
|
|
return "", fmt.Errorf("source column absent from target contract: %s.%s", part.Name, name)
|
|
}
|
|
}
|
|
if contract.LocalColumn != "" && allowed[part.Name][contract.LocalColumn] != "" {
|
|
if allowed[part.Name][contract.LocalColumn] != "bigint" {
|
|
return "", fmt.Errorf("local column type mismatch: %s.%s", part.Name, contract.LocalColumn)
|
|
}
|
|
if _, err := positiveBigint(row[contract.LocalColumn]); err != nil {
|
|
return "", fmt.Errorf("missing/invalid source local number: %s.%s", part.Name, contract.LocalColumn)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
raw, err := json.Marshal(catalog)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if err := persistImmutableJSON(t.config.ArchiveRoot+"/catalogs/"+digest+".json", raw); err != nil {
|
|
return "", err
|
|
}
|
|
return digest, nil
|
|
}
|
|
|
|
func (t *ProductionLibraryTarget) verifyPlanSchema(ctx context.Context) error {
|
|
if t.activePlan == nil {
|
|
return nil
|
|
}
|
|
if t.activePlan.SchemaDigest == "" {
|
|
return errors.New("persisted execution plan lacks schema fingerprint")
|
|
}
|
|
_, digest, err := t.migrationCatalog(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if digest != t.activePlan.SchemaDigest {
|
|
return errors.New("target schema changed after immutable plan")
|
|
}
|
|
return nil
|
|
}
|