Files
knowledge-governance/internal/releaseadapter/v071/gateway_authority.go
T
dev cbc6b981c6
build / build (push) Successful in 1m56s
fix(library): 0.9.0 索引写入/归属校验不补 tenant_id,冲突可定位
- SearchIdentity 增加 NoTenantField,按目标 profile 决定是否注入 tenant_id
  (写入、归属预检、恢复搬运三条路径)
- 归属冲突与写集合不匹配写明具体字段,排查不用再猜
- 网关侧 acquire 冲突打印 plan/claim/owner 三项
2026-11-17 11:59:45 +08:00

138 lines
7.1 KiB
Go

package v071
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/libraryrelease"
"knowledge-governance/internal/objectgateway"
"log"
"path/filepath"
)
// GatewayGovernanceAuthority runs only in the trusted gateway control domain.
// Its governance connection is SELECT-only; the ordinary worker never receives
// the gateway control credential or backend write credential. Archive contents
// are trusted only after their immutable digest is found in the original
// persisted prebackup event belonging to the currently leased attempt.
type GatewayGovernanceAuthority struct {
Pool *pgxpool.Pool
ArchiveRoot string
TargetID string
Provider string
Bucket string
}
func (a *GatewayGovernanceAuthority) Ready(ctx context.Context) error {
if a == nil || a.Pool == nil || !filepath.IsAbs(a.ArchiveRoot) || a.TargetID == "" || a.Provider == "" || a.Bucket == "" {
return objectgateway.ErrAuthority
}
var safe bool
e := a.Pool.QueryRow(ctx, `SELECT NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole FROM pg_roles WHERE rolname=current_user`).Scan(&safe)
if e != nil || !safe {
return objectgateway.ErrAuthorityPrivileges
}
for _, table := range []string{"library_jobs", "library_operations", "library_attempts", "library_versions", "jobs"} {
e = a.Pool.QueryRow(ctx, `SELECT has_table_privilege(current_user,$1,'SELECT') AND NOT has_table_privilege(current_user,$1,'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER')`, table).Scan(&safe)
if e != nil || !safe {
return objectgateway.ErrAuthorityPrivileges
}
}
return nil
}
func (a *GatewayGovernanceAuthority) Load(ctx context.Context, c objectgateway.Claim) (objectgateway.Plan, error) {
if e := a.Ready(ctx); e != nil {
return objectgateway.Plan{}, e
}
if a == nil || a.Pool == nil || !filepath.IsAbs(a.ArchiveRoot) || a.TargetID == "" || a.Provider == "" || a.Bucket == "" {
return objectgateway.Plan{}, objectgateway.ErrAuthority
}
recovery, err := a.verifyRecoveryClaim(ctx, c)
if err != nil {
return objectgateway.Plan{}, err
}
var scope, backup, snapshot string
var matches int
e := a.Pool.QueryRow(ctx, `SELECT j.scope,v.snapshot_id,v.evidence->>'writeset_target_snapshot',count(*) OVER()
FROM library_jobs j
JOIN library_operations o ON o.id=j.operation_id AND o.target_id=j.target_id
JOIN library_attempts a ON a.operation_id=j.operation_id AND a.epoch=j.attempt_epoch AND a.job_id=j.id
JOIN library_versions v ON v.source_job_id=j.id AND v.operation_id=j.operation_id AND v.scope=j.scope AND v.kind='production_prebackup' AND v.target_id=j.target_id
WHERE j.id=$1 AND j.operation_id=$2 AND j.attempt_epoch=$3 AND j.lease_owner=$4 AND j.target_id=$6
AND j.lease_until>clock_timestamp() AND (j.state='running' OR $7)
AND a.owner=$4 AND a.state IN ('claimed','running') AND a.lease_until>clock_timestamp()
AND v.evidence->>'writeset_digest'=$5
AND v.evidence->>'job'=j.id AND v.evidence->>'backup_snapshot'=v.snapshot_id
AND (o.target_snapshot_id='' OR o.target_snapshot_id=v.evidence->>'writeset_target_snapshot')
AND NOT EXISTS(SELECT 1 FROM library_attempts newer WHERE newer.operation_id=a.operation_id AND newer.epoch>a.epoch)`, c.JobID, c.OperationID, c.AttemptEpoch, c.Owner, c.PlanDigest, a.TargetID, recovery).Scan(&scope, &backup, &snapshot, &matches)
if errors.Is(e, pgx.ErrNoRows) {
return objectgateway.Plan{}, objectgateway.ErrEpoch
}
if e != nil {
return objectgateway.Plan{}, objectgateway.ErrPersistence
}
if matches != 1 {
log.Printf("gateway authority: claim matches=%d job=%s op=%s epoch=%d", matches, c.JobID, c.OperationID, c.AttemptEpoch)
return objectgateway.Plan{}, objectgateway.ErrConflict
}
set, e := LoadWriteSet(a.ArchiveRoot, c.PlanDigest)
if e != nil || set == nil {
log.Printf("gateway authority: writeset %s unavailable: %v", c.PlanDigest, e)
return objectgateway.Plan{}, objectgateway.ErrConflict
}
if set.Version != libraryrelease.MigrationWriteSetVersion || set.JobID != c.JobID || set.Target != scope || set.BackupSnapshotID != backup || set.TargetSnapshotID != snapshot {
log.Printf("gateway authority: writeset mismatch version=%d/%d job=%s/%s target=%s/%s backup=%s/%s target_snap=%s/%s",
set.Version, libraryrelease.MigrationWriteSetVersion, set.JobID, c.JobID, set.Target, scope,
set.BackupSnapshotID, backup, set.TargetSnapshotID, snapshot)
return objectgateway.Plan{}, objectgateway.ErrConflict
}
for _, obj := range set.Objects {
if obj.Provider != a.Provider || obj.Bucket != a.Bucket {
return objectgateway.Plan{}, objectgateway.ErrConflict
}
}
return ObjectGatewayPlan(*set)
}
// Recovery authorization does not replace c.JobID/c.OperationID (the original
// send domain). Its separate queue and operation must both be durable, leased,
// and bound to the same before-image, source, target and frozen plan.
func (a *GatewayGovernanceAuthority) verifyRecoveryClaim(ctx context.Context, c objectgateway.Claim) (bool, error) {
if c.RecoveryJobID == "" && c.RecoveryOperationID == "" {
return false, nil
}
if c.RecoveryJobID != governance.LibraryRecoveryQueueID(c.JobID) {
return false, objectgateway.ErrConflict
}
var scope, backup, source, recorded string
e := a.Pool.QueryRow(ctx, `SELECT j.scope,v.snapshot_id,v.evidence->>'writeset_target_snapshot',o.request_digest
FROM library_jobs j JOIN library_versions v ON v.source_job_id=j.id AND v.operation_id=j.operation_id
AND v.target_id=j.target_id AND v.scope=j.scope AND v.kind='production_prebackup'
JOIN jobs q ON q.id=$3 AND q.type='library.recover' AND q.state='running'
JOIN library_operations o ON o.id=$4 AND o.kind='recover' AND o.scope=j.scope AND o.target_id=j.target_id
WHERE j.id=$1 AND j.operation_id=$2 AND j.target_id=$5
AND q.payload->>'scope'=j.scope AND q.payload->>'window_job_id'=j.id
AND COALESCE(NULLIF(q.payload->>'source_snapshot_id',''),v.evidence->>'writeset_target_snapshot')=v.evidence->>'writeset_target_snapshot'
AND COALESCE(NULLIF(q.payload->>'target_id',''),j.target_id)=j.target_id
AND COALESCE(NULLIF(q.payload->>'original_operation_id',''),j.operation_id)=j.operation_id
AND COALESCE(NULLIF(q.payload->>'backup_snapshot_id',''),v.snapshot_id)=v.snapshot_id
AND COALESCE(NULLIF(q.payload->>'plan_digest',''),$7)=$7
AND q.idempotency_key='library.recover:'||j.id AND q.lease_until>clock_timestamp()
AND q.lease_owner||'#'||q.id||'#'||q.attempt::text=$6
AND o.operation_key=q.id AND o.target_snapshot_id=v.snapshot_id
AND v.evidence->>'writeset_digest'=$7`, c.JobID, c.OperationID, c.RecoveryJobID, c.RecoveryOperationID, a.TargetID, c.Owner, c.PlanDigest).Scan(&scope, &backup, &source, &recorded)
if errors.Is(e, pgx.ErrNoRows) {
return false, objectgateway.ErrConflict
}
if e != nil {
return false, objectgateway.ErrPersistence
}
digest, e := governance.LibraryRecoveryDigest(scope, c.RecoveryJobID, c.JobID, c.OperationID, a.TargetID, source, backup, c.PlanDigest)
if e != nil || recorded != digest || c.RecoveryOperationID != governance.LibraryOperationID(scope, governance.LibraryJobRecover, c.RecoveryJobID) {
return false, objectgateway.ErrConflict
}
return true, nil
}