chord

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package chord ports Pi's @earendil-works/chord root export base: strict JSON copies, the shared Context (a context.Context, see chord/context), and replicated state, either authoritative and mutable (NewReplicatedState) or a publication-only view of an external revision source (AttachReplicatedStateSource).

Upstream Chord runs on one JavaScript event loop. A synchronous listener runs inline on the publishing goroutine; a listener that returns a Completion (the Go form of a Promise) suspends its own subscription until the completion settles, without blocking the producer. Publications made while a delivery runs, on the same goroutine or another, are delivered by the running loop in sequence order.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CopyJSON

func CopyJSON(value any) (any, error)

CopyJSON returns a detached copy of a strict JSON value: nil, bool, float64 (Go integer and float32 kinds are normalized), string, *delta.JsonObject, string-keyed maps, and slices. Objects are copied as *delta.JsonObject in own-key order; a Go map's keys, which have no order, follow chordjson.SortOwnKeys. Non-finite numbers, cycles, and other Go kinds return a *delta.StrictJSONError. Go has no undefined, so upstream's omitUndefinedProperties option has no counterpart.

func CopyJSONObject

func CopyJSONObject(value any) (*delta.JsonObject, error)

CopyJSONObject is CopyJSON for an object root: a *delta.JsonObject or a string-keyed map. Any other value returns nil.

func IsJsonValue

func IsJsonValue(value any) bool

IsJsonValue reports whether value is finite strict JSON with no cycles, without normalizing it.

func SetUncaughtErrorReporter

func SetUncaughtErrorReporter(report func(error)) (previous func(error))

SetUncaughtErrorReporter replaces the receiver of failures no error reporter handled: the Go form of state.ts reportErrorAsync, which rethrows in a microtask and so reaches the process's uncaught-exception handler. The default ends the process as an unhandled throw does, from its own goroutine so the reporting call is not interrupted. It returns the previous receiver and is safe to call while states deliver.

Types

type AggregateError

type AggregateError struct {
	Message string
	Errors  []error
}

AggregateError is JavaScript's AggregateError(errors, message): Error() is the message alone and the causes are reachable through Unwrap.

func NewAggregateError

func NewAggregateError(message string, failures ...error) *AggregateError

NewAggregateError builds an AggregateError over failures in order.

func (*AggregateError) Error

func (err *AggregateError) Error() string

func (*AggregateError) Unwrap

func (err *AggregateError) Unwrap() []error

type AttachedReplicatedState

type AttachedReplicatedState[T any] struct {
	// contains filtered or unexported fields
}

AttachedReplicatedState is a synchronously hydrated publication-only state backed by one source attachment.

func AttachReplicatedStateSource

func AttachReplicatedStateSource[T any](source ReplicatedStateSource[T], options ReplicatedStateSourceOptions) (*AttachedReplicatedState[T], error)

AttachReplicatedStateSource attaches a publication-only replicated state to one authoritative immutable source stream: replicatedState(source, options). An attachment that fails to activate is disposed; when that dispose also fails, both failures return as an AggregateError.

func (*AttachedReplicatedState[T]) Dispose

func (state *AttachedReplicatedState[T]) Dispose()

Dispose idempotently releases the source attachment. The last published value remains readable.

func (*AttachedReplicatedState[T]) InternalSnapshot

func (state *AttachedReplicatedState[T]) InternalSnapshot() (T, int)

InternalSnapshot atomically captures the immutable value and its publication sequence.

InternalSnapshot, SubscribeSource and SubscribePublications are the gap-free observation of an attached state. The typed durable document state (durable/documents.go) re-attaches each publication decoded as its Go type and needs every cursor, which the public subscription's 100-delivery window does not give. Upstream Chord's root export has no exact-operation subscription (a TypeScript typed state is the erased state), so a mutable state has none and its listener failures are always reported asynchronously.

func (*AttachedReplicatedState[T]) Subscribe

func (state *AttachedReplicatedState[T]) Subscribe(listener func(T, context.Context, ReplicatedStateDelivery)) func()

Subscribe implements ReplicatedState.

func (*AttachedReplicatedState[T]) SubscribeAsync

func (state *AttachedReplicatedState[T]) SubscribeAsync(listener func(T, context.Context, ReplicatedStateDelivery) Completion) func()

SubscribeAsync implements ReplicatedState.

func (*AttachedReplicatedState[T]) SubscribePublications

func (state *AttachedReplicatedState[T]) SubscribePublications(listener PublicationListener[T]) func()

SubscribePublications observes every publication with its value, before the state's subscribers. A publication whose sequence is at most InternalSnapshot's, read after subscribing, is already in that snapshot. Failures are reported through the state's error reporter.

func (*AttachedReplicatedState[T]) SubscribeSource

func (state *AttachedReplicatedState[T]) SubscribeSource(listener SourceListener) func()

SubscribeSource observes every operation batch the state publishes, before its subscribers; failures are reported through the state's error reporter.

func (*AttachedReplicatedState[T]) Value

func (state *AttachedReplicatedState[T]) Value() T

Value returns the latest published immutable value; it stays readable after Dispose.

type Completion

type Completion <-chan error

Completion is the Go form of the Promise a listener may return. A listener that has finished returns nil. A listener that is still working returns a channel that receives its failure, or nil, exactly once when it settles; its subscription delivers nothing else until then.

type DeliveryKind

type DeliveryKind string

DeliveryKind is "hydrate" or "update".

const (
	DeliveryHydrate DeliveryKind = "hydrate"
	DeliveryUpdate  DeliveryKind = "update"
)

type JsonRoot

type JsonRoot interface {
	*delta.JsonObject | []any
}

JsonRoot is the root of an authoritative replicated state: state.ts `T extends object`, an alias-free strict-JSON object or array.

type JsonValue

type JsonValue = delta.JsonValue

JsonValue is a strict JSON value: nil, bool, float64, string, []any or *delta.JsonObject.

type MutableReplicatedState

type MutableReplicatedState[T JsonRoot] struct {
	// contains filtered or unexported fields
}

MutableReplicatedState is authoritative replicated state: replicatedState(initial). It is safe for concurrent use: changes from other goroutines serialize; a change or replace from inside a change callback is rejected.

Listener failures never reach Change or Replace: each is reported to the uncaught reporter (SetUncaughtErrorReporter) after the revision has been committed, and delivery to the other subscribers continues.

func NewReplicatedState

func NewReplicatedState[T JsonRoot](initial T) *MutableReplicatedState[T]

NewReplicatedState creates authoritative state by taking immutable ownership of an alias-free strict-JSON root. The caller must not mutate initial after this call.

func (*MutableReplicatedState[T]) Change

func (state *MutableReplicatedState[T]) Change(ctx context.Context, mutate func(draft *delta.Object) error) error

Change atomically publishes one synchronous overlay mutation of an object root. Draft handles are unusable after the callback returns. Values placed through the draft are cloned by value. A mutate error or panic aborts the draft and is returned; an unchanged draft publishes nothing.

func (*MutableReplicatedState[T]) ChangeArray

func (state *MutableReplicatedState[T]) ChangeArray(ctx context.Context, mutate func(draft *delta.Array) error) error

ChangeArray is Change for an array root: mutate edits the draft of the root array.

func (*MutableReplicatedState[T]) Replace

func (state *MutableReplicatedState[T]) Replace(ctx context.Context, value T) error

Replace atomically takes immutable ownership of an alias-free strict-JSON replacement. The caller must not mutate the transferred root after this call. A deeply equal replacement publishes nothing.

func (*MutableReplicatedState[T]) Subscribe

func (state *MutableReplicatedState[T]) Subscribe(listener func(T, context.Context, ReplicatedStateDelivery)) func()

Subscribe implements ReplicatedState.

func (*MutableReplicatedState[T]) SubscribeAsync

func (state *MutableReplicatedState[T]) SubscribeAsync(listener func(T, context.Context, ReplicatedStateDelivery) Completion) func()

SubscribeAsync implements ReplicatedState.

func (*MutableReplicatedState[T]) Value

func (state *MutableReplicatedState[T]) Value() T

Value is the current immutable root.

type PublicationListener

type PublicationListener[T any] func(value T, ops []delta.Op, sequence int, ctx context.Context)

PublicationListener receives every publication of an attached state, in sequence order, with no gap: its value, the operations that produced it, its sequence and context.

type ReplicatedState

type ReplicatedState[T any] interface {
	// Value is the current immutable value. It is not frozen and may share containers with the provider; callers must
	// not mutate it. Later updates do not mutate previously returned values.
	Value() T
	// Subscribe delivers the current value as a hydration, then every later update.
	Subscribe(listener func(value T, ctx context.Context, delivery ReplicatedStateDelivery)) func()
	// SubscribeAsync is Subscribe for a listener that may still be working when it returns: the subscription waits for
	// the returned Completion before its next delivery.
	SubscribeAsync(listener func(value T, ctx context.Context, delivery ReplicatedStateDelivery) Completion) func()
}

ReplicatedState is a contract-immutable value with ordered, serialized change notifications.

Each subscription serializes callbacks, awaiting hydration before updates. Values are immutable and may share unchanged revision data. At most 100 deliveries wait behind the running callback; overflow keeps only the newest pending value, context and delivery, so update sequences may skip. Failures are reported in isolation and delivery continues. Unsubscribe discards pending work without aborting or joining a callback.

type ReplicatedStateDelivery

type ReplicatedStateDelivery struct {
	Kind     DeliveryKind
	Sequence int
}

ReplicatedStateDelivery describes one listener delivery.

type ReplicatedStateSnapshot

type ReplicatedStateSnapshot[T any] struct {
	Value  T
	Cursor int
}

ReplicatedStateSnapshot is the fixed immutable snapshot of an attachment.

type ReplicatedStateSource

type ReplicatedStateSource[T any] interface {
	Attach() (ReplicatedStateSourceAttachment[T], error)
}

ReplicatedStateSource is an authoritative immutable revision source. Attach must synchronously and atomically capture one snapshot and register the returned attachment to buffer every later committed frame, with no overlap or gap.

type ReplicatedStateSourceAttachment

type ReplicatedStateSourceAttachment[T any] interface {
	// Snapshot is captured at the atomic attachment boundary.
	Snapshot() ReplicatedStateSnapshot[T]
	// Activate installs the sole listener and synchronously drains every buffered frame in source commit order. It is
	// single use. After it begins, every new committed frame must also be delivered in order until disposal, including
	// commits made reentrantly while a prior frame is being delivered.
	Activate(listener func(frame ReplicatedStateSourceFrame[T])) error
	// Dispose stops delivery and releases source resources; idempotent.
	Dispose()
}

ReplicatedStateSourceAttachment is one source subscription.

type ReplicatedStateSourceFrame

type ReplicatedStateSourceFrame[T any] struct {
	// Cursor is monotonic; the first frame after a snapshot is snapshot cursor + 1.
	Cursor int
	// Value is the exact immutable value produced by this commit.
	Value T
	// Ops is the exact immutable batch that produced Value from the preceding revision. Chord publishes Value as is;
	// it never applies or re-diffs Ops.
	Ops     []delta.Op
	Context context.Context
}

ReplicatedStateSourceFrame is one immutable authoritative revision committed after an attachment snapshot.

type ReplicatedStateSourceOptions

type ReplicatedStateSourceOptions struct {
	// OnError receives source-contract and publication-listener failures without throwing them into the source. When it
	// is nil, or panics, the failure goes to the uncaught reporter (SetUncaughtErrorReporter).
	OnError func(error)
}

ReplicatedStateSourceOptions configures an attached state.

type SourceListener

type SourceListener func(ops []delta.Op, sequence int, ctx context.Context)

SourceListener receives every operation batch an attached state publishes, in sequence order.

type WatchEnd

type WatchEnd struct {
	Reason WatchEndReason
	Error  error
}

WatchEnd is the terminal result of one watch; Error is set only for listener_error and failed.

type WatchEndReason

type WatchEndReason string

WatchEndReason is why a watch ended.

  • WatchStopped: Stop was called.
  • WatchCancelled: the context the watch was acquired with was cancelled.
  • WatchRetired: the source was retired; its last frame was [["r", null]].
  • WatchEnded: the source closed (its owner ended or closed).
  • WatchListenerError: the listener failed with Error.
  • WatchFailed: the source failed with Error.
const (
	WatchStopped       WatchEndReason = "stopped"
	WatchCancelled     WatchEndReason = "cancelled"
	WatchRetired       WatchEndReason = "retired"
	WatchEnded         WatchEndReason = "ended"
	WatchListenerError WatchEndReason = "listener_error"
	WatchFailed        WatchEndReason = "failed"
)

type WatchHandle

type WatchHandle[T any] interface {
	// Value is the acquisition revision before Start and the latest delivered immutable revision afterward.
	Value() T
	// Start installs the sole asynchronous listener. It never invokes it inline.
	Start(listener func(ctx context.Context, value T, ops []delta.Op) error)
	// Stop idempotently stops future callbacks and returns this watch's terminal result.
	Stop() (WatchEnd, error)
	// Closed returns a channel closed when the watch terminates; an already-running callback remains caller-owned.
	Closed() <-chan struct{}
	// End returns the terminal result once Closed is closed.
	End() WatchEnd
}

WatchHandle is a serialized exact-frame observation of an immutable value with bounded pending delivery.

Directories

Path Synopsis
Package chordctx ports packages/chord/src/context/index.ts (`@earendil-works/chord/context`) onto context.Context.
Package chordctx ports packages/chord/src/context/index.ts (`@earendil-works/chord/context`) onto context.Context.
Package delta ports @earendil-works/chord/delta (packages/chord/src/delta): immutable JSON revisions, exact operation batches for ordered replicas, the operation applier, the path-interning wire codec, revision diffing, and the revision tracker.
Package delta ports @earendil-works/chord/delta (packages/chord/src/delta): immutable JSON revisions, exact operation batches for ordered replicas, the operation applier, the path-interning wire codec, revision diffing, and the revision tracker.
Package host ports the Chord host runtime of Pi's @earendil-works/chord root export (packages/chord/src): contracts, hosts, objects, cells, roots, plugins, hot reload and links.
Package host ports the Chord host runtime of Pi's @earendil-works/chord root export (packages/chord/src): contracts, hosts, objects, cells, roots, plugins, hot reload and links.
Package sqlite ports Pi's @earendil-works/chord/sqlite: the portable SQLite database facade, the atomic migration runner and schema-prefix validation that durable storage and other Chord hosts share.
Package sqlite ports Pi's @earendil-works/chord/sqlite: the portable SQLite database facade, the atomic migration runner and schema-prefix validation that durable storage and other Chord hosts share.
cloudflare
Package cloudflare adapts the SQLite storage of a Cloudflare Durable Object to the portable Chord SQLite facade.
Package cloudflare adapts the SQLite storage of a Cloudflare Durable Object to the portable Chord SQLite facade.
node
Package node adapts a native SQLite connection to the portable Chord SQLite facade.
Package node adapts a native SQLite connection to the portable Chord SQLite facade.
Package telemetrysqlite ports Pi's @earendil-works/chord/telemetry-sqlite: a portable, buffered SQLite telemetry recorder and the TelemetryStore queries over its committed rows.
Package telemetrysqlite ports Pi's @earendil-works/chord/telemetry-sqlite: a portable, buffered SQLite telemetry recorder and the TelemetryStore queries over its committed rows.

Jump to

Keyboard shortcuts

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