chord

package
v0.7.0 Latest Latest
Warning

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

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

README

chord

Go port of Pi's @earendil-works/chord: the root package (strict JSON, the shared Context, replicated state, watches) with chord/context, chord/delta, and the Chord v2 packages under chord/next and chord/nextnode.

Chord v2's design documents are Pi's packages/chord/docs/next (decisions, layers, slices, store, flow control); they are not ported: the Go packages chord/next/{contracts,data,state,registries,link,host} mirror the source layout those documents describe.

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 DeliveryEntered

func DeliveryEntered()

DeliveryEntered says that the watch delivery running on the calling goroutine, if there is one, has entered: its listener went on to wait for something the host knows (a wait of the Durable Session, a park of the host loop, a call that awaits the deliveries of earlier batches), as an upstream listener's first await ends the synchronous part DeliveryScheduler.AwaitEntered orders. A wait that the host cannot see (a plain lock or channel of the listener's) does not call it, so the listener calls it first when it blocks on one: the contract of every watch listener (pig divergence (D224)).

pig divergence (D224): Go has no await point, so a listener's first suspension is observable only by a call like this one.

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 DeliveryScheduler

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

DeliveryScheduler runs the deliveries of the watches built on it, each queued as upstream's microtask is. A host owns one: the Durable Session for its watches, the native Durable core driver for its own.

func NewDeliveryScheduler

func NewDeliveryScheduler() *DeliveryScheduler

NewDeliveryScheduler returns an idle delivery scheduler.

func (*DeliveryScheduler) AwaitEntered

func (s *DeliveryScheduler) AwaitEntered(ctx context.Context) error

AwaitEntered blocks until every delivery scheduled before the call has entered: the synchronous part of its listener ran (the call returned), or the listener went on to a wait the host knows (DeliveryEntered), or the delivery ended. A call made from inside a delivery enters that delivery and does not wait for it. A listener blocked on a plain lock or channel the host cannot see has not entered until it returns. It returns the cause of ctx when ctx ends the wait.

func (*DeliveryScheduler) Busy

func (s *DeliveryScheduler) Busy() bool

Busy reports whether a delivery is queued or running: what Wait would wait for.

func (*DeliveryScheduler) Hold

func (s *DeliveryScheduler) Hold() (release func())

Hold makes the deliveries that frames advanced from now on would start wait until the returned release runs, which starts them in the order the watches were first advanced. Frames a watch is advanced with meanwhile fold into one call, as the frames of one publication fold into the single microtask upstream queues for it. Holds nest; release is called once.

func (*DeliveryScheduler) Wait

func (s *DeliveryScheduler) Wait()

Wait blocks until no scheduled delivery is queued or running.

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 NativeWatch

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

NativeWatch is the watch handle of a native source: every value in order, one call each; past 100 pending values they collapse to one, replace() or by default the newest value. A failure (Fail) drops the pending values and waits as one failed call; a value after it replaces it.

func NewNativeWatch

func NewNativeWatch[T any](value T, detach func(), report func(error), replace func() T) *NativeWatch[T]

NewNativeWatch returns a watch holding value; detach, report and the scheduler as for NewWatch. replace, when not nil, gives the value an overflow delivers; nil delivers the newest value.

func (*NativeWatch) Abort

func (watch *NativeWatch) Abort()

Abort ends the watch aborted: its acquisition context was aborted.

func (*NativeWatch[T]) Advance

func (watch *NativeWatch[T]) Advance(ctx context.Context, value T)

Advance queues value, the source's new value; it replaces a pending failure.

func (*NativeWatch) Closed

func (watch *NativeWatch) Closed() <-chan struct{}

Closed is closed when the watch terminates.

func (*NativeWatch) End

func (watch *NativeWatch) End() WatchEnd

End returns the terminal result once Closed is closed.

func (*NativeWatch) EndAfterDelivery

func (watch *NativeWatch) EndAfterDelivery()

EndAfterDelivery tells the watch that its source sends nothing more after its last frames, such as a retirement: it takes no more frames, delivers what is pending, then ends ended, after the running call returns, if one runs, and at once when nothing is pending and no call runs. Until then the watch stays attached, so EndWith, Stop, an abort and a failing listener still end it first; a watch never started keeps what is pending until one of them or Start.

func (*NativeWatch) EndWith

func (watch *NativeWatch) EndWith(end WatchEnd)

EndWith ends the watch with end at once, dropping what is pending: the source closed (WatchEnded), or failed for good (WatchFailed). A failure the source may recover from is a failed call instead (Fail). It is Pi's `end(end)`; Go's End is the accessor of the terminal result.

func (*NativeWatch[T]) Fail

func (watch *NativeWatch[T]) Fail(ctx context.Context, err error)

Fail queues a failure the source may recover from: the pending values are dropped (Value keeps the last delivered value), and the listener gets a failed call with err. ctx is the frame's context.

func (*NativeWatch) ObserveAbort

func (watch *NativeWatch) ObserveAbort(ctx context.Context)

ObserveAbort ends the watch aborted when ctx is done; it is installed once.

func (*NativeWatch[T]) On

func (watch *NativeWatch[T]) On(scheduler *DeliveryScheduler) *NativeWatch[T]

On runs the watch's deliveries on scheduler; see Watch.On.

func (*NativeWatch[T]) Start

func (watch *NativeWatch[T]) Start(listener func(ctx context.Context, call NativeWatchCall[T]) error)

Start installs the sole asynchronous listener; it never invokes it inline. It panics when the watch is started or stopped, as upstream throws.

A listener that blocks on something the host cannot see before it returns (a channel send or receive, a mutex, network I/O, a child process) holds back every wait that follows its delivery until it returns: the Harness waits, and the Session's publication of the next commit of a call, which waits for the synchronous part of each listener (pig divergence (D224): Pi's listener awaits, which ends its synchronous part, and nothing waits for it). Such a listener calls DeliveryEntered before it blocks, or does the blocking on a goroutine of its own and returns.

func (*NativeWatch) Stop

func (watch *NativeWatch) Stop() (WatchEnd, error)

Stop idempotently stops future callbacks and returns the terminal result.

func (*NativeWatch) Value

func (watch *NativeWatch) Value() T

Value is the acquisition revision before Start and the latest delivered revision afterward.

type NativeWatchCall

type NativeWatchCall[T any] struct {
	Kind  WatchCallKind
	Value T
	Error error
}

NativeWatchCall is one call of a native watch's listener: the new value, or a failure its source may recover from, as in WatchCall. Value is zero in a failed call; Error is nil in a value call.

type NativeWatchHandle

type NativeWatchHandle[T any] interface {
	// Value is the acquisition value before Start and the latest delivered value afterward (a failed call keeps it).
	Value() T
	// Start installs the sole asynchronous listener. It never invokes it inline.
	// pig divergence (D224): a listener that blocks on something the host cannot see (a channel, a lock, I/O) calls DeliveryEntered
	// first, or blocks on a goroutine of its own: the waits and the publications that follow its delivery wait until its call returns
	// or it has entered (see DeliveryEntered).
	Start(listener func(ctx context.Context, call NativeWatchCall[T]) 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
}

NativeWatchHandle is a serialized observation of an in-process value: as WatchHandle, but a value call carries no ops.

type NativeWatchable

type NativeWatchable[T any] interface {
	// Value is the current value.
	Value() T
	// Watch returns a watch holding the current value, then one frame per new value; aborting ctx ends it. It returns an
	// error where Pi's watch rejects.
	Watch(ctx context.Context) (NativeWatchHandle[T], error)
}

NativeWatchable is an in-process value that changes and can be watched (it may hold anything, errors and functions included): a change is a new value by identity, delivered without ops. It is the in-process counterpart of Watchable.

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 Watch

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

Watch is the watch handle of a JSON source. Frames that arrive before Start or while the listener runs wait in one delta.PendingOps queue; the next call gets the newest value, the folded ops of every frame since the previous call (or [["r", newest]] after the queue overflowed), Retired when any of them was a retirement, and the newest frame's context. A failure (Fail) drops the pending frames and waits as one failed call; a value after it replaces it, and the first value call after a failure is [["r", value]]. A source creates one per watch and feeds it with Advance, Fail, EndAfterDelivery, EndWith and ObserveAbort.

func NewWatch

func NewWatch[T any](value T, detach func(), report func(error)) *Watch[T]

NewWatch returns a watch holding value, as Pi's `new Watch(value, detach, report)`. detach runs once when the watch ends; report receives a listener's failure, which also ends the watch. Its deliveries run on a process-wide scheduler until On gives it the host's own.

func (*Watch) Abort

func (watch *Watch) Abort()

Abort ends the watch aborted: its acquisition context was aborted.

func (*Watch[T]) Advance

func (watch *Watch[T]) Advance(ctx context.Context, call WatchCall[T])

Advance queues the frame call. A value call's Ops turn the previous value into its Value, and Retired says the document the watch follows was retired, which the next value call reports however many frames it folds; a failed call is Fail. ctx is the frame's context.

func (*Watch) Closed

func (watch *Watch) Closed() <-chan struct{}

Closed is closed when the watch terminates.

func (*Watch) End

func (watch *Watch) End() WatchEnd

End returns the terminal result once Closed is closed.

func (*Watch) EndAfterDelivery

func (watch *Watch) EndAfterDelivery()

EndAfterDelivery tells the watch that its source sends nothing more after its last frames, such as a retirement: it takes no more frames, delivers what is pending, then ends ended, after the running call returns, if one runs, and at once when nothing is pending and no call runs. Until then the watch stays attached, so EndWith, Stop, an abort and a failing listener still end it first; a watch never started keeps what is pending until one of them or Start.

func (*Watch) EndWith

func (watch *Watch) EndWith(end WatchEnd)

EndWith ends the watch with end at once, dropping what is pending: the source closed (WatchEnded), or failed for good (WatchFailed). A failure the source may recover from is a failed call instead (Fail). It is Pi's `end(end)`; Go's End is the accessor of the terminal result.

func (*Watch[T]) Fail

func (watch *Watch[T]) Fail(ctx context.Context, err error)

Fail queues a failure the source may recover from: the pending frames are dropped (Value keeps the last delivered value), the listener gets a failed call with err, and the next value arrives as [["r", value]]. ctx is the frame's context.

func (*Watch) ObserveAbort

func (watch *Watch) ObserveAbort(ctx context.Context)

ObserveAbort ends the watch aborted when ctx is done; it is installed once.

func (*Watch[T]) On

func (watch *Watch[T]) On(scheduler *DeliveryScheduler) *Watch[T]

On runs the watch's deliveries on scheduler, the Go counterpart of the host's microtask queue. It is called once, before the watch is advanced or started, and returns the watch.

func (*Watch[T]) Start

func (watch *Watch[T]) Start(listener func(ctx context.Context, call WatchCall[T]) error)

Start installs the sole asynchronous listener; it never invokes it inline. It panics when the watch is started or stopped, as upstream throws.

A listener that blocks on something the host cannot see before it returns (a channel send or receive, a mutex, network I/O, a child process) holds back every wait that follows its delivery until it returns: the Harness waits, and the Session's publication of the next commit of a call, which waits for the synchronous part of each listener (pig divergence (D224): Pi's listener awaits, which ends its synchronous part, and nothing waits for it). Such a listener calls DeliveryEntered before it blocks, or does the blocking on a goroutine of its own and returns.

func (*Watch) Stop

func (watch *Watch) Stop() (WatchEnd, error)

Stop idempotently stops future callbacks and returns the terminal result.

func (*Watch) Value

func (watch *Watch) Value() T

Value is the acquisition revision before Start and the latest delivered revision afterward.

type WatchCall

type WatchCall[T any] struct {
	Kind    WatchCallKind
	Value   T
	Ops     []delta.Op
	Retired bool
	Error   error
}

WatchCall is one call of a JSON watch's listener, and one frame a source hands its Watch, tagged by Kind:

  • WatchCallValue: the newest Value, the Ops that turn the previous value into it, and whether the document the watch follows was retired since the previous value call. A retirement does not end the watch: Value is then what the address shows after it (the source decides; a Durable document keeps the last value the watch was given, with no ops), and a document created there later arrives as [["r", value]], possibly in the same call.
  • WatchCallFailed: the source cannot compute its value now, with Error; the watch stays open, and the next value arrives as [["r", value]]. WatchHandle.Value keeps the last value.

Plain data: the frame's context is the listener's first argument, never part of the call. Value, Ops and Retired are zero in a failed call; Error is nil in a value call.

type WatchCallKind

type WatchCallKind string

WatchCallKind tags a WatchCall and a NativeWatchCall.

const (
	// WatchCallValue is a call with the newest value.
	WatchCallValue WatchCallKind = "value"
	// WatchCallFailed is a call with the error of a failure its source may recover from.
	WatchCallFailed WatchCallKind = "failed"
)

type WatchEnd

type WatchEnd struct {
	Kind  WatchEndKind
	Error error
}

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

type WatchEndKind

type WatchEndKind string

WatchEndKind is why a watch ended. A watch ends only for good; a failure its source recovers from is a failed WatchCall and the watch stays open.

  • WatchStopped: Stop was called.
  • WatchAborted: the context the watch was acquired with was aborted.
  • WatchEnded: the source closed (its owner ended or closed).
  • WatchListenerError: the listener failed with Error.
  • WatchFailed: the source failed for good with Error.
const (
	WatchStopped       WatchEndKind = "stopped"
	WatchAborted       WatchEndKind = "aborted"
	WatchEnded         WatchEndKind = "ended"
	WatchListenerError WatchEndKind = "listener_error"
	WatchFailed        WatchEndKind = "failed"
)

type WatchHandle

type WatchHandle[T any] interface {
	// Value is the acquisition revision before Start and the latest delivered immutable revision afterward (a failed call keeps it).
	Value() T
	// Start installs the sole asynchronous listener. It never invokes it inline.
	// pig divergence (D224): a listener that blocks on something the host cannot see (a channel, a lock, I/O) calls DeliveryEntered
	// first, or blocks on a goroutine of its own: the waits and the publications that follow its delivery wait until its call returns
	// or it has entered (see DeliveryEntered).
	Start(listener func(ctx context.Context, call WatchCall[T]) 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.

type Watchable

type Watchable[T any] interface {
	// Value is the current value.
	Value() T
	// Watch returns a watch holding the current value, then one frame per change; aborting ctx ends it.
	Watch(ctx context.Context) (WatchHandle[T], error)
}

Watchable is a value that changes and can be watched: documents, derives, members of references. Values are immutable by convention (JSON for state); each watch starts at the current value and then gets one frame per change. Watch returns an error where Pi's watch rejects.

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.
internal
parking
Package parking is the hand-off of a method handler's first suspension (Chord v2 host, section "handler authoring").
Package parking is the hand-off of a method handler's first suspension (Chord v2 host, section "handler authoring").
next
contracts
Package contracts ports packages/chord/src/next/contracts: the contracts of Chord's layers.
Package contracts ports packages/chord/src/next/contracts: the contracts of Chord's layers.
data
Package data ports packages/chord/src/next/data: Chord's errors and plugin errors, principals, per-call checks of params and arguments, and how a plugin's open reports a broken configuration.
Package data ports packages/chord/src/next/data: Chord's errors and plugin errors, principals, per-call checks of params and arguments, and how a plugin's open reports a broken configuration.
documents
Package documents ports packages/chord/src/next/documents: definitions, the handles an object's attempts get, the object's documents (in memory, or persisted in the host's store), keyed watches and `at(key)`, retirement, and transactions over documents, tables and job runs.
Package documents ports packages/chord/src/next/documents: definitions, the handles an object's attempts get, the object's documents (in memory, or persisted in the host's store), keyed watches and `at(key)`, retirement, and transactions over documents, tables and job runs.
host
Package host ports packages/chord/src/next/host, jobs and remote: the host of Chord v2, its objects and references, the jobs they run and the links they hold.
Package host ports packages/chord/src/next/host, jobs and remote: the host of Chord v2, its objects and references, the jobs they run and the links they hold.
internal/nexttest
Package nexttest ports the helpers of packages/chord/test/next/support.ts that the Chord v2 foundation tests share: counting contexts, metered contexts and watch collectors.
Package nexttest ports the helpers of packages/chord/test/next/support.ts that the Chord v2 foundation tests share: counting contexts, metered contexts and watch collectors.
internal/nexttest/contractstest
Package contractstest holds the test helpers of packages/chord/test/next/support.ts that need the contracts package: kept apart from nexttest so the helpers that do not need it (counters, collectors) build without it.
Package contractstest holds the test helpers of packages/chord/test/next/support.ts that need the contracts package: kept apart from nexttest so the helpers that do not need it (counters, collectors) build without it.
link
Package link ports packages/chord/src/next/link: Chord v2's links for its layers (a host's end of a link with its handshake, codec, checks, heartbeat and in-order handling), the message types, parts with their limits and compression, errors in messages, and the in-memory, IPC and WebSocket links.
Package link ports packages/chord/src/next/link: Chord v2's links for its layers (a host's end of a link with its handshake, codec, checks, heartbeat and in-order handling), the message types, parts with their limits and compression, errors in messages, and the in-memory, IPC and WebSocket links.
registries
Package registries ports packages/chord/src/next/registries: an extension point between plugins (design §17).
Package registries ports packages/chord/src/next/registries: an extension point between plugins (design §17).
state
Package state ports packages/chord/src/next/state: the reactive state of Chord v2.
Package state ports packages/chord/src/next/state: the reactive state of Chord v2.
Package nextnode ports packages/chord/src/next-node: compression for Chord v2 hosts (§22, slice 4b), the synchronous compressor `createHost({ compression })` takes.
Package nextnode ports packages/chord/src/next-node: compression for Chord v2 hosts (§22, slice 4b), the synchronous compressor `createHost({ compression })` takes.
http
Package http ports packages/chord/src/next-node/http (Chord v2's HTTP component, slice 10 §2): a Web-standard `fetch` handler built from the routes, wraps and sockets plugins contribute to the registry `Http`, with the security baseline on by default, Chord's own listener, an upgrade adapter and the request conversion for apps that mount it.
Package http ports packages/chord/src/next-node/http (Chord v2's HTTP component, slice 10 §2): a Web-standard `fetch` handler built from the routes, wraps and sockets plugins contribute to the registry `Http`, with the security baseline on by default, Chord's own listener, an upgrade adapter and the request conversion for apps that mount it.
plugins
Package plugins ports packages/chord/src/next-node/plugins: the plugins component of Chord v2 (slice 7c, design §21 "Loading plugins and the reload loop"), the plugin directories found, each facet built, evaluated, loaded and reloaded per plugin, watched and rolled out.
Package plugins ports packages/chord/src/next-node/plugins: the plugins component of Chord v2 (slice 7c, design §21 "Loading plugins and the reload loop"), the plugin directories found, each facet built, evaluated, loaded and reloaded per plugin, watched and rolled out.
workers
Package workers ports packages/chord/src/next-node/workers: Chord v2's workers component (slice 10 §3, §4), a worker process per address of a host kind, started on demand, stopped when idle, never restarted by itself, its plugins shipped from the server; `WorkerMain` is the worker's side.
Package workers ports packages/chord/src/next-node/workers: Chord v2's workers component (slice 10 §3, §4), a worker process per address of a host kind, started on demand, stopped when idle, never restarted by itself, its plugins shipped from the server; `WorkerMain` is the worker's side.
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.
sqlitetest
Package sqlitetest holds the helpers the Chord SQLite driver tests share.
Package sqlitetest holds the helpers the Chord SQLite driver tests share.
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