Files

76 lines
2.4 KiB
Go

package postgres
import (
"context"
"encoding/json"
"fmt"
"reflect"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
// insertAudit writes one audit row inside the caller's transaction, attributed
// to the caller the RPC interceptor authenticated. table is the audited table's
// own name; nil oldValue is a create and nil newValue a delete.
func insertAudit(ctx context.Context, q *postgresdb.Queries, table, recordKey, field string, oldValue, newValue []byte, version int64, orgID string) error {
if err := q.InsertAudit(ctx, postgresdb.InsertAuditParams{
TableName: table,
RecordKey: recordKey,
Field: field,
OldValue: oldValue,
NewValue: newValue,
RecordVersion: version,
Actor: access.ActorFromContext(ctx),
Source: access.SourceFromContext(ctx),
OrgID: orgID,
}); err != nil {
return fmt.Errorf("audit %s %q: %w", table, recordKey, err)
}
return nil
}
// insertAuditValues encodes both sides of one change and writes the row, so a
// caller records the value it holds rather than pre-encoding it.
func insertAuditValues(ctx context.Context, q *postgresdb.Queries, table, recordKey, field string, oldValue, newValue any, version int64, orgID string) error {
oldJSON, err := auditJSON(oldValue)
if err != nil {
return err
}
newJSON, err := auditJSON(newValue)
if err != nil {
return err
}
return insertAudit(ctx, q, table, recordKey, field, oldJSON, newJSON, version, orgID)
}
// auditJSON encodes one side of an audit change. An absent value stays nil,
// which the column stores as NULL: absent is not the same fact as JSON null.
// A value that cannot be encoded is an error, never a silent NULL that would
// read as a create or delete.
func auditJSON(value any) ([]byte, error) {
if isNil(value) {
return nil, nil
}
out, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("audit value: %w", err)
}
return out, nil
}
// isNil covers the typed nils interface comparison misses, so a nil pointer or
// map is recorded as absent rather than the JSON literal null.
func isNil(value any) bool {
if value == nil {
return true
}
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
return v.IsNil()
default:
return false
}
}