audit

package
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package audit 提供写操作审计原语:审计记录与业务写在同一事务内落库, 事务回滚则审计一并消失——审计反映的是"已发生的事实"。

PSP 约定:资金相关的每次状态变更(记账、退款、改配置)都应留一条审计。

Index

Constants

View Source
const DefaultTopic = "audit.event.v1"

DefaultTopic is the default event topic used by BusSink.

Variables

This section is empty.

Functions

func ArchiveMigrationSQL added in v0.13.0

func ArchiveMigrationSQL(schema string) string

ArchiveMigrationSQL returns idempotent DDL for the daily RANGE-partitioned archive table `<schema>.audit_archive_events`.

func MigrationSQL

func MigrationSQL(schema string) string

MigrationSQL 返回审计表 DDL(幂等),域 repo 把它并入自己的基础迁移。

func MigrationSQLBare

func MigrationSQLBare() string

MigrationSQLBare 返回无 schema 前缀的审计表 DDL,供分区域域 (appkit new domain -partitioned)的迁移使用:目标 schema 由 pgmigrate 在应用时经 SET LOCAL search_path 落位。两版的列定义必须保持一致。

func NewArchiveHandler added in v0.13.0

func NewArchiveHandler(batcher *Batcher, now func() time.Time) appkit.EventHandler

NewArchiveHandler adapts a Batcher into an appkit.EventHandler suitable for reg.Consumer(...) on any appkit EventBus.

Types

type ArchiveRecord added in v0.13.0

type ArchiveRecord struct {
	ID         string          `json:"id"`
	Topic      string          `json:"topic"`
	Partition  string          `json:"partition,omitempty"`
	TenantID   string          `json:"tenant_id,omitempty"`
	Actor      string          `json:"actor,omitempty"`
	Action     string          `json:"action,omitempty"`
	Entity     string          `json:"entity,omitempty"`
	EntityID   string          `json:"entity_id,omitempty"`
	Payload    json.RawMessage `json:"payload"`
	OccurredAt time.Time       `json:"occurred_at"`
	ArchivedAt time.Time       `json:"archived_at"`
}

ArchiveRecord represents a normalized audit event ready for batch archival.

type ArchiveSink added in v0.13.0

type ArchiveSink interface {
	WriteBatch(ctx context.Context, records []ArchiveRecord) error
	Close() error
}

ArchiveSink persists micro-batches of normalized ArchiveRecord entries.

type Batcher added in v0.13.0

type Batcher struct {
	// contains filtered or unexported fields
}

Batcher buffers ArchiveRecord entries and flushes micro-batches to ArchiveSink when BatchSize is reached or FlushInterval elapses.

func NewBatcher added in v0.13.0

func NewBatcher(sink ArchiveSink, batchSize int, flushInterval time.Duration, log *slog.Logger) *Batcher

NewBatcher constructs a Batcher with sensible defaults when parameters are <= 0.

func (*Batcher) Enqueue added in v0.13.0

func (b *Batcher) Enqueue(ctx context.Context, rec ArchiveRecord) error

Enqueue submits rec for micro-batch archival. Blocks until queued or ctx is done.

func (*Batcher) Flush added in v0.13.0

func (b *Batcher) Flush(ctx context.Context) error

Flush immediately drains queued records and writes them to the ArchiveSink.

func (*Batcher) Run added in v0.13.0

func (b *Batcher) Run(ctx context.Context) error

Run runs the micro-batch flush loop until ctx is canceled, flushing any buffered records before returning.

type BusSink added in v0.13.0

type BusSink struct {
	// contains filtered or unexported fields
}

BusSink publishes audit entries as asynchronous appkit.Event records via an EventPublisher (such as NATS JetStream or DirectBus) instead of writing inside the primary database transaction.

func NewBusSink added in v0.13.0

func NewBusSink(pub EventPublisher, opts ...BusSinkOption) *BusSink

NewBusSink constructs a BusSink backed by pub.

func (*BusSink) Record added in v0.13.0

func (s *BusSink) Record(ctx context.Context, e Entry) error

Record serializes e and publishes it to the configured EventPublisher. Unlike Recorder, BusSink does not require an active database transaction.

type BusSinkOption added in v0.13.0

type BusSinkOption func(*BusSink)

BusSinkOption configures BusSink.

func WithNow added in v0.13.0

func WithNow(now func() time.Time) BusSinkOption

WithNow overrides the clock used by BusSink when stamping OccurredAt.

func WithTopic added in v0.13.0

func WithTopic(topic string) BusSinkOption

WithTopic overrides the event topic published by BusSink (default DefaultTopic).

type Entry

type Entry struct {
	Actor    string // 操作者(用户 ID、服务名、"system")
	Action   string // 动作(如 "entry.post"、"refund.approve")
	Entity   string // 实体类型(如 "ledger_entry")
	EntityID string
	Before   any
	After    any
	Meta     any
}

Entry 是一条审计记录。Before/After/Meta 会被 JSON 序列化(可为 nil)。

type EventPublisher added in v0.13.0

type EventPublisher interface {
	Publish(ctx context.Context, evt appkit.Event) error
}

EventPublisher is the minimal publishing contract satisfied by outbox.Bus, outbox.Publisher, and external broker buses (such as natsbus.Bus).

type FileArchiveSink added in v0.13.0

type FileArchiveSink struct {
	// contains filtered or unexported fields
}

FileArchiveSink writes ArchiveRecord lines as daily NDJSON files named `audit-YYYY-MM-DD.ndjson`.

func NewFileArchiveSink added in v0.13.0

func NewFileArchiveSink(dir string) (*FileArchiveSink, error)

NewFileArchiveSink creates dir if absent and returns a FileArchiveSink.

func (*FileArchiveSink) Close added in v0.13.0

func (s *FileArchiveSink) Close() error

Close closes all open daily archive files.

func (*FileArchiveSink) WriteBatch added in v0.13.0

func (s *FileArchiveSink) WriteBatch(ctx context.Context, records []ArchiveRecord) error

WriteBatch appends records as NDJSON lines to their UTC daily files.

type PGArchiveSink added in v0.13.0

type PGArchiveSink struct {
	// contains filtered or unexported fields
}

PGArchiveSink archives audit records in daily RANGE partitions under `<Schema>.audit_archive_events` using UNNEST micro-batch inserts.

func NewPGArchiveSink added in v0.13.0

func NewPGArchiveSink(opts PGArchiveSinkOptions) (*PGArchiveSink, error)

NewPGArchiveSink constructs a PGArchiveSink.

func (*PGArchiveSink) Close added in v0.13.0

func (s *PGArchiveSink) Close() error

Close satisfies ArchiveSink (the caller owns Pool lifecycle).

func (*PGArchiveSink) EnsureSchema added in v0.13.0

func (s *PGArchiveSink) EnsureSchema(ctx context.Context) error

EnsureSchema ensures the archive schema, parent partitioned table, and daily partitions from today-2 through today+DaysAhead exist.

func (*PGArchiveSink) WriteBatch added in v0.13.0

func (s *PGArchiveSink) WriteBatch(ctx context.Context, records []ArchiveRecord) error

WriteBatch ensures partitions for each record's occurred_at date and inserts the batch idempotently with ON CONFLICT (id, occurred_at) DO NOTHING.

type PGArchiveSinkOptions added in v0.13.0

type PGArchiveSinkOptions struct {
	Pool      *pgxpool.Pool
	Schema    string // defaults to "audit_archive"
	DaysAhead int    // defaults to 14
	Now       func() time.Time
}

PGArchiveSinkOptions configures PGArchiveSink.

type Recorder

type Recorder struct {
	// contains filtered or unexported fields
}

Recorder 绑定 pool 与 schema,在 wiring 期构造后注入业务层 (业务层按"接口放消费方"依赖单方法接口,不 import 本包)。

func NewRecorder

func NewRecorder(pool *pgxpool.Pool, schema string) *Recorder

func (*Recorder) Record

func (r *Recorder) Record(ctx context.Context, e Entry) error

Record 在当前事务内写入一条审计。必须在事务内调用——审计脱离业务事务 就失去了"与事实同生共死"的意义。

type RoutedRecorder added in v0.13.0

type RoutedRecorder struct {
	// contains filtered or unexported fields
}

RoutedRecorder 是分区域(P+T)服务的事务内审计记录器:每次 Record 通过 route 从 ctx 解析分区 schema,并在同一事务内写入 {schema}.audit_log。

func NewRoutedRecorder added in v0.13.0

func NewRoutedRecorder(pool *pgxpool.Pool, route func(context.Context) (string, error)) *RoutedRecorder

NewRoutedRecorder 构造分区域审计记录器。route 为 nil 时 panic。

func (*RoutedRecorder) Record added in v0.13.0

func (r *RoutedRecorder) Record(ctx context.Context, e Entry) error

Record 解析目标分区 schema 并在当前事务内写入一条审计。

type Sink added in v0.13.0

type Sink interface {
	Record(ctx context.Context, e Entry) error
}

Sink 是审计写通道的统一抽象(事务内 PG、异步总线、或 noop)。

func NoopSink added in v0.13.0

func NoopSink() Sink

NoopSink returns a Sink that discards all entries without error. Useful for benchmarks or explicit opt-out audit modes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL