audit

package
v0.4.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 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 is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package audit writes an append-only JSON Lines log of a server's administrative and security-relevant events — kicks, replaced sessions, operator commands and destructive calls — with the actor and the subject of each, so support questions, anti-cheat review and accountability for admin power have a trail that survives restarts. One file per UTC day rolls at midnight; the files are text, greppable and shippable to a log store, and need no database.

Index

Examples

Constants

View Source
const DefaultQueue = 4096

DefaultQueue is a Writer's buffer size when Options.Queue is 0.

View Source
const MaxReadLimit = 1000

MaxReadLimit is the most records one Read returns.

View Source
const SchemaVersion = 1

SchemaVersion is the record schema's version, written as each line's "v".

Variables

View Source
var ErrClosed = errors.New("audit: writer closed")

ErrClosed reports a record logged with LogWait after Close.

View Source
var ErrCursor = errors.New("audit: malformed cursor")

ErrCursor reports a Query.Cursor that is not one Read returned.

Functions

This section is empty.

Types

type Options

type Options struct {
	// Dir is the directory the log lives in, one <yyyy-mm-dd>.jsonl file per
	// UTC day, created when missing. Required.
	Dir string
	// Queue is how many records buffer while the writer appends earlier
	// ones, DefaultQueue when 0. Log drops and counts a record past it
	// rather than blocking the caller.
	Queue int
	// Retain is how many days of files to keep, counting back from the day
	// of the record being written; older files are deleted as the log opens
	// a new day's file. 0 keeps every file.
	Retain int
}

Options are a Writer's settings.

type Page

type Page struct {
	// Records are the matching records, oldest file first and in each file in the order they were appended.
	Records []Record
	// Next is the Query.Cursor that reads on after the last record, or empty when the files hold no more matching records. A cursor stays valid as the log grows, since the files are only appended to.
	Next string
	// Corrupt is how many lines Read skipped because they are not records of this schema, such as a line torn by a crash or a full disk.
	Corrupt int
}

Page is what Read returns: the matching records in the order they were written, and where to continue.

func Read

func Read(dir string, q Query) (Page, error)

Read reads the records of the log in dir that match q, at most q.Limit of them, from the daily files Writer writes. It reads what has reached the files: a record still queued in a Writer is not there yet. A line that is not a record of this schema is skipped and counted in Page.Corrupt, and a last line with no newline, a record still being appended, is left for a later Read.

type Query

type Query struct {
	// From is the earliest time a record may have, inclusive; zero means no lower bound.
	From time.Time
	// To is the time records must be before, exclusive; zero means no upper bound.
	To time.Time
	// Actor, when set, keeps only the records of that actor.
	Actor string
	// Action, when set, keeps only the records of that action, or with a trailing "*" ("accounts.*") of every action that starts with what precedes it.
	Action string
	// Limit is the most records to return, from 1 to MaxReadLimit; 0 means MaxReadLimit.
	Limit int
	// Cursor continues a previous Read where it stopped: the Next it returned.
	Cursor string
}

Query selects records for Read.

type Record

type Record struct {
	// V is the schema version; Log fills in SchemaVersion when 0.
	V int `json:"v"`
	// Time is when the event happened; Log fills in the current time when
	// zero. The record lands in the file of its own UTC day, so a replayed
	// batch lands in the files of the days it happened.
	Time time.Time `json:"time"`
	// Actor is the account ID, an admin token subject, or "system" when empty.
	Actor string `json:"actor"`
	// Action is what happened, such as "peer.kick", "session.replaced" or
	// "admin.run".
	Action string `json:"action"`
	// Subject is what the action acted on: a peer, an account, a board/slot.
	Subject string `json:"subject"`
	// Data holds the action's details; omitted from the line when empty.
	Data map[string]any `json:"data,omitempty"`
}

Record is one audited event: who did what to whom, with the action's details in Data.

type Writer

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

Writer appends records to the day's file on one background goroutine, fsyncing in batches. It is safe for concurrent use.

func Open

func Open(o Options) (*Writer, error)

Open returns a Writer logging to o.Dir, creating the directory when missing.

Example

Open writes an append-only JSON Lines log, one file per UTC day; Read returns the records matching a query.

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/nsgo-dev/game/pkg/online/audit"
)

func main() {
	dir, err := os.MkdirTemp("", "audit")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)
	w, err := audit.Open(audit.Options{Dir: dir})
	if err != nil {
		fmt.Println(err)
		return
	}
	w.Log(audit.Record{
		Time:    time.Date(2026, 11, 28, 9, 15, 2, 500_000_000, time.UTC),
		Actor:   "admin:ada",
		Action:  "peer.kick",
		Subject: "peer:42",
		Data:    map[string]any{"reason": "cheating"},
	})
	if err := w.Close(); err != nil {
		fmt.Println(err)
		return
	}

	page, err := audit.Read(dir, audit.Query{Action: "peer.kick"})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(len(page.Records), page.Records[0].Actor, page.Records[0].Subject)
}
Output:
1 admin:ada peer:42

func (*Writer) Close

func (w *Writer) Close() error

Close flushes the queued records, fsyncs and closes the file, and returns the first append failure, if any. It is safe to call twice.

func (*Writer) Dropped

func (w *Writer) Dropped() uint64

Dropped reports how many records never reached the file: they arrived while the queue was full, after Close, or their append failed.

func (*Writer) Log

func (w *Writer) Log(r Record)

Log queues a record, filling in its schema version, time and actor when unset. It never blocks: a record that does not fit in the queue is dropped and counted by Dropped, as is one logged after Close.

func (*Writer) LogWait

func (w *Writer) LogWait(ctx context.Context, r Record) error

LogWait queues a record as Log does, but when the queue is full it waits for room until ctx is done rather than dropping the record. It returns ErrClosed after Close and ctx's error when ctx ends first; on an error the record is not queued and is not counted by Dropped. A record it queues can still fail to append, which Dropped and Close report.

Jump to

Keyboard shortcuts

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