feat(state): apply audit retention to observability events

This commit is contained in:
sam committed 2026-10-25 21:42:38 +11:00
1 parent 655068db70
commit 045f8c427d
9 files changed
+478 -2

No files matched your search

@@ -0,0 +1,82 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
const (
// auditPruneBatch is one delete's bound; auditPruneMaxBatches keeps a
// single sweep from owning the table for an unbounded time.
auditPruneBatch = 10_000
auditPruneMaxBatches = 100
auditRetentionActor = "archie-state-store"
auditRetentionSource = "audit retention"
)
// ErrAuditPruneBusy reports that another audit retention sweep holds the lock.
// The caller skips its tick rather than waiting.
var ErrAuditPruneBusy = errors.New("postgres: audit prune already running")
// auditPruneRecord is the value stored on the sweep's audit row.
type auditPruneRecord struct {
Cutoff time.Time `json:"cutoff"`
Rows int64 `json:"rows"`
}
// PruneAuditEvents deletes events of the given kinds older than cutoff in
// bounded batches and appends one sys_audit row recording the cutoff and the
// total removed, even when that total is zero. The whole sweep is one
// transaction under the audit prune lock, so the lock covers every batch and a
// concurrent sweep gets ErrAuditPruneBusy without touching a row. The kind
// list is the caller's allowlist: this method deletes nothing else.
func (s *Store) PruneAuditEvents(ctx context.Context, kinds []string, cutoff time.Time) (int64, error) {
if len(kinds) == 0 {
return 0, nil
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return 0, fmt.Errorf("prune audit events: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
q := postgresdb.New(tx)
locked, err := q.TryAuditPruneLock(ctx)
if err != nil {
return 0, fmt.Errorf("audit prune lock: %w", err)
}
if !locked {
return 0, ErrAuditPruneBusy
}
var total int64
for range auditPruneMaxBatches {
removed, err := q.PruneAuditEventBatch(ctx, postgresdb.PruneAuditEventBatchParams{
Kinds: kinds, Cutoff: cutoff.UTC(), Batch: auditPruneBatch,
})
if err != nil {
return 0, fmt.Errorf("prune audit events: %w", err)
}
total += removed
if removed < auditPruneBatch {
break
}
}
// The sweep is not an RPC, so it attributes its own row: the State Store
// pruned the events and the retention setting decided how many.
ctx = access.WithActor(access.WithSource(ctx, auditRetentionSource), auditRetentionActor)
if err := insertAuditValues(ctx, q, "audit_retention", "runtime_events", "pruned", nil,
auditPruneRecord{Cutoff: cutoff.UTC(), Rows: total}, 0, storecontract.DefaultOrgID); err != nil {
return 0, err
}
if err := tx.Commit(ctx); err != nil {
return 0, fmt.Errorf("prune audit events: %w", err)
}
return total, nil
}
@@ -167,3 +167,43 @@ func (q *Queries) LockAuditRecord(ctx context.Context, arg LockAuditRecordParams
_, err := q.db.Exec(ctx, lockAuditRecord, arg.TableName, arg.RecordKey)
return err
}
const pruneAuditEventBatch = `-- name: PruneAuditEventBatch :execrows
DELETE FROM events
WHERE id IN (
SELECT id FROM events
WHERE kind = ANY($1::text[])
AND at < $2::timestamptz
ORDER BY at
LIMIT $3::bigint
)
`
type PruneAuditEventBatchParams struct {
Kinds []string
Cutoff time.Time
Batch int64
}
// One bounded delete of the observability kinds the sweep allows, oldest
// first. The kind list is code, so no stored setting can widen it.
func (q *Queries) PruneAuditEventBatch(ctx context.Context, arg PruneAuditEventBatchParams) (int64, error) {
result, err := q.db.Exec(ctx, pruneAuditEventBatch, arg.Kinds, arg.Cutoff, arg.Batch)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const tryAuditPruneLock = `-- name: TryAuditPruneLock :one
SELECT pg_try_advisory_xact_lock(hashtextextended('archie.audit.prune', 0))
`
// The retention sweep's transaction-scoped lock. A second sweep skips its
// tick rather than queuing deletes behind this one.
func (q *Queries) TryAuditPruneLock(ctx context.Context) (bool, error) {
row := q.db.QueryRow(ctx, tryAuditPruneLock)
var pg_try_advisory_xact_lock bool
err := row.Scan(&pg_try_advisory_xact_lock)
return pg_try_advisory_xact_lock, err
}
@@ -25,6 +25,23 @@ VALUES (now(), sqlc.arg(table_name)::text, sqlc.arg(record_key)::text, sqlc.arg(
sqlc.arg(old_value)::jsonb, sqlc.arg(new_value)::jsonb, sqlc.arg(record_version)::bigint,
sqlc.arg(actor)::text, sqlc.arg(source)::text, sqlc.arg(request_id)::text, sqlc.arg(org_id)::text);
-- name: TryAuditPruneLock :one
-- The retention sweep's transaction-scoped lock. A second sweep skips its
-- tick rather than queuing deletes behind this one.
SELECT pg_try_advisory_xact_lock(hashtextextended('archie.audit.prune', 0));
-- name: PruneAuditEventBatch :execrows
-- One bounded delete of the observability kinds the sweep allows, oldest
-- first. The kind list is code, so no stored setting can widen it.
DELETE FROM events
WHERE id IN (
SELECT id FROM events
WHERE kind = ANY(sqlc.arg(kinds)::text[])
AND at < sqlc.arg(cutoff)::timestamptz
ORDER BY at
LIMIT sqlc.arg(batch)::bigint
);
-- name: AuditForRecords :many
SELECT id, at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id
FROM sys_audit