feat(controlplane): field-level sys_audit table, audit view on settings pages, whole-task time limit

This commit is contained in:
sam committed 2026-09-25 09:54:30 +10:00
1 parent 49d7527f1c
commit 8fea8e8686
43 files changed
+1176 -174

No files matched your search

@@ -0,0 +1,56 @@
-- sys_audit is the field-level audit trail: one row per changed field of one
-- record, whatever the table. Settings resources are the first writer.
-- +goose Up
CREATE TABLE sys_audit (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
at timestamptz NOT NULL,
table_name text NOT NULL,
record_key text NOT NULL,
field text NOT NULL,
old_value jsonb,
new_value jsonb,
record_version bigint NOT NULL,
actor text NOT NULL,
source text NOT NULL,
request_id text NOT NULL
);
CREATE INDEX idx_sys_audit_record ON sys_audit (table_name, record_key, id DESC);
-- audit_json_diff lists the top-level fields that differ between two JSON
-- documents. A document that is not an object is audited whole, as field ''.
-- +goose StatementBegin
CREATE FUNCTION audit_json_diff(prev jsonb, doc jsonb)
RETURNS TABLE (field text, old_value jsonb, new_value jsonb)
LANGUAGE sql IMMUTABLE AS $$
SELECT k, prev -> k, doc -> k
FROM (
SELECT jsonb_object_keys(doc) AS k WHERE jsonb_typeof(doc) = 'object'
UNION
SELECT jsonb_object_keys(prev) WHERE jsonb_typeof(prev) = 'object'
) keys
WHERE jsonb_typeof(COALESCE(doc, '{}')) = 'object'
AND jsonb_typeof(COALESCE(prev, '{}')) = 'object'
AND (prev -> k) IS DISTINCT FROM (doc -> k)
UNION ALL
SELECT '', prev, doc
WHERE NOT (jsonb_typeof(COALESCE(doc, '{}')) = 'object'
AND jsonb_typeof(COALESCE(prev, '{}')) = 'object')
AND prev IS DISTINCT FROM doc
$$;
-- +goose StatementEnd
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
SELECT h.at, 'resources', h.kind, d.field, d.old_value, d.new_value, h.version, h.actor, h.source, h.request_id
FROM (
SELECT kind, version, actor, source, request_id, at,
convert_from(value, 'UTF8')::jsonb AS doc,
lag(convert_from(value, 'UTF8')::jsonb) OVER (PARTITION BY kind ORDER BY version) AS prev
FROM resource_history
) h
CROSS JOIN LATERAL audit_json_diff(h.prev, h.doc) d
ORDER BY h.kind, h.version, d.field;
-- +goose Down
DROP TABLE sys_audit;
DROP FUNCTION audit_json_diff(jsonb, jsonb);
@@ -0,0 +1,96 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: audit.sql
package postgresdb
import (
"context"
"time"
)
const auditForRecords = `-- name: AuditForRecords :many
SELECT id, at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id
FROM sys_audit
WHERE table_name = $1::text AND record_key = ANY($2::text[])
ORDER BY id DESC
LIMIT $3::bigint
`
type AuditForRecordsParams struct {
TableName string
RecordKeys []string
EntryLimit int64
}
func (q *Queries) AuditForRecords(ctx context.Context, arg AuditForRecordsParams) ([]SysAudit, error) {
rows, err := q.db.Query(ctx, auditForRecords, arg.TableName, arg.RecordKeys, arg.EntryLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []SysAudit
for rows.Next() {
var i SysAudit
if err := rows.Scan(
&i.ID,
&i.At,
&i.TableName,
&i.RecordKey,
&i.Field,
&i.OldValue,
&i.NewValue,
&i.RecordVersion,
&i.Actor,
&i.Source,
&i.RequestID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const insertResourceAudit = `-- name: InsertResourceAudit :exec
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
SELECT $1::timestamptz, 'resources', $2::text, d.field, d.old_value, d.new_value,
$3::bigint, $4::text, $5::text, $6::text
FROM audit_json_diff(
(SELECT convert_from(h.value, 'UTF8')::jsonb FROM resource_history h
WHERE h.kind = $2::text AND h.version = $7::bigint),
convert_from($8::bytea, 'UTF8')::jsonb
) d
ORDER BY d.field
`
type InsertResourceAuditParams struct {
At time.Time
Kind string
Version int64
Actor string
Source string
RequestID string
PreviousVersion int64
Value []byte
}
// Records the fields one resource write changed, against the version it
// replaced. Runs in the write's own transaction.
func (q *Queries) InsertResourceAudit(ctx context.Context, arg InsertResourceAuditParams) error {
_, err := q.db.Exec(ctx, insertResourceAudit,
arg.At,
arg.Kind,
arg.Version,
arg.Actor,
arg.Source,
arg.RequestID,
arg.PreviousVersion,
arg.Value,
)
return err
}
@@ -212,6 +212,20 @@ type Source struct {
UpdatedAt time.Time
}
type SysAudit struct {
ID int64
At time.Time
TableName string
RecordKey string
Field string
OldValue []byte
NewValue []byte
RecordVersion int64
Actor string
Source string
RequestID string
}
type Task struct {
ID int64
Owner string
@@ -0,0 +1,19 @@
-- name: InsertResourceAudit :exec
-- Records the fields one resource write changed, against the version it
-- replaced. Runs in the write's own transaction.
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
SELECT sqlc.arg(at)::timestamptz, 'resources', sqlc.arg(kind)::text, d.field, d.old_value, d.new_value,
sqlc.arg(version)::bigint, sqlc.arg(actor)::text, sqlc.arg(source)::text, sqlc.arg(request_id)::text
FROM audit_json_diff(
(SELECT convert_from(h.value, 'UTF8')::jsonb FROM resource_history h
WHERE h.kind = sqlc.arg(kind)::text AND h.version = sqlc.arg(previous_version)::bigint),
convert_from(sqlc.arg(value)::bytea, 'UTF8')::jsonb
) d
ORDER BY d.field;
-- name: AuditForRecords :many
SELECT id, at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id
FROM sys_audit
WHERE table_name = sqlc.arg(table_name)::text AND record_key = ANY(sqlc.arg(record_keys)::text[])
ORDER BY id DESC
LIMIT sqlc.arg(entry_limit)::bigint;
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"math"
"time"
"github.com/jackc/pgx/v5"
@@ -54,6 +55,29 @@ func (s *Resources) ResourceHistory(ctx context.Context, kind string, limit int)
return resources, nil
}
// Audit returns the field-level audit of the named records of one table,
// newest first. A limit of zero or less returns every entry.
func (s *Resources) Audit(ctx context.Context, table string, keys []string, limit int) ([]storecontract.AuditEntry, error) {
if limit <= 0 {
limit = math.MaxInt32
}
rows, err := postgresdb.New(s.pool).AuditForRecords(ctx, postgresdb.AuditForRecordsParams{
TableName: table, RecordKeys: keys, EntryLimit: int64(limit),
})
if err != nil {
return nil, err
}
entries := make([]storecontract.AuditEntry, 0, len(rows))
for _, row := range rows {
entries = append(entries, storecontract.AuditEntry{
ID: row.ID, Table: row.TableName, RecordKey: row.RecordKey, Field: row.Field,
OldValue: row.OldValue, NewValue: row.NewValue, Version: row.RecordVersion,
Actor: row.Actor, Source: row.Source, RequestID: row.RequestID, At: row.At,
})
}
return entries, nil
}
func (s *Resources) PutResource(ctx context.Context, write storecontract.ResourceWrite) (_ storecontract.Resource, retErr error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -111,6 +135,12 @@ func (s *Resources) PutResource(ctx context.Context, write storecontract.Resourc
if err != nil {
return storecontract.Resource{}, err
}
if err := queries.InsertResourceAudit(ctx, postgresdb.InsertResourceAuditParams{
At: write.At, Kind: write.Kind, Version: resource.Version, Actor: write.Actor,
Source: write.Source, RequestID: write.RequestID, PreviousVersion: current, Value: write.Value,
}); err != nil {
return storecontract.Resource{}, err
}
if err := tx.Commit(ctx); err != nil {
return storecontract.Resource{}, err
}
@@ -2,6 +2,8 @@ package postgres
import (
"errors"
"fmt"
"strings"
"testing"
"time"
@@ -296,3 +298,37 @@ func TestConcurrentResourceWritesAcceptOnlyOneExpectedVersion(t *testing.T) {
t.Fatalf("history after race = %+v, want exactly one version 1", history)
}
}
// TestResourceWritesRecordFieldLevelAudit: each write records one sys_audit row
// per field it changed, newest first, and a replayed write records nothing.
func TestResourceWritesRecordFieldLevelAudit(t *testing.T) {
resources := resourcesFor(t)
put := func(value string, expected int64, request string) {
t.Helper()
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
Kind: "settings", Value: []byte(value), Actor: "sam", Source: "archie-ui",
RequestID: request, ExpectedVersion: expected,
}); err != nil {
t.Fatalf("PutResource(%s): %v", value, err)
}
}
put(`{"a":1,"b":2}`, 0, "r1")
put(`{"a":1,"b":3,"c":4}`, 1, "r2")
put(`{"a":1,"b":3,"c":4}`, 1, "r2")
audit, err := resources.Audit(t.Context(), storecontract.AuditTableResources, []string{"settings"}, 0)
if err != nil {
t.Fatalf("ResourceAudit: %v", err)
}
got := make([]string, 0, len(audit))
for _, entry := range audit {
got = append(got, fmt.Sprintf("v%d %s %s->%s by %s", entry.Version, entry.Field, entry.OldValue, entry.NewValue, entry.Actor))
}
want := []string{
"v2 c ->4 by sam", "v2 b 2->3 by sam",
"v1 b ->2 by sam", "v1 a ->1 by sam",
}
if strings.Join(got, "; ") != strings.Join(want, "; ") {
t.Fatalf("audit =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
}