persistence

package
v1.31.2 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 14 Imported by: 1 module, 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 persistence provides a versioned, append-only store for ygo CRDT documents, keyed by room name. Each committed transaction's incremental V1 update is appended as a distinct Version; the head state can be loaded, rebuilt at any past version, snapshotted by name, and pruned.

Internal format

Everything is stored in lib0 V1 (the format produced by crdt.EncodeStateAsUpdateV1 and consumed by crdt.ApplyUpdateV1). V1 is the only format ygo can merge (crdt.MergeUpdatesV1 has no V2 sibling). Callers that need V2 at the edge convert with crdt.UpdateV1ToV2 / UpdateV2ToV1.

Versions

A Version is a per-room sequence number assigned by AppendUpdate, starting at 1. Within an unbroken history versions are dense and increasing; PruneAfter resets the head to its target and subsequent appends continue at target+1, so version numbers above a pruned point are superseded and reused for the new history. Named snapshots carry their own captured version independently. ListVersions returns the single (non-cumulative) updates newest-first; MaterializeAt folds the updates up to and including a version into a head state via MergeUpdatesV1.

Crash safety

PruneAfter implements snapshot-before-delete: it first persists a rolled-back head plus a checkpoint at the target version, and only then deletes the updates newer than the target. A crash between those steps must never resurrect a "future" version on reopen — implementations enforce the checkpoint as a hard ceiling on the visible version range.

Index

Constants

This section is empty.

Variables

View Source
var ErrRoomNotFound = errors.New("persistence: room not found")

ErrRoomNotFound is returned by operations that require an existing room. Load returns a zero LoadResult (not this error) for an unknown room, matching the provider PersistenceAdapter contract where a missing room is (nil, nil).

Functions

func RunConformance

func RunConformance(t *testing.T, factory func() VersionedPersistence)

RunConformance runs the full VersionedPersistence behavioural suite against a fresh store produced by factory. External adapters import this package and call RunConformance with their own factory to verify conformance. The factory must return an empty store on each call.

Types

type CrashInjector

type CrashInjector interface {
	// SetCrashAfterCheckpoint installs a hook PruneAfter calls immediately after
	// writing its checkpoint + rolled-back head but before deleting future
	// records. Returning true makes PruneAfter return early, leaving stale
	// future records behind. Pass nil to clear.
	SetCrashAfterCheckpoint(fn func() bool)
}

CrashInjector is an optional interface a VersionedPersistence implementation may satisfy to let the conformance suite simulate a crash partway through PruneAfter (between the checkpoint write and the deletes). Implementations that cannot simulate this should not implement it; the suite skips the crash-safety subtest for them (and logs a notice).

type FilePersistence

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

FilePersistence is a directory-backed VersionedPersistence. Layout:

<root>/<roomHex>/updates/<version>.bin     one V1 update per file
<root>/<roomHex>/snapshots/<nameHex>.bin   named V1 snapshot
<root>/<roomHex>/checkpoint                target version + rolled-back head

Room and snapshot names are hex-encoded so arbitrary Unicode/space names map to safe filenames. The checkpoint file is the crash-safety pivot: PruneAfter writes it (atomically via temp+rename) before deleting future update files, and every read clamps the visible version range to the checkpoint, so a crash between the checkpoint write and the deletes can never resurrect a future version. Safe for concurrent use via a process-local mutex; it is NOT a multi-process lock.

func NewFilePersistence

func NewFilePersistence(dir string) (*FilePersistence, error)

NewFilePersistence opens (creating if necessary) a file-backed store rooted at dir.

func (*FilePersistence) AppendUpdate

func (f *FilePersistence) AppendUpdate(ctx context.Context, room string, update []byte) (Version, error)

AppendUpdate appends one V1 update.

func (*FilePersistence) CaptureSnapshot

func (f *FilePersistence) CaptureSnapshot(ctx context.Context, room, name string, state []byte) (Version, error)

CaptureSnapshot stores a named V1 snapshot.

func (*FilePersistence) Compact

func (f *FilePersistence) Compact(ctx context.Context, room string, keep int) (int, error)

Compact folds the oldest updates into the oldest retained one.

func (*FilePersistence) Delete

func (f *FilePersistence) Delete(ctx context.Context, room string) error

Delete removes all data for room.

func (*FilePersistence) GetUpdate

func (f *FilePersistence) GetUpdate(ctx context.Context, room string, v Version) ([]byte, VersionMeta, bool, error)

GetUpdate returns the single update at v.

func (*FilePersistence) ListVersions

func (f *FilePersistence) ListVersions(ctx context.Context, room string) ([]VersionMeta, error)

ListVersions returns metadata newest-first.

Cost: O(n) in the number of stored versions — it does one os.Stat per record to read the modification time. Keep histories bounded with Compact (or PruneAfter) so this stays cheap; an unbounded log makes every ListVersions (and Load/MaterializeAt) linearly slower.

func (*FilePersistence) Load

func (f *FilePersistence) Load(ctx context.Context, room string) (LoadResult, error)

Load returns the materialized head.

func (*FilePersistence) MaterializeAt

func (f *FilePersistence) MaterializeAt(ctx context.Context, room string, v Version) ([]byte, error)

MaterializeAt rebuilds the V1 head at v.

func (*FilePersistence) PruneAfter

func (f *FilePersistence) PruneAfter(ctx context.Context, room string, target Version, rolledBack []byte) error

PruneAfter implements snapshot-before-delete.

func (*FilePersistence) Reopen

Reopen returns a fresh handle over the same directory, modelling a process restart. Satisfies Reopener for the conformance crash-safety subtest.

func (*FilePersistence) RestoreSnapshot

func (f *FilePersistence) RestoreSnapshot(ctx context.Context, room, name string) ([]byte, Version, bool, error)

RestoreSnapshot returns a named snapshot.

func (*FilePersistence) SetCrashAfterCheckpoint

func (f *FilePersistence) SetCrashAfterCheckpoint(fn func() bool)

SetCrashAfterCheckpoint satisfies CrashInjector.

type LegacyAdapter

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

LegacyAdapter adapts a VersionedPersistence to the provider/websocket PersistenceAdapter contract (LoadDoc / StoreUpdate), so a versioned store can be passed to websocket.NewServerWithPersistence. It is intentionally defined without importing provider/websocket — the websocket package consumes its PersistenceAdapter dependency structurally, so matching method signatures is sufficient and avoids an import cycle.

Mapping:

  • LoadDoc(room) → Load(ctx, room).Update (materialized head)
  • StoreUpdate(room, upd) → AppendUpdate(ctx, room, upd) (drops the Version)

The provider calls StoreUpdate once per committed transaction with the incremental V1 update, which is exactly AppendUpdate's contract — so every transaction becomes one persisted Version, giving the version history for free.

func NewLegacyAdapter

func NewLegacyAdapter(store VersionedPersistence) *LegacyAdapter

NewLegacyAdapter wraps store. The provider's LoadDoc/StoreUpdate are context-free; the adapter uses context.Background() for the underlying calls. Use NewLegacyAdapterContext to supply a context (e.g. one cancelled on shutdown) so I/O-backed stores can abort in-flight work.

func NewLegacyAdapterContext

func NewLegacyAdapterContext(ctx context.Context, store VersionedPersistence) *LegacyAdapter

NewLegacyAdapterContext is like NewLegacyAdapter but threads ctx through every underlying store call.

func (*LegacyAdapter) LoadDoc

func (a *LegacyAdapter) LoadDoc(room string) ([]byte, error)

LoadDoc returns the merged V1 head state for room, or (nil, nil) when empty — matching the PersistenceAdapter contract.

func (*LegacyAdapter) Store

Store returns the wrapped VersionedPersistence so callers can reach the versioned API (ListVersions, MaterializeAt, snapshots, prune) alongside the legacy provider integration.

func (*LegacyAdapter) StoreUpdate

func (a *LegacyAdapter) StoreUpdate(room string, update []byte) error

StoreUpdate appends one incremental V1 update as a new Version. The assigned version is discarded to satisfy the PersistenceAdapter signature; callers needing the version should use the VersionedPersistence directly.

func (*LegacyAdapter) StoreUpdateContext

func (a *LegacyAdapter) StoreUpdateContext(ctx context.Context, room string, update []byte) error

StoreUpdateContext satisfies the optional PersistenceAdapterContext extension, threading the supplied ctx through to AppendUpdate so the provider can abort in-flight writes on shutdown.

type LoadResult

type LoadResult struct {
	// Update is the full lib0 V1 head state (suitable for crdt.ApplyUpdateV1).
	// Empty (nil) for a room that has no stored updates.
	Update []byte
	// Version is the highest version folded into Update, or 0 if the room is
	// empty.
	Version Version
}

LoadResult is the materialized head state of a room.

type MemoryPersistence

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

MemoryPersistence is an in-memory VersionedPersistence. It is the reference implementation and the simplest target for the conformance suite. Safe for concurrent use.

func NewMemoryPersistence

func NewMemoryPersistence() *MemoryPersistence

NewMemoryPersistence returns an empty in-memory store.

func (*MemoryPersistence) AppendUpdate

func (m *MemoryPersistence) AppendUpdate(ctx context.Context, room string, update []byte) (Version, error)

AppendUpdate appends one V1 update and returns its version.

func (*MemoryPersistence) CaptureSnapshot

func (m *MemoryPersistence) CaptureSnapshot(ctx context.Context, room, name string, state []byte) (Version, error)

CaptureSnapshot stores a named V1 snapshot.

func (*MemoryPersistence) Compact

func (m *MemoryPersistence) Compact(ctx context.Context, room string, keep int) (int, error)

Compact folds the oldest updates into the oldest retained one, keeping at most keep newest records.

func (*MemoryPersistence) Delete

func (m *MemoryPersistence) Delete(ctx context.Context, room string) error

Delete removes all data for room.

func (*MemoryPersistence) GetUpdate

func (m *MemoryPersistence) GetUpdate(ctx context.Context, room string, v Version) ([]byte, VersionMeta, bool, error)

GetUpdate returns the single update at v.

func (*MemoryPersistence) ListVersions

func (m *MemoryPersistence) ListVersions(ctx context.Context, room string) ([]VersionMeta, error)

ListVersions returns metadata newest-first.

func (*MemoryPersistence) Load

func (m *MemoryPersistence) Load(ctx context.Context, room string) (LoadResult, error)

Load returns the materialized head state.

func (*MemoryPersistence) MaterializeAt

func (m *MemoryPersistence) MaterializeAt(ctx context.Context, room string, v Version) ([]byte, error)

MaterializeAt rebuilds the V1 head at v.

func (*MemoryPersistence) PruneAfter

func (m *MemoryPersistence) PruneAfter(ctx context.Context, room string, target Version, rolledBack []byte) error

PruneAfter implements snapshot-before-delete.

Steps 1 (checkpoint write) and 2 (delete) run in a SINGLE critical section so a concurrent Delete(room) cannot slip in between them — without the single lock, step 2 would mutate a *memRoom already detached from m.rooms and silently lose the prune. The crash-injector hook is invoked while the lock is still held: the conformance suite only needs the crash to be observable AFTER the checkpoint is set and BEFORE the deletes, which is exactly this point. On a simulated crash we return with the checkpoint set but the records still present — readers clamp to the checkpoint (checkpointSet), so the lingering future records stay invisible even across a "reopen".

func (*MemoryPersistence) RestoreSnapshot

func (m *MemoryPersistence) RestoreSnapshot(ctx context.Context, room, name string) ([]byte, Version, bool, error)

RestoreSnapshot returns a named snapshot.

func (*MemoryPersistence) SetCrashAfterCheckpoint

func (m *MemoryPersistence) SetCrashAfterCheckpoint(fn func() bool)

SetCrashAfterCheckpoint satisfies CrashInjector for the conformance suite.

type Reopener

type Reopener interface {
	Reopen() (VersionedPersistence, error)
}

Reopener is an optional interface a VersionedPersistence may satisfy to model a process restart: it returns a fresh handle over the same backing store. File-backed stores reopen the directory; in-memory stores return themselves (the data already survives within the process). Used by the crash-safety subtest to assert that a crash-left store does not resurrect future versions after "reopen".

type Version

type Version uint64

Version is a per-room update sequence number assigned by AppendUpdate, starting at 1. Within an unbroken history it is dense and increasing; PruneAfter resets the head to its target, after which appends continue at target+1 (versions above a pruned point are superseded and reused for the new history). Zero is the "no version" sentinel (an empty room).

type VersionMeta

type VersionMeta struct {
	Version   Version
	UpdatedAt time.Time
}

VersionMeta describes one stored update without its payload.

type VersionedPersistence

type VersionedPersistence interface {
	// Load returns the materialized head state for room. For an unknown or
	// empty room it returns a zero LoadResult and a nil error.
	Load(ctx context.Context, room string) (LoadResult, error)

	// AppendUpdate appends one incremental V1 update to room's log and returns
	// the newly assigned Version. The update must be a valid V1 update; an
	// invalid update is rejected without advancing the version.
	AppendUpdate(ctx context.Context, room string, update []byte) (Version, error)

	// ListVersions returns metadata for every stored update in room,
	// newest-first. Each entry is a single (non-cumulative) update. Returns an
	// empty slice (not an error) for an unknown room.
	ListVersions(ctx context.Context, room string) ([]VersionMeta, error)

	// GetUpdate returns the single (non-cumulative) update stored at version v,
	// its metadata, and ok=true when present. ok=false (nil error) when the
	// room or version does not exist.
	GetUpdate(ctx context.Context, room string, v Version) (update []byte, meta VersionMeta, ok bool, err error)

	// MaterializeAt rebuilds the full V1 head state as of version v by merging
	// all updates with version <= v (crdt.MergeUpdatesV1). Returns an empty
	// slice for v == 0. Returns ErrRoomNotFound if room has no updates and
	// v > 0.
	MaterializeAt(ctx context.Context, room string, v Version) ([]byte, error)

	// CaptureSnapshot stores a named snapshot for room. state is a portable V1
	// blob (typically crdt.EncodeStateAsUpdateV1 of the materialized doc — NOT
	// a crdt.Snapshot state-vector marker). It returns the head Version the
	// snapshot is associated with (the current highest version, or 0 if empty).
	// A snapshot with the same (room, name) is overwritten.
	CaptureSnapshot(ctx context.Context, room, name string, state []byte) (Version, error)

	// RestoreSnapshot returns the V1 blob previously stored under (room, name),
	// the version it was captured at, and ok=true when present. ok=false (nil
	// error) when no such snapshot exists.
	RestoreSnapshot(ctx context.Context, room, name string) (update []byte, v Version, ok bool, err error)

	// PruneAfter removes every update with version > target, making target the
	// new head. rolledBack is the V1 head state at target (the caller supplies
	// it, typically from MaterializeAt(target)); it is persisted as a
	// crash-safe checkpoint BEFORE the deletes so that a crash mid-prune can
	// never expose a version > target on reopen. After PruneAfter, ListVersions
	// returns nothing newer than target.
	PruneAfter(ctx context.Context, room string, target Version, rolledBack []byte) error

	// Compact trims the oldest updates, keeping at most keep of the newest, by
	// folding the trimmed prefix into the oldest retained update so the
	// materialized state is preserved. Returns the number of update records
	// removed. keep <= 0 is treated as keep all (deleted = 0).
	Compact(ctx context.Context, room string, keep int) (deleted int, err error)

	// Delete removes all data for room (updates, snapshots, checkpoint).
	Delete(ctx context.Context, room string) error
}

VersionedPersistence is an append-only, versioned CRDT store keyed by room.

All methods take a context for cancellation; in-memory implementations honor only ctx cancellation at entry, while I/O-backed ones should respect it throughout. Implementations must be safe for concurrent use across rooms; per-room serialization of AppendUpdate is the implementation's responsibility.

Directories

Path Synopsis
Package sqlite provides a pure-Go (CGo-free) SQLite implementation of persistence.VersionedPersistence using modernc.org/sqlite.
Package sqlite provides a pure-Go (CGo-free) SQLite implementation of persistence.VersionedPersistence using modernc.org/sqlite.

Jump to

Keyboard shortcuts

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