package postgres import ( "context" "errors" "fmt" "time" "github.com/jackc/pgx/v5" ) // WeKnoraConnection is one environment's 地址 + 写-only 密钥. The ciphertext is // opened only in the service layer; everything below this line treats it as an // opaque blob so no query result can accidentally be rendered as a secret. type WeKnoraConnection struct { Environment string Revision int64 Endpoint string KeyCiphertext []byte KeyTail string Verification string LibraryCount int CheckedAt *time.Time UpdatedBy string UpdatedAt time.Time } // WeKnoraConnectionTest is the evidence a save needs: which endpoint, which key // (fingerprint only) and what the last real listing said. type WeKnoraConnectionTest struct { Environment string Endpoint string KeyFingerprint string Outcome string LibraryCount int Message string CheckedAt time.Time } // LoadWeKnoraConnections reads both environments. A missing row is simply absent // from the result: 「未配置」 is a state, not an error. func (s *Store) LoadWeKnoraConnections(ctx context.Context) ([]WeKnoraConnection, error) { rows, err := s.db.Query(ctx, ` SELECT environment,revision,endpoint,key_ciphertext,key_tail,verification,library_count,checked_at,updated_by,updated_at FROM weknora_environment_connections ORDER BY environment`) if err != nil { return nil, errors.New("load weknora connections") } defer rows.Close() connections := make([]WeKnoraConnection, 0, 2) for rows.Next() { var connection WeKnoraConnection if err := rows.Scan(&connection.Environment, &connection.Revision, &connection.Endpoint, &connection.KeyCiphertext, &connection.KeyTail, &connection.Verification, &connection.LibraryCount, &connection.CheckedAt, &connection.UpdatedBy, &connection.UpdatedAt); err != nil { return nil, errors.New("load weknora connections") } connections = append(connections, connection) } if rows.Err() != nil { return nil, errors.New("load weknora connections") } return connections, nil } // LoadWeKnoraConnection reads one environment. The boolean is false when the // environment was never configured. func (s *Store) LoadWeKnoraConnection(ctx context.Context, environment string) (WeKnoraConnection, bool, error) { var connection WeKnoraConnection err := s.db.QueryRow(ctx, ` SELECT environment,revision,endpoint,key_ciphertext,key_tail,verification,library_count,checked_at,updated_by,updated_at FROM weknora_environment_connections WHERE environment=$1`, environment). Scan(&connection.Environment, &connection.Revision, &connection.Endpoint, &connection.KeyCiphertext, &connection.KeyTail, &connection.Verification, &connection.LibraryCount, &connection.CheckedAt, &connection.UpdatedBy, &connection.UpdatedAt) if errors.Is(err, pgx.ErrNoRows) { return WeKnoraConnection{}, false, nil } if err != nil { return WeKnoraConnection{}, false, errors.New("load weknora connection") } return connection, true, nil } // SaveWeKnoraConnection writes one revision and its history row in a single // transaction. The advisory lock is per environment so two concurrent saves // cannot both pick the same revision. func (s *Store) SaveWeKnoraConnection(ctx context.Context, connection WeKnoraConnection, now time.Time) error { if now.IsZero() { return errors.New("weknora connection save requires a timestamp") } tx, err := s.db.Begin(ctx) if err != nil { return fmt.Errorf("begin weknora connection save: %w", err) } defer func() { _ = tx.Rollback(ctx) }() if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext('weknora_connection:'||$1))`, connection.Environment); err != nil { return fmt.Errorf("lock weknora connection: %w", err) } if _, err := tx.Exec(ctx, ` INSERT INTO weknora_environment_connections(environment,revision,endpoint,key_ciphertext,key_tail,verification,library_count,checked_at,updated_by,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) ON CONFLICT(environment) DO UPDATE SET revision=EXCLUDED.revision, endpoint=EXCLUDED.endpoint, key_ciphertext=EXCLUDED.key_ciphertext, key_tail=EXCLUDED.key_tail, verification=EXCLUDED.verification, library_count=EXCLUDED.library_count, checked_at=EXCLUDED.checked_at, updated_by=EXCLUDED.updated_by, updated_at=EXCLUDED.updated_at`, connection.Environment, connection.Revision, connection.Endpoint, connection.KeyCiphertext, connection.KeyTail, connection.Verification, connection.LibraryCount, connection.CheckedAt, connection.UpdatedBy, now); err != nil { return errors.New("save weknora connection") } if _, err := tx.Exec(ctx, ` INSERT INTO weknora_environment_connection_history(environment,revision,endpoint,key_configured,verification,actor,created_at) VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT(environment,revision) DO NOTHING`, connection.Environment, connection.Revision, connection.Endpoint, len(connection.KeyCiphertext) > 0, connection.Verification, connection.UpdatedBy, now); err != nil { return errors.New("record weknora connection history") } if err := tx.Commit(ctx); err != nil { return fmt.Errorf("commit weknora connection save: %w", err) } return nil } // SaveWeKnoraConnectionTest stores the outcome of the real listing a save will // later point at. Only the key fingerprint is kept — never the key. func (s *Store) SaveWeKnoraConnectionTest(ctx context.Context, result WeKnoraConnectionTest, now time.Time) error { if now.IsZero() { return errors.New("weknora connection test requires a timestamp") } if _, err := s.db.Exec(ctx, ` INSERT INTO weknora_environment_connection_tests(environment,endpoint,key_fingerprint,outcome,library_count,message,checked_at) VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT(environment) DO UPDATE SET endpoint=EXCLUDED.endpoint, key_fingerprint=EXCLUDED.key_fingerprint, outcome=EXCLUDED.outcome, library_count=EXCLUDED.library_count, message=EXCLUDED.message, checked_at=EXCLUDED.checked_at`, result.Environment, result.Endpoint, result.KeyFingerprint, result.Outcome, result.LibraryCount, result.Message, now); err != nil { return errors.New("save weknora connection test") } return nil } // LoadWeKnoraConnectionTest reads the last test for one environment. func (s *Store) LoadWeKnoraConnectionTest(ctx context.Context, environment string) (WeKnoraConnectionTest, bool, error) { var result WeKnoraConnectionTest err := s.db.QueryRow(ctx, ` SELECT environment,endpoint,key_fingerprint,outcome,library_count,message,checked_at FROM weknora_environment_connection_tests WHERE environment=$1`, environment). Scan(&result.Environment, &result.Endpoint, &result.KeyFingerprint, &result.Outcome, &result.LibraryCount, &result.Message, &result.CheckedAt) if errors.Is(err, pgx.ErrNoRows) { return WeKnoraConnectionTest{}, false, nil } if err != nil { return WeKnoraConnectionTest{}, false, errors.New("load weknora connection test") } return result, true, nil } // UpdateWeKnoraConnectionVerification refreshes the card state without touching // the saved endpoint or ciphertext. func (s *Store) UpdateWeKnoraConnectionVerification(ctx context.Context, environment, verification string, libraryCount int, checkedAt time.Time, now time.Time) error { if _, err := s.db.Exec(ctx, ` UPDATE weknora_environment_connections SET verification=$2, library_count=$3, checked_at=$4, updated_at=$5 WHERE environment=$1`, environment, verification, libraryCount, checkedAt, now); err != nil { return errors.New("update weknora connection verification") } return nil } // ProductionExecutionCounts reports, for executions that are still in flight, // how many items already have a frozen production target and how many do not yet. // A production binding change never rewrites the frozen ones: an execution that // already started keeps the knowledge base it was authorized against. Lifetime // counts are deliberately excluded — completed executions are history, not // something a binding change could still affect. func (s *Store) ProductionExecutionCounts(ctx context.Context) (int, int, error) { var frozen, retargetable int if err := s.db.QueryRow(ctx, ` SELECT COUNT(*) FILTER (WHERE item.target_knowledge_base_id <> ''), COUNT(*) FILTER (WHERE item.target_knowledge_base_id = '') FROM release_item_executions item JOIN release_executions execution ON execution.id = item.release_execution_id WHERE execution.state IN ('pending','running')`).Scan(&frozen, &retargetable); err != nil { return 0, 0, errors.New("load production execution counts") } return frozen, retargetable, nil }