clientstate

package
v0.3.0-beta.20 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package clientstate persists opaque, workspace-scoped client state and publishes committed changes in workspace sequence order.

Index

Constants

View Source
const (
	// StateDirName is the Compozy-home directory that owns client-state data.
	StateDirName = "state"
	// DatabaseName is the client-state bbolt filename.
	DatabaseName = "clientstate.db"
	// SubscriptionBufferSize is the fixed per-subscription event capacity.
	SubscriptionBufferSize = 256
)

Variables

View Source
var (
	// ErrNotFound reports that no live value exists for a key.
	ErrNotFound = errors.New("client state not found")
	// ErrWorkspaceNotFound reports an unknown, deleting, or stale workspace generation.
	ErrWorkspaceNotFound = errors.New("client state workspace not found")
	// ErrRevConflict reports a failed compare-and-swap revision.
	ErrRevConflict = errors.New("client state revision conflict")
	// ErrValueTooLarge reports a payload beyond the configured byte limit.
	ErrValueTooLarge = errors.New("client state value too large")
	// ErrKeyQuota reports that a new retained key would exceed workspace quota.
	ErrKeyQuota = errors.New("client state key quota exceeded")
	// ErrInvalidDomain reports a malformed internal domain.
	ErrInvalidDomain = errors.New("client state invalid domain")
	// ErrInvalidKey reports a malformed key.
	ErrInvalidKey = errors.New("client state invalid key")
	// ErrInvalidValue reports malformed JSON or a non-object JSON payload.
	ErrInvalidValue = errors.New("client state invalid value")
	// ErrEmptyApply reports an Apply request with no operations.
	ErrEmptyApply = errors.New("client state apply is empty")
	// ErrSlowConsumer reports subscription eviction after its queue fills.
	ErrSlowConsumer = errors.New("client state slow consumer")
	// ErrClosed reports an operation attempted after service shutdown.
	ErrClosed = errors.New("client state service closed")
	// ErrStoreFormatTooNew reports a durable store written by a newer binary.
	ErrStoreFormatTooNew = errors.New("client state store format is newer than supported")
)

Functions

func DatabasePath

func DatabasePath(homeDir string) string

DatabasePath returns the canonical client-state path for an Compozy home.

Types

type ApplyOptions

type ApplyOptions struct {
	Origin string
}

ApplyOptions carries mutation metadata that is not persisted in the value.

type Engine

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

Engine is the bbolt-backed client-state service.

func Open

func Open(
	ctx context.Context,
	path string,
	resolver WorkspaceResolver,
	limits Limits,
	options ...Option,
) (*Engine, error)

Open constructs a client-state engine over path.

func (*Engine) Apply

func (e *Engine) Apply(
	ctx context.Context,
	ws WorkspaceID,
	domain string,
	ops []Op,
	opts ApplyOptions,
) (entries []Entry, err error)

Apply atomically commits and publishes a mutation batch.

func (*Engine) Close

func (e *Engine) Close() error

Close stops sequencers and subscriptions before closing bbolt.

func (*Engine) ConnectionClosed

func (e *Engine) ConnectionClosed()

ConnectionClosed records one transport connection closure.

func (*Engine) ConnectionOpened

func (e *Engine) ConnectionOpened()

ConnectionOpened records one transport connection.

func (*Engine) Get

func (e *Engine) Get(
	ctx context.Context,
	ws WorkspaceID,
	domain string,
	key string,
) (Entry, error)

Get returns one live entry.

func (*Engine) List

func (e *Engine) List(
	ctx context.Context,
	ws WorkspaceID,
	domain string,
) ([]Entry, error)

List returns all live entries in one domain sorted by key.

func (*Engine) Metrics

func (e *Engine) Metrics() MetricsSnapshot

Metrics returns a consistent low-cardinality runtime snapshot.

func (*Engine) PrepareWorkspacePurge

func (e *Engine) PrepareWorkspacePurge(
	ctx context.Context,
	ws WorkspaceID,
) (WorkspacePurgePreparation, error)

PrepareWorkspacePurge closes subscriptions and removes the live workspace bucket while retaining a rollback copy until the owning row deletion commits.

func (*Engine) PurgeWorkspace

func (e *Engine) PurgeWorkspace(ctx context.Context, ws WorkspaceID) error

PurgeWorkspace closes workspace subscriptions and deletes its entire bucket.

func (*Engine) RecordOutboundQueueDepth

func (e *Engine) RecordOutboundQueueDepth(depth int)

RecordOutboundQueueDepth observes one WebSocket writer-queue sample.

func (*Engine) RecordReconnect

func (e *Engine) RecordReconnect()

RecordReconnect records one transport reconnect.

func (*Engine) RecordSlowConsumerEviction

func (e *Engine) RecordSlowConsumerEviction()

RecordSlowConsumerEviction records a transport-level writer-queue eviction.

func (*Engine) Watch

func (e *Engine) Watch(
	ctx context.Context,
	ws WorkspaceID,
	domains []string,
) (Subscription, error)

Watch returns a snapshot and a gap-free stream of later workspace commits.

type Entry

type Entry struct {
	Domain    string
	Key       string
	Value     []byte
	Rev       uint64
	Seq       uint64
	Deleted   bool
	UpdatedAt time.Time
}

Entry is the durable envelope for one client-state value.

type Event

type Event struct {
	Workspace WorkspaceID
	Entry     Entry
	Origin    string
}

Event is one committed entry published to workspace subscribers.

type Limits

type Limits struct {
	MaxValueBytes       int
	MaxKeysPerWorkspace int
}

Limits bounds retained data in the client-state store.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the production client-state limits.

type MetricsSnapshot

type MetricsSnapshot struct {
	ActiveConnections     int64
	ActiveSubscriptions   int64
	OutboundQueueDepthMax int
	OutboundQueueDepthP95 int
	SlowConsumerEvictions uint64
	Reconnects            uint64
	Snapshots             uint64
	SnapshotEntries       uint64
	SnapshotBytes         uint64
	SnapshotDurationP95   time.Duration
	Applies               uint64
	ApplyErrors           uint64
	ApplyLatencyP95       time.Duration
	RevConflicts          uint64
	PurgeFailures         uint64
}

MetricsSnapshot is a low-cardinality runtime view of client-state health.

type Op

type Op struct {
	Kind  OpKind
	Key   string
	Value []byte
	IfRev uint64
}

Op is one mutation in an Apply batch.

type OpKind

type OpKind uint8

OpKind identifies one mutation in an atomic Apply batch.

const (
	// OpPut creates or replaces a live value.
	OpPut OpKind = iota + 1
	// OpDelete writes a tombstone for an existing live value.
	OpDelete
)

type Option

type Option func(*engineOptions) error

Option customizes Engine construction.

func WithClock

func WithClock(now func() time.Time) Option

WithClock replaces the wall clock for deterministic tests.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger configures structured client-state logging.

func WithOpenTimeout

func WithOpenTimeout(timeout time.Duration) Option

WithOpenTimeout bounds waiting for another process to release the bbolt file.

type Service

type Service interface {
	Get(ctx context.Context, ws WorkspaceID, domain, key string) (Entry, error)
	List(ctx context.Context, ws WorkspaceID, domain string) ([]Entry, error)
	Apply(
		ctx context.Context,
		ws WorkspaceID,
		domain string,
		ops []Op,
		opts ApplyOptions,
	) ([]Entry, error)
	Watch(ctx context.Context, ws WorkspaceID, domains []string) (Subscription, error)
	PurgeWorkspace(ctx context.Context, ws WorkspaceID) error
}

Service is the client-state runtime contract.

type StoreFormatTooNewError

type StoreFormatTooNewError struct {
	Version          uint32
	SupportedVersion uint32
}

StoreFormatTooNewError records the incompatible durable and supported versions.

func (*StoreFormatTooNewError) Error

func (e *StoreFormatTooNewError) Error() string

func (*StoreFormatTooNewError) Unwrap

func (e *StoreFormatTooNewError) Unwrap() error

type Subscription

type Subscription interface {
	AsOfSeq() uint64
	Snapshot() []Entry
	Events() <-chan Event
	Err() error
	Close() error
}

Subscription composes a snapshot fence with later committed events.

type WorkspaceGeneration

type WorkspaceGeneration string

WorkspaceGeneration uniquely identifies one registration of a workspace ID.

type WorkspaceID

type WorkspaceID string

WorkspaceID identifies the workspace that owns a state partition.

type WorkspacePurgePreparation

type WorkspacePurgePreparation interface {
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
}

WorkspacePurgePreparation is a reversible physical purge staged before the owning workspace row is deleted.

type WorkspaceResolver

type WorkspaceResolver interface {
	ResolveWorkspace(ctx context.Context, ws WorkspaceID) (WorkspaceGeneration, error)
	ResolveWorkspaceForPurge(ctx context.Context, ws WorkspaceID) (WorkspaceGeneration, error)
}

WorkspaceResolver gates access to registered workspaces.

ResolveWorkspace rejects unknown or deleting workspaces. Purge resolution succeeds only while the matching registration is held behind its deletion gate. Implementations must never reuse a generation for a recreated ID.

Jump to

Keyboard shortcuts

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