auditqueue

package
v0.18.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package auditqueue is the durable auditlog.Recorder: Record schedules the audit entry as a task of a skit queue — one INSERT on the request path — and the workers of the queue write it through the audit core. Use it when an entry must survive a crash or the writes come in spikes; for the lowest latency and the order of each model use auditlog.AsyncRecorder.

Wiring

The recorder schedules on the queue, the workers drain it into the core; supervise them in a worker.Group:

q := queue.NewPG(log, db)
if err := q.EnsureSchema(ctx); err != nil {
    return err
}
rec := auditqueue.NewRecorder(q, log) // an auditlog.Recorder
auditbus.Register(bus, rec)

workers, err := auditqueue.NewWorkers(q, core, log, auditqueue.WorkerConfig{
    Metrics: reg,
})
if err != nil {
    return err
}
for _, w := range workers {
    group.Add(w)
}

The tasks go to the queue Queue under the kind Kind. Record is best-effort: a failed schedule is logged, not returned. A task whose payload does not decode goes to the dead letters of the queue; a failed write is retried with backoff.

WorkerConfig

  • Interval: the wait after a poll that found no entry (default 1s).
  • Batch: the entries claimed at once (default 100).
  • Metrics: the registry of the skit_queue_* and skit_worker_* metrics of the queue; nil turns them off.

Order

The queue keeps no order within a model: the workers of every replica claim its tasks. Core.Create retries on a version collision, so no entry is lost, but two changes of one model handled out of order are stored in that order. Run the workers on one replica, or use AsyncRecorder, when the order matters.

Example

The durable recorder: Record schedules the entry on the audit queue, and the workers of the queue write it through the core until a signal. The example needs Postgres, so go test builds it but does not run it.

package main

import (
	"context"
	"errors"
	"log/slog"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/assanoff/skit/auditlog"
	"github.com/assanoff/skit/auditlog/auditpg"
	"github.com/assanoff/skit/auditlog/auditqueue"
	"github.com/assanoff/skit/dbx/pg"
	"github.com/assanoff/skit/metrics"
	"github.com/assanoff/skit/queue"
	"github.com/assanoff/skit/worker"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	log := slog.Default()

	db, err := pg.Open(pg.Config{Host: "localhost:5432", Name: "shop", DisableTLS: true})
	if err != nil {
		log.ErrorContext(ctx, "open", "err", err)
		return
	}
	defer func() { _ = db.Close() }()

	store := auditpg.NewStore(log, db)
	q := queue.NewPG(log, db)
	if err := errors.Join(store.EnsureSchema(ctx), q.EnsureSchema(ctx)); err != nil {
		log.ErrorContext(ctx, "schema", "err", err)
		return
	}
	core := auditlog.NewCore(log, store)

	// Where the model changes: one INSERT into the queue.
	rec := auditqueue.NewRecorder(q, log)
	rec.Record(ctx, auditlog.NewAuditLog{
		ModelType: "widget", ModelID: "w-1", CreatedBy: "ann",
		Payload: map[string]string{"name": "gear"},
	})

	workers, err := auditqueue.NewWorkers(q, core, log, auditqueue.WorkerConfig{
		Metrics: metrics.New(),
	})
	if err != nil {
		log.ErrorContext(ctx, "workers", "err", err)
		return
	}
	g := worker.NewGroup(log, worker.GroupConfig{ShutdownTimeout: 10 * time.Second})
	g.Add(workers...)
	if err := g.Run(ctx); err != nil {
		log.ErrorContext(ctx, "group stopped", "err", err)
	}
}

Index

Examples

Constants

View Source
const (
	// Queue is the queue the audit entries go through.
	Queue = "auditlog"
	// Kind is the queue task kind for audit entries.
	Kind = "auditlog.record"
)

Variables

This section is empty.

Functions

func NewWorkers added in v0.14.0

func NewWorkers(q *queue.PG, core *auditlog.Core, log *slog.Logger, cfg WorkerConfig) ([]worker.Runnable, error)

NewWorkers returns the workers of Queue (queue.Workers), which record the audit entries through core. A payload that does not decode goes to the dead letters; a failed record is retried with backoff. Supervise the workers in a worker.Group. log may be nil.

It returns an error only if wiring the queue fails — which cannot happen here, as the single registration uses a constant Kind and a non-nil handler.

Types

type Enqueuer added in v0.14.0

type Enqueuer interface {
	Schedule(ctx context.Context, p queue.Params) (inserted bool, err error)
}

Enqueuer schedules a task on a queue; *queue.PG implements it.

type Recorder

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

Recorder enqueues audit entries onto a queue. It implements auditlog.Recorder.

Example

Record schedules the entry as a task of the audit queue, an auditbus.Event in its payload. A failed schedule is logged, not returned: recording is best-effort.

package main

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"os"

	"github.com/assanoff/skit/auditlog"
	"github.com/assanoff/skit/auditlog/auditqueue"
	"github.com/assanoff/skit/queue"
)

// enqueuerFunc is an auditqueue.Enqueuer of a function, in place of the queue.
type enqueuerFunc func(ctx context.Context, p queue.Params) (bool, error)

func (f enqueuerFunc) Schedule(ctx context.Context, p queue.Params) (bool, error) {
	return f(ctx, p)
}

func main() {
	log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if len(groups) == 0 && a.Key == slog.TimeKey {
				return slog.Attr{}
			}
			return a
		},
	}))
	ctx := context.Background()
	entry := auditlog.NewAuditLog{
		ModelType: "widget", ModelID: "w-1", CreatedBy: "ann",
		Payload: map[string]string{"name": "gear"},
	}

	var q enqueuerFunc = func(_ context.Context, p queue.Params) (bool, error) {
		fmt.Println(p.Queue, p.Kind, string(p.Payload))
		return true, nil
	}
	auditqueue.NewRecorder(q, log).Record(ctx, entry)

	q = func(context.Context, queue.Params) (bool, error) {
		return false, errors.New("connection refused")
	}
	auditqueue.NewRecorder(q, log).Record(ctx, entry)
}
Output:
auditlog auditlog.record {"model_type":"widget","model_id":"w-1","method":"","path":"","created_by":"ann","payload":{"name":"gear"}}
level=ERROR msg="auditqueue: enqueue failed" model_type=widget model_id=w-1 err="connection refused"

func NewRecorder

func NewRecorder(q Enqueuer, log *slog.Logger) *Recorder

NewRecorder builds a queue-backed recorder.

func (*Recorder) Record

func (r *Recorder) Record(ctx context.Context, entry auditlog.NewAuditLog)

Record enqueues entry as a task of Queue (best-effort: a failed enqueue is logged, not returned). The workers later write it through the audit core.

type WorkerConfig

type WorkerConfig struct {
	// Interval is the wait after a poll that found no entry (default 1s).
	Interval time.Duration
	// Batch caps the entries claimed at once (default 100).
	Batch int
	// Metrics is the registry for the skit_queue_* metrics of the audit queue
	// and the skit_worker_* metrics of its loops; nil — metrics off.
	Metrics prometheus.Registerer
}

WorkerConfig configures the workers of the audit queue.

Jump to

Keyboard shortcuts

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