host

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: 42 Imported by: 0

Documentation

Overview

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. The shared base (Context, JSON, replicated state) is the parent package chord, which the durable core links without the runtime.

Index

Constants

View Source
const (
	MemberMethod = "method"
	MemberState  = "state"
	MemberOpaque = "opaque"
)

Member kinds of a MemberDescription.

View Source
const (
	KindHost   = "host"
	KindClient = "client"
)

Host kinds.

View Source
const (
	HostManagerStopped  = "stopped"
	HostManagerStarting = "starting"
	HostManagerRunning  = "running"
	HostManagerStopping = "stopping"
)

Host manager statuses: manager.ts HostManager.status.

View Source
const (
	// ConflictError rejects two objects registering one key.
	ConflictError = "error"
	// ConflictLast keeps the later registration.
	ConflictLast = "last"
)

Registry conflict policies (registry.ts:5 `conflict: "error" | "last"`).

View Source
const LocalVariant = ""

LocalVariant is the one unnamed variant of a local contract.

View Source
const PackThreshold = 64 * 1024

PackThreshold is link.ts PACK_THRESHOLD: payloads whose JSON is longer than this many characters (UTF-16 code units) are deflated.

View Source
const ProtocolVersion = 4

ProtocolVersion is the link protocol version, announced in hello. Peers of different versions do not talk: the side that notices closes the link with reason `protocol-version <its version>`, so the other side learns it too (LinkOptions.OnProtocolMismatch).

Variables

This section is empty.

Functions

func AcceptWebSockets

func AcceptWebSockets[Request any](server WebSocketServerLike[Request], host *HostImpl, options WebSocketAcceptOptions[Request])

AcceptWebSockets accepts every connection of server on host as a client link stamped with the authenticated principal (Pi websocket.ts:17-34). The socket is wrapped at once, so frames sent while authenticating are queued, not lost; a refused client's link closes with "unauthorized" and a failed authentication's with "authentication failed".

func CanonicalIdentity

func CanonicalIdentity(schema Schema, value any) string

CanonicalIdentity is schema.ts canonicalIdentity: the canonical JSON of a normalized value with fields equal to their schema default omitted.

func CanonicalJSON

func CanonicalJSON(value any) string

CanonicalJSON is schema.ts canonicalJson: sorted object keys, undefined members dropped.

func Cleaned

func Cleaned(schema Schema, value any) (any, error)

Cleaned is schema.ts cleaned: a copy of value with only what schema knows, unknown object fields dropped, recursively (what TypeBox's `Clean` did).

func Coverage

func Coverage(provider, consumer Description) string

Coverage is contract.ts coverage: why provider does not cover consumer, or "" when it does.

func DeepEqual

func DeepEqual(a, b any) bool

DeepEqual is schema.ts deepEqual over canonical JSON.

func EncodeFrame

func EncodeFrame(frame Frame) ([]byte, error)

EncodeFrame is JSON.stringify(frame).

func Fits

func Fits(subSchema, supSchema any) bool

Fits is schema.ts fits: conservative structural subtyping. It is true only if every value valid under sub is valid under sup, where object fields missing from sub but optional in sup count as fine. A provider schema using a keyword this function does not model, or an additionalProperties schema, only fits an identical consumer schema.

func Hash64

func Hash64(text string) string

Hash64 is schema.ts hash64: a non-cryptographic 64-bit hash (two FNV-1a lanes) over UTF-16 code units, as 16 hex digits.

func InflateMessage

func InflateMessage(data []byte) (string, error)

InflateMessage is link.ts inflateMessage: the text frame of a binary (packed) WebSocket message, inflated, for a transport that relays text frames only (the TUI launcher feeding its sandbox).

func IsChordError

func IsChordError(err error, code ...ChordErrorCode) bool

IsChordError is errors.ts isChordError(error, code?): whether err is a ChordError, of code when one is given. As upstream's instanceof, it does not look through a wrapper (an AggregateError, a %w wrap).

func IsFrame

func IsFrame(value any) bool

IsFrame is wire.ts isFrame: whether value (decoded JSON) passes structural validation; anything else is a protocol violation.

func IsSource

func IsSource(value any) bool

IsSource is cell.ts isSource: whether value is an object cell or derivation.

func IsValid

func IsValid(schema, value any) (bool, error)

IsValid is schema.ts isValid: whether value matches schema.

func MemoryLinkPair

func MemoryLinkPair() (*MemoryLink, *MemoryLink)

MemoryLinkPair is two connected in-memory links (tests).

func Normalize

func Normalize(schema Schema, value any, what string) (any, error)

Normalize is schema.ts normalize: it applies defaults, strips unknown fields and validates, returning a fresh value. A nil value is normalized as an empty object (value ?? {}).

func OrderedJSON

func OrderedJSON(value any) string

OrderedJSON is canonicalJson except that the members of an ordered object (*chordjson.Object) keep the order they were declared in, as JSON.stringify writes a schema; Go maps are written sorted, as CanonicalJSON writes them.

func ProcessLock

func ProcessLock(name string) (func() error, error)

ProcessLock is manager.ts processLock(name): a process lock owned by the kernel for the holder's lifetime. An abstract socket (Linux, Android) or a named pipe (Windows) vanishes with its process, so there is no stale state to take over and no race between two would-be owners. Other platforms need a socket file, removed on release; a leftover one nobody accepts on is taken over. The socket file lives in the temporary directory, or in the private per-user directory /tmp/chord2-<uid> when that path does not fit in sun_path. The child acquires it (before opening storage), so the lock follows the process that owns the data. A held lock fails with unavailable/locked. The returned function releases it.

Pi also removes the socket file at process exit; Go has no exit hook, so a file left by a process that exited without releasing is a stale lock the next holder takes over.

Types

type AbortFrame

type AbortFrame struct{ Reload int }

func (AbortFrame) T

func (AbortFrame) T() string

type AcceptOptions

type AcceptOptions struct {
	LinkOptions
	// Principal is the principal of whatever connects, from the app's authenticator. Every request on the link acts
	// as it.
	Principal Principal
	// Kind is what the peer is, decided here and never by its hello: "client" (default when empty; a browser: no
	// roots, no code versions, not a reload participant, not addressable) or "host" (a child host; needs Name).
	Kind string
	// Name is a child host's name: its hello must match, and it is reachable at this name.
	Name *string
	// Restamp is called on invalidatePrincipal: a new principal (true) keeps the link, false closes it. Nil closes it.
	Restamp func(principal Principal) (Principal, bool)
	// MaxCalls is the calls the peer may have in progress on this link (nil: no limit). Further ones never run: they
	// are answered at once with unavailable (reason too_many_calls), and the link stays open.
	MaxCalls *int
}

AcceptOptions are the options of accepting a link.

type Accepts

type Accepts map[int]Adapter

Accepts are the adapters a provider declares, by consumer contract version.

type AckFrame

type AckFrame struct{ N int }

AckFrame counts every frame received so far except ack frames, from the link's start, once processed.

func (AckFrame) T

func (AckFrame) T() string

type Adapter

type Adapter func(current Implementation) Implementation

Adapter maps the provider's current implementation to the view a consumer of an older contract version expects.

func Bind

func Bind(provider *Contract, accepts Accepts, consumer *Contract) (Adapter, error)

Bind is contract.ts bind: how a consumer token binds to a provider, directly (nil adapter) or through an accepts adapter. It fails with contract_mismatch.

type AggregateError

type AggregateError struct {
	Message string
	Errors  []error
}

AggregateError is JavaScript's AggregateError(errors, message), which runAll throws when several steps failed: Error() is the message alone, and the errors are reachable through Unwrap. Its shape is chord2-port S1's chord.AggregateError (chord/state.go), so the two merge into one when S1 lands.

func (*AggregateError) Error

func (err *AggregateError) Error() string

func (*AggregateError) Unwrap

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

type ByeFrame

type ByeFrame struct {
	// Reason is nil when absent.
	Reason *string
}

func (ByeFrame) T

func (ByeFrame) T() string

type CallFrame

type CallFrame struct {
	ID     int
	Hold   int
	Member string
	Args   any
	// HasArgs is false when the call carries no args (a method without arguments): JSON has no undefined.
	HasArgs bool
	// Root is nil when the receiving host starts a root (browsers never carry roots).
	Root *RootRef
}

func (CallFrame) T

func (CallFrame) T() string

type CancelFrame

type CancelFrame struct{ ID int }

func (CancelFrame) T

func (CancelFrame) T() string

type Cell

type Cell[T any] struct {
	Source[T]
	// Schema is replaced at a reload commit that changes the schema (state-version bump).
	Schema Schema
	// contains filtered or unexported fields
}

Cell is cell.ts Cell: a state cell holding any JSON value, validated against its schema at creation and (dev mode) on writes.

func NewCell

func NewCell[T any](key string, schema Schema, initial T, guard WriteGuard, options SourceOptions) (*Cell[T], error)

NewCell is cell.ts new Cell(key, schema, initial, guard, options). initial is always validated against schema; ownership moves to the cell.

func NewCellAwaitingInit

func NewCellAwaitingInit[T any](key string, schema Schema, guard WriteGuard, options SourceOptions) (*Cell[T], error)

NewCellAwaitingInit is cell.ts new Cell(key, schema, undefined, guard, options): a cell without a value until Initialize (a cell declared with init, filled before its object goes live).

func (*Cell[T]) Change

func (cell *Cell[T]) Change(ctx Ctx, fn func(draft any)) error

Change is cell.ts change(ctx, fn) with a draft-mutating fn (Pi's void-returning overload): only mutated paths are published. draft is the value's draft reference (*delta.Object or *delta.Array) for a container, or the value itself for a primitive. The draft is unusable after fn returns.

func (*Cell[T]) ChangeValue

func (cell *Cell[T]) ChangeValue(ctx Ctx, fn func(draft any) T) error

ChangeValue is cell.ts change(ctx, fn) with a value-returning fn (`n => n + 1`). The returned value replaces the cell's value and is always validated against the schema, unless fn returns the draft itself.

func (*Cell[T]) Initialize

func (cell *Cell[T]) Initialize(value T) error

Initialize sets the first value of a cell declared with init (validated; ownership moves to the cell). It publishes nothing.

func (*Cell[T]) Replace

func (cell *Cell[T]) Replace(ctx Ctx, value T, options CellReplaceOptions) error

Replace is cell.ts replace(ctx, value, options): it replaces the whole value. Ownership of value moves to the cell: never mutate it afterwards.

Subscribers get a structural diff (delta.DiffRevisions) when Diff is true, or by default when the new value shares containers with the old one (a new immutable revision of the same state, e.g. mirrored from another store); otherwise a single r op. The resulting value is the same either way; only the ops differ.

func (*Cell[T]) Reset

func (cell *Cell[T]) Reset(value T, schema Schema) error

Reset is cell.ts reset(value, schema): it installs a migrated value and its schema (reload commit). The caller validated the value and the derivations over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset.

func (*Cell[T]) Value

func (cell *Cell[T]) Value() T

Value is the current value. A cell declared with init throws (panics with) not_ready until it is initialized.

type CellReplaceOptions

type CellReplaceOptions struct {
	// Diff selects a structural diff (true) or a single r op (false); nil diffs when the new value shares containers
	// with the old one.
	Diff *bool
}

CellReplaceOptions is the options parameter of cell.ts Cell.replace.

type ChildControlChannel

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

ChildControlChannel is the object manager.ts childControl returns: the child side of the control channel.

func ChildControl

func ChildControl(channel IpcChannel) *ChildControlChannel

ChildControl is manager.ts childControl(channel) (call in the child's entry). Pi's default channel is the process's own IPC channel: ProcessChannel.

func (*ChildControlChannel) Fatal

func (control *ChildControlChannel) Fatal(err error)

Fatal reports a failed start: the error's message, and a ChordError's reason.

func (*ChildControlChannel) Init

func (control *ChildControlChannel) Init(ctx context.Context) (any, error)

Init waits for the manager's init value (manager.ts childControl().init); ctx ends the wait.

func (*ChildControlChannel) Lock

func (control *ChildControlChannel) Lock() error

Lock acquires the manager's lock (if one was configured) as a kernel lock held for this process's lifetime. Call it before opening storage. It fails with unavailable/locked, also reported to the manager as a fatal start error.

func (*ChildControlChannel) OnShutdown

func (control *ChildControlChannel) OnShutdown(handler func())

OnShutdown adds a handler the manager's shutdown request starts.

func (*ChildControlChannel) Ready

func (control *ChildControlChannel) Ready()

Ready reports the child ready.

func (*ChildControlChannel) Report

func (control *ChildControlChannel) Report(status ChildStatus)

Report sends a status report.

type ChildReloads

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

ChildReloads is the child side: prepare and vote, then wait for the server's commit or abort. An abort or a lost parent link can arrive at any point: while loading modules, while preparing (pending opens close themselves when they complete), or after the vote. The operation is unwound once its pending work settles, and the reload slot is freed. Its methods run on the loop.

type ChildStatus

type ChildStatus struct {
	ActiveCalls  *float64
	Viewers      *float64
	DurableTasks *float64
}

ChildStatus is the status report of manager.ts childControl().report (nil = absent).

type ChordError

type ChordError struct {
	// Name is the error class name, "ChordError" (errors.ts:38 this.name).
	Name string
	Code ChordErrorCode
	// Reason is empty when the error has none.
	Reason    string
	Retryable bool
	Details   any
	// Message is the full message: "<code>[/<reason>]: <message>".
	Message string
	Cause   error
}

ChordError is a Chord failure: a code, an optional finer reason (for logs and tests: invalid + args, result, state, input, implementation, duplicate, cycle, read_only, not_host_lifetime, registry_conflict; unavailable + unknown_type), and whether a new root may retry it.

func Forbidden

func Forbidden(message ...string) *ChordError

Forbidden is errors.ts forbidden(message = "forbidden"), for factories and methods refusing a principal. The default applies only when message is omitted, as upstream's default parameter does.

func FromWireError

func FromWireError(err WireError) *ChordError

FromWireError is wire.ts fromWireError: the ChordError again, without the code prefix the message carries.

func Invalid

func Invalid(reason, message string, details any) *ChordError

Invalid is errors.ts invalid(reason, message, details).

func NewChordError

func NewChordError(code ChordErrorCode, message string, options ChordErrorOptions) *ChordError

NewChordError is errors.ts new ChordError(code, message, options).

func NotReady

func NotReady(what string) *ChordError

NotReady is cell.ts notReady: the error placeholders throw when used before activation finished.

func (*ChordError) Error

func (err *ChordError) Error() string

func (*ChordError) Unwrap

func (err *ChordError) Unwrap() error

type ChordErrorCode

type ChordErrorCode string

ChordErrorCode is a code callers see. A refused or aborted reload keeps the code of its cause.

const (
	CodeAborted          ChordErrorCode = "aborted"
	CodeContractMismatch ChordErrorCode = "contract_mismatch"
	CodeForbidden        ChordErrorCode = "forbidden"
	CodeGone             ChordErrorCode = "gone"
	CodeInvalid          ChordErrorCode = "invalid"
	CodeNotInVariant     ChordErrorCode = "not_in_variant"
	CodeNotReady         ChordErrorCode = "not_ready"
	CodeReleased         ChordErrorCode = "released"
	CodeSuperseded       ChordErrorCode = "superseded"
	CodeUnavailable      ChordErrorCode = "unavailable"
	CodeUpgradeConflict  ChordErrorCode = "upgrade_conflict"
	CodeUpgradeRequired  ChordErrorCode = "upgrade_required"
)

type ChordErrorOptions

type ChordErrorOptions struct {
	Cause   error
	Details any
	Reason  string
}

ChordErrorOptions are the optional parts of a ChordError.

type CodeVersionState

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

CodeVersionState is one retained code version.

type CommitFrame

type CommitFrame struct{ Reload int }

func (CommitFrame) T

func (CommitFrame) T() string

type ConnectOptions

type ConnectOptions struct {
	LinkOptions
	// Principal is what a request from the parent acts as when the parent does not forward its caller's principal (its
	// own code). Required: Connect panics with a TypeError unless it is set (HasPrincipal for an explicit null).
	Principal    Principal
	HasPrincipal bool
}

ConnectOptions are Connect's options: the link's, and the principal its parent's own requests act as.

type Connection

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

Connection is one end of a link on a host: consumer of remote references, provider for the peer's holds, and relay.

State

A hold implies the state of its variant (unless it says state: false). The provider answers with a unit: the shape, then a snapshot of each state member the consumer does not have yet (the shape's State lists them), then the members' ops and resets. A reload or a variant change sends another unit with the members that are new; members that left the variant stop. The consumer applies a shape once its snapshots are here (RemoteBinding).

Flow control

Problem: state is pushed as fast as it changes, but a peer may read slowly (a phone behind a relay), and a relay may hide that: Cloudflare forwards to browsers without backpressure. Everything sent then queues in front of the next call result. Example: a browser opens three long transcripts (500 KiB of snapshots each) over a 5 Mbit/s path; a result sent next waits 2.4 s, and the snapshot of a transcript the user already left is still sent in full.

Solution: the peer acknowledges what it processed (AckFrame, a cumulative frame count), and the sender counts the sizes of the frames not yet acknowledged. While they exceed the window, state waits here in slots, flushed in creation order as acknowledgements come:

  • a member's stream has one slot: ops are appended (encoded batches of one stream may be concatenated, see delta's encoder), a snapshot, reset or error replaces it;
  • a hold's unit has one slot, built lazily from the current values when it is sent, so a newer unit merges into it; while it waits, the members it introduces have no stream yet.

The first unit of a hold that is not a re-hold (Again) is sent at once, past the window: a Get waits for it, and must not wait behind other holds' state. Results, shapes, gone, reload control and pings are sent at once too: they are bounded by the requests the peer makes. Hence the one ordering exception of a link: while state waits, a result can arrive before state changes made before it. Frames of one stream stay in order.

Waiting ops are capped per link (PendingCap): beyond, the oldest streams are replaced by their current value (a reset built at flush), or, on a relay, by a reset asked of the provider (resync), so memory stays bounded however long the peer stalls. The window bounds what is unacknowledged when a frame is sent, so one frame (a large snapshot) may exceed it. Both hellos must announce acks; with an older peer nothing is acknowledged and nothing waits. Links that do not report sizes (IPC) never fill the window.

type Contract

type Contract struct {
	Scope       ContractScope
	Name        string
	Version     int
	Input       Schema
	Description Description
	Fingerprint string
	Remote      *RemoteDef
	Local       *LocalDef
}

Contract is a remote or local contract token (contract.ts RemoteContract | LocalContract). A token received over a link has neither Remote nor Local definition members: it is only good for binding and validation.

func Local

func Local(name string, def LocalDef) *Contract

Local is contract.ts local(name, def). It panics with a TypeError on an invalid definition.

func Remote

func Remote(name string, def RemoteDef) *Contract

Remote is contract.ts remote(name, def). It panics with a TypeError on an invalid definition. Variants and members are described in Pi's order: each variant's state members, then its methods.

type ContractScope

type ContractScope string

ContractScope is a contract's scope, the discriminator of contract.ts AnyContract = RemoteContract | LocalContract.

const (
	ScopeRemote ContractScope = "remote"
	ScopeLocal  ContractScope = "local"
)

Contract scopes.

type ControlMessage

type ControlMessage struct {
	Type         ControlMessageType
	Value        any
	Message      string
	Reason       string
	ActiveCalls  *float64
	Viewers      *float64
	DurableTasks *float64
}

ControlMessage is manager.ts ControlMessage. Control messages share the IPC channel with chord frames: { chord2control: message }. Type selects the members a message carries: init carries Value, fatal carries Message and an optional Reason (empty = absent), status carries the optional counts (nil = absent), JS numbers as sent.

func (ControlMessage) MarshalJSON

func (message ControlMessage) MarshalJSON() ([]byte, error)

MarshalJSON writes the members of the message's type, in manager.ts order.

func (*ControlMessage) UnmarshalJSON

func (message *ControlMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a control message as manager.ts reads one: by its type, ignoring other members.

type ControlMessageType

type ControlMessageType string

ControlMessageType is the discriminator of a ControlMessage: manager.ts ControlMessage's type literals.

const (
	ControlInit     ControlMessageType = "init"
	ControlReady    ControlMessageType = "ready"
	ControlFatal    ControlMessageType = "fatal"
	ControlShutdown ControlMessageType = "shutdown"
	ControlStatus   ControlMessageType = "status"
)

Control message types: manager.ts ControlMessage's type literals.

type Ctx

type Ctx interface {
	// Signal is the root's AbortSignal: its Done channel closes when the root is aborted.
	Signal() context.Context
	RootID() string
	CodeVersion() int
	Principal() Principal
	// Get holds the object of contract typ for input; options nil is Pi's undefined. It returns once the reference is ready:
	// live, with every state member of its variant (unless State is false). It fails with the activation error, aborted
	// when the ctx is aborted or the call settles first, or unavailable/ready_timeout after the host's ReadyTimeout; the
	// reference is released then.
	Get(typ *Contract, input any, options *GetOptions) (Ref, error)
}

Ctx is the explicit call context of one root, a short Chord call tree (types.ts:14-24). Calls made with it carry its root id and code version; Get holds are released when the call that received this ctx settles.

type CtxImpl

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

CtxImpl is the Ctx of one root, call or task.

func (*CtxImpl) CodeVersion

func (ctx *CtxImpl) CodeVersion() int

func (*CtxImpl) Get

func (ctx *CtxImpl) Get(typ *Contract, input any, options *GetOptions) (Ref, error)

Get holds an object for this call and waits for it to be ready (see awaitReady); the hold is released when the call that received this ctx settles.

func (*CtxImpl) Principal

func (ctx *CtxImpl) Principal() Principal

func (*CtxImpl) RootID

func (ctx *CtxImpl) RootID() string

func (*CtxImpl) Signal

func (ctx *CtxImpl) Signal() context.Context

type Decls

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

Decls is everything one factory run declared, by kind and key.

type DefineFacetOptions

type DefineFacetOptions struct {
	Uses []*Contract
}

DefineFacetOptions are DefineFacet's options.

type Derived

type Derived struct {
	Source[any]
	Sources Sources
	// contains filtered or unexported fields
}

Derived is cell.ts Derived: a synchronous derivation. Sources are object cells/derivations (recomputed atomically with the write) or other readables such as reference state members (recomputed when they publish). Subscribers receive diffs.

func NewDerived

func NewDerived(key string, sources Sources, fn func(values ...any) any, options SourceOptions) (*Derived, error)

NewDerived is cell.ts new Derived(key, sources, fn, options). fn panics where Pi's throws.

func (*Derived) Attach

func (derived *Derived) Attach(precomputed map[any]any) error

Attach computes the first value (or takes it from precomputed, a reload's validated dry run, keyed by derivation) and starts following the sources (at install, never inside a factory).

func (*Derived) Compute

func (derived *Derived) Compute(read func(source Readable[any]) any) (result any, err error)

Compute applies the derivation's function to the values read from the sources. A panicking fn is Pi's throwing fn and returns its error.

func (*Derived) Detach

func (derived *Derived) Detach()

Detach stops following the sources.

func (*Derived) Install

func (derived *Derived) Install(next any)

Install adopts next and publishes its diff from the previous value (a single r op before the first value).

func (*Derived) Refresh

func (derived *Derived) Refresh()

Refresh recomputes and republishes, including dependents. Errors are reported (the source write already happened).

func (*Derived) Value

func (derived *Derived) Value() any

Value is the current value (nil before Attach).

type Description

type Description struct {
	Name    string
	Scope   ContractScope
	Version int
	Input   Schema
	// Host is where the objects of a remote type live (required there); nil for a local type.
	Host     Placement
	Variants Fields[Fields[MemberDescription]]
}

Description is a contract's canonical description: what a token carries over a link and what fingerprints hash. Variants and their members are in Pi's order (own-key order of the definition).

func (Description) MarshalJSON

func (description Description) MarshalJSON() ([]byte, error)

MarshalJSON writes the description's wire form (wireValue).

func (*Description) UnmarshalJSON

func (description *Description) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a wire description, keeping the order of its variants and members.

type Driver

type Driver interface {
	Spawn() (Instance, error)
}

Driver is manager.ts Driver.

func ForkDriver

func ForkDriver(options ForkDriverOptions) Driver

ForkDriver is manager.ts forkDriver: it forks options.Entry under Node (node from PATH, Pi's process.execPath) with Node's IPC channel, as child_process.fork does. The child is detached: it leads a process group, so the whole tree can be killed.

type Entry

type Entry struct {
	Name  string
	Value any
}

Entry is one named entry of an object literal passed to Self.Register. A slice of entries keeps the literal's order, which Pi iterates with Object.entries and which a Go map would lose.

type Exit

type Exit struct {
	Code   *int
	Signal *string
}

Exit is manager.ts Exit: the exit code, or the signal that ended the child (nil = null).

type Exposed

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

Exposed is a local member backed by a resource (`self.Expose(res)`): references read the resource's value once live.

type Facet

type Facet struct {
	FacetDefinition
	Name string
}

Facet is a named facet. Modules are named by their URL; reloading a facet replaces everything it served.

func NodeLoader

func NodeLoader(modules []string) ([]Facet, error)

NodeLoader is loader.ts nodeLoader: it imports fresh copies of facet modules (default export: a FacetDefinition, from DefineFacet's JavaScript twin defineFacet); each facet is named by its URL. It is NewNodeLoader's Load with no options.

type FacetApi

type FacetApi struct {
	Serve Serve
	// Name is the host's name (`server`, `session:S1`, ...).
	Name string
	// Signal is cancelled when this run of the facet is no longer installed: a reload that replaced or removed it
	// committed, the reload that loaded it aborted, or the host closed. While a reload prepares, the installed and the
	// candidate run are both live.
	Signal context.Context
	// contains filtered or unexported fields
}

FacetApi is what a facet's Setup gets. Serve registers types; Root and Registry give the facet's code that is not a Chord method, listener or task access to its own host, so plugins never need a process-global host. Both may be kept and used after Setup returns.

func (FacetApi) Registry

func (api FacetApi) Registry(registry Registry[any]) RegistryView[any]

Registry is the facet's host's registry view (Get(key, ctx) reads the table of ctx's code version).

func (FacetApi) Root

func (api FacetApi) Root(fn func(ctx Ctx) (any, error), options RootOptions) (any, error)

Root starts a root on the facet's host (in its current code version at call time).

type FacetDefinition

type FacetDefinition struct {
	// Uses are the contract tokens this facet consumes; checked against providers at reload.
	Uses  []*Contract
	Setup func(api FacetApi) error
}

FacetDefinition is what a facet module exports: the code that serves its types on one host kind.

func DefineFacet

func DefineFacet(setup func(api FacetApi) error, options DefineFacetOptions) FacetDefinition

DefineFacet is host.ts defineFacet.

type FacetLoader

type FacetLoader func(modules []string) ([]Facet, error)

FacetLoader imports facet modules (fresh copies on every call) and names them by module URL.

type Factory

type Factory func(input any, principal Principal, self Self) (Implementation, error)

Factory builds an object's implementation from its input, the principal it is created for and its self.

type Field

type Field[V any] struct {
	Name  string
	Value V
}

Field is one own property of a JavaScript object literal: its name and value.

type Fields

type Fields[V any] []Field[V]

Fields is a JavaScript object literal as an ordered list of properties. Pi iterates such objects (Object.entries, Object.keys) and JSON.stringify writes them in own-key order: array-index names first in ascending order, then the other names in insertion order. Contracts normalize their definitions to that order (ownFields).

func (Fields[V]) Get

func (fields Fields[V]) Get(name string) (V, bool)

Get is the value of property name.

func (Fields[V]) Has

func (fields Fields[V]) Has(name string) bool

Has reports whether property name exists.

type ForkDriverOptions

type ForkDriverOptions struct {
	// Entry is the child's entry module.
	Entry string
	Args  []string
	Env   map[string]string
	// ExecArgv are Node flags for the child, e.g. ["--import", sourceResolver] (default: none).
	ExecArgv []string
	// Init is sent to the child as its first control message (ChildControl's Init) when HasInit is set.
	Init    any
	HasInit bool
	// Lock is a lock name (nil = none): one live process per name, across managers and processes. The child acquires
	// it as a kernel lock (ChildControl's Lock, before opening its storage); a second child fails to start with
	// unavailable/locked.
	Lock *string
	// OnOutput is an optional stdout/stderr tap. Streams are still mirrored to the parent's standard output.
	OnOutput func(stream string, chunk []byte)
	// OnMessage is an optional application metadata tap; control messages and chord frames keep their normal handling.
	OnMessage func(message any)
}

ForkDriverOptions is manager.ts ForkDriverOptions.

type Frame

type Frame interface {
	// T is the frame's "t" discriminant.
	T() string
	// contains filtered or unexported methods
}

Frame is one wire frame.

func DecodeFrame

func DecodeFrame(data []byte) (Frame, error)

DecodeFrame parses and validates one frame. It fails when the data is not JSON or not a frame.

type GetOptions

type GetOptions struct {
	// Principal the object is created for. HasPrincipal false is Pi's undefined (the host's own principal); true with a
	// nil Principal is an explicit null, which host.ts `??` also maps to the host's own principal but acquireRemote
	// sends on.
	Principal    Principal
	HasPrincipal bool
	// State is false for a method-only reference (types.ts:11-15): it receives no state unless another reference to
	// the same object wants it, and is ready once its object is live. Nil is true.
	State *bool
	// Signal aborts an awaited Host.Get (Pi's `options.signal`; Ctx.Get ignores it).
	Signal context.Context
}

GetOptions are the options of a get (types.ts:7-12).

type GoneFrame

type GoneFrame struct {
	ID    int
	Error WireError
}

func (GoneFrame) T

func (GoneFrame) T() string

type HelloFrame

type HelloFrame struct {
	// Protocol is the link protocol version (ProtocolVersion; 0 is absent, Pi's 1). Peers of another version close
	// the link.
	Protocol int
	Name     string
	// Kind is "host" or "client".
	Kind        string
	CodeVersion int
	// Acks: the sender acknowledges what it receives (AckFrame). Flow control applies only when both hellos say so.
	Acks bool
}

func (HelloFrame) T

func (HelloFrame) T() string

type HoldFrame

type HoldFrame struct {
	ID int
	// At is the target host name.
	At string
	// Token is the consumer's contract token; the provider checks that it covers it.
	Token Description
	Input any
	// Principal is a forwarded principal, honored only on frames from the parent link.
	Principal    any
	HasPrincipal bool
	// Origin is the client connection the hold comes from: an opaque id the server assigned to it, forwarded by
	// relays and honored only on frames from the parent link; present means the hold is a client's (not a reload
	// participant). Empty is absent.
	Origin string
	// NoState is `state: false`: no state for this hold until a sub (a method-only binding).
	NoState bool
	// Again says the consumer already has values (a re-hold after a link loss): its unit is not urgent.
	Again bool
}

func (HoldFrame) T

func (HoldFrame) T() string

type HostFamily

type HostFamily struct{ Prefix, Key string }

HostFamily places the objects of a remote type on the host Prefix + the value of the input's string field Key (contract.ts HostFamily): `session:` + `session` puts `{ session: "S1", … }` on `session:S1`.

func NewHostFamily

func NewHostFamily(prefix, key string) HostFamily

NewHostFamily is contract.ts hostFamily(prefix, key): objects of the type live on prefix + the value of the input's string field key. The field is required and must be a non-empty string. It panics with a TypeError for an empty prefix or key.

type HostImpl

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

HostImpl is a Chord host.

func CreateHost

func CreateHost(options HostOptions) *HostImpl

CreateHost is host.ts createHost. It panics with a TypeError, as upstream throws one, unless options carry Self.

func (*HostImpl) Accept

func (host *HostImpl) Accept(link Link, options AcceptOptions) error

Accept accepts a child link (a worker or a browser); requests on it act as options.Principal.

func (*HostImpl) Close

func (host *HostImpl) Close() error

Close disposes every object, holders before what they hold (a resource's close may still use the objects its object holds, local or remote), then closes the links and waits for the host's background tasks.

func (*HostImpl) CodeVersion

func (host *HostImpl) CodeVersion() int

CodeVersion is the current code version.

func (*HostImpl) Connect

func (host *HostImpl) Connect(link Link, options ConnectOptions)

Connect sets (or replaces, after a reconnect) the link to this host's parent; remote references re-hold over it. The parent's own requests act as options.Principal; requests it relays act as the principal it forwards. It panics with a TypeError, as upstream throws one, unless options carry Principal.

func (*HostImpl) Get

func (host *HostImpl) Get(typ *Contract, input any, options *GetOptions) (Ref, error)

Get holds the object of typ for input and returns its reference once it is ready: live, with every state member of its variant (unless options.State is false). It fails with the activation error, aborted when options.Signal is cancelled, or unavailable/ready_timeout after HostOptions.ReadyTimeout; the reference is released then.

func (*HostImpl) Hold

func (host *HostImpl) Hold(typ *Contract, input any, options *GetOptions) (ref Ref, err error)

Hold is the synchronous form of Get: the reference at once, possibly still loading (Ready waits for it).

func (*HostImpl) Install

func (host *HostImpl) Install(facet Facet, options LoadOptions) error

Install installs facet synchronously, then awaits its host objects unless AwaitHostObjects is false.

func (*HostImpl) InvalidatePrincipal

func (host *HostImpl) InvalidatePrincipal(match PrincipalMatch) error

InvalidatePrincipal force-disposes every object whose principal matches (never the host principal), re-stamps or closes matching links, and propagates pattern matches to child hosts.

func (*HostImpl) Load

func (host *HostImpl) Load(plugins []PluginRef, options LoadOptions) error

Load installs all facets before awaiting their host objects; referenced objects are created when first referenced.

func (*HostImpl) Name

func (host *HostImpl) Name() string

Name is the host's name.

func (*HostImpl) PreviousCodeVersion

func (host *HostImpl) PreviousCodeVersion() (codeVersion int, ok bool)

PreviousCodeVersion is the retained previous code version; ok is false when there is none.

func (*HostImpl) Ready

func (host *HostImpl) Ready() error

Ready awaits the host objects present at call time, including those started by Serve or deferred loads.

func (*HostImpl) Registry

func (host *HostImpl) Registry(registry Registry[any]) RegistryView[any]

Registry is the host's view of registry (Get(key, ctx) reads the table of ctx's code version).

func (*HostImpl) Reload

func (host *HostImpl) Reload(plugins []PluginRef, options ReloadOptions) (ReloadReport, error)

Reload reloads the given facets (modules are re-imported); facets not listed keep running unchanged.

func (*HostImpl) Root

func (host *HostImpl) Root(fn func(ctx Ctx) (any, error), options RootOptions) (any, error)

Root runs fn in a new root of this host, in options.CodeVersion (default: the current code version at call time). The root's id, its code version and its entry are one section of the loop, as upstream's root is synchronous up to its first await: a retirement cannot fall between choosing the current code version and entering it.

func (*HostImpl) Route

func (host *HostImpl) Route(prefix string, route Route)

Route sends requests for hosts named prefix… to route. It panics with a TypeError, as upstream throws one, when route has no Principal.

func (*HostImpl) Serve

func (host *HostImpl) Serve(typ *Contract, factory Factory, options ServeOptions) (err error)

Serve registers a factory for a type on the current code version.

type HostManager

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

HostManager is manager.ts HostManager, made by CreateHostManager.

func CreateHostManager

func CreateHostManager(options HostManagerOptions) *HostManager

CreateHostManager is manager.ts createHostManager.

func (*HostManager) Instance

func (manager *HostManager) Instance() Instance

Instance is the running child (nil = undefined).

func (*HostManager) Liveness

func (manager *HostManager) Liveness() Liveness

Liveness is the child's last reported liveness.

func (*HostManager) Replace

func (manager *HostManager) Replace() (Instance, error)

Replace stops, waits for the exit, and starts.

func (*HostManager) Start

func (manager *HostManager) Start() (Instance, error)

Start starts the child (or returns the running one) once it reported ready. Serialized with Stop and Replace.

func (*HostManager) Status

func (manager *HostManager) Status() string

Status is the manager's status: HostManagerStopped, HostManagerStarting, HostManagerRunning or HostManagerStopping.

func (*HostManager) Stop

func (manager *HostManager) Stop() error

Stop asks the child to shut down, then kills its process tree after the grace period.

type HostManagerOptions

type HostManagerOptions struct {
	Driver Driver
	// KeepAlive is evaluated every CheckInterval (default 1s) while running; false stops the child.
	KeepAlive     func(liveness Liveness) bool
	CheckInterval *time.Duration
	// Grace is how long a child may take to shut down before its process tree is killed (default 5s).
	Grace *time.Duration
	// ReadyTimeout is how long to wait for ready (default 30s).
	ReadyTimeout *time.Duration
	// OnExit is called when the child exited on its own (crash, fatal) or after a stop.
	OnExit func(exit Exit)
}

HostManagerOptions is manager.ts HostManagerOptions. A nil duration takes manager.ts's default.

type HostNamed

type HostNamed struct{ Name string }

HostNamed places the objects of a remote type on the one host named Name (contract.ts HostNamed).

func NewHostNamed

func NewHostNamed(name string) HostNamed

NewHostNamed is contract.ts hostNamed(name): objects of the type live on the host named name. It panics with a TypeError for an empty name.

type HostOptions

type HostOptions struct {
	// Name defaults to "host".
	Name string
	// Self is the principal of the host's own code: roots it starts, code inside its objects, and its `lifetime:
	// "host"` objects. Required: CreateHost panics with a TypeError unless Self is set (HasSelf for an explicit null).
	// It is compared by PrincipalKey, so an equal principal from elsewhere reaches the same objects.
	Self    Principal
	HasSelf bool
	// PrincipalKey maps a principal to its object key (should include connection provenance and grant revision).
	// Defaults to CanonicalJSON.
	PrincipalKey func(principal Principal) string
	// Dev validates every cell write and exposed state value against its schemas.
	Dev bool
	// OnError gets errors from background work (disposal, listeners, tasks). Defaults to writing them to stderr.
	OnError func(err error)
	// TaskStopDeadline is how long a reload waits for an object's aborted tasks to finish before it starts their
	// replacements anyway (reported). Nil is Pi's undefined: 5000 ms.
	TaskStopDeadline *time.Duration
	// ReadyTimeout is how long an awaited Get waits for its reference to be ready, and an object waits for the
	// references it holds to be ready and hydrated, before it fails unavailable/ready_timeout. Nil is Pi's undefined:
	// 60000 ms; math.MaxInt64 is Pi's Infinity (no timeout).
	ReadyTimeout *time.Duration
	// Linger keeps a remote reference's binding after its last reference was released (consumer side).
	Linger *LingerOptions
	// Loader is needed for Load/Reload with modules.
	Loader FacetLoader
	// Kind is KindClient (browser: never a reload participant, never carries roots or code versions) or KindHost (default).
	Kind string
	// Upstream is the link to this host's parent (server) and the principal its own requests act as. It can also be set
	// later with Connect.
	Upstream *UpstreamOptions
}

HostOptions are CreateHost's options. Pi's principal type is a parameter and Chord invents no principals: the app supplies the host's own (Self), the one its parent's own requests act as (Upstream, Connect), the ones links act as (Accept) and the ones routed hosts act as (Route.Principal).

type Hydration

type Hydration struct {
	Hydrated bool
	// WhenHydrated resolves once hydrated and rejects if the source ends first. It runs on the host's loop.
	WhenHydrated func() *Promise[struct{}]
}

Hydration is cell.ts Hydration: whether a state source has its value. A remote reference's member before its first snapshot has none, and neither has anything derived from or forwarding it. Sources that do not implement hydrating always have their value.

type Implementation

type Implementation = *chordjson.Object

Implementation is what a factory returns: members by name (methods, state sources, opaque values) and, for a remote contract, the variant under "kind". It is a JavaScript object: members keep own-key order (Shape.Members, validation order) and the object has identity (accepts views are cached per implementation).

type Installed

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

Installed is an implementation installed for an code version.

type Instance

type Instance interface {
	PID() int
	Link() *IpcLink
	// Exited is closed once the child exited; Exit then returns the exit.
	Exited() <-chan struct{}
	Exit() Exit
	Send(message ControlMessage)
	// KillTree kills the child and everything it spawned.
	KillTree()
	OnControl(listener func(message ControlMessage))
}

Instance is manager.ts Instance: a running child, its link (for host.accept) and its exit.

type InvalidateFrame

type InvalidateFrame struct{ Pattern *chordjson.Object }

func (InvalidateFrame) T

func (InvalidateFrame) T() string

type IpcChannel

type IpcChannel interface {
	Connected() bool
	// Send writes message. With a callback, a failed write (the peer process exited and the pipe is broken: EPIPE) is
	// reported to it, off the sender's stack, instead of being raised where nobody would handle it; nil is Node's send
	// without one. The error may carry a Node error code (a Code() string method).
	Send(message any, callback func(err error)) bool
	// On adds listener for event "message" or "disconnect".
	On(event string, listener *IpcListener)
	// Off removes listener from event "message" or "disconnect".
	Off(event string, listener *IpcListener)
}

IpcChannel is `process` in a forked child, or the parent's child process reference. Messages are JSON values (chordjson), as Node's default IPC serialization carries them.

func ProcessChannel

func ProcessChannel() IpcChannel

ProcessChannel is Pi's `process` as an IPC channel: the Node IPC channel the parent opened on NODE_CHANNEL_FD (manager.ts childControl's default channel). Without one, as in a process nobody forked, the channel is not connected and sends are skipped.

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

IpcLink carries Chord frames on an IPC channel wrapped as `{ chord2: frame }`; other messages (control) pass by. Both ends are processes of one application, so large payloads are packed both ways.

func NewIpcLink(channel IpcChannel) *IpcLink

NewIpcLink is Pi's ipcLink.

func (*IpcLink) Close

func (link *IpcLink) Close(reason ...string)

func (*IpcLink) Closed

func (link *IpcLink) Closed() bool

func (*IpcLink) OnClose

func (link *IpcLink) OnClose(handler func(reason string))

OnClose registers handler; on a closed link it is called at once with "closed" (link.ts:38-41). Handlers are a set, as Pi's: the same func value registered again is not added twice. Identity is the func value itself (funcID), so it is the same handler only when the same value is passed again, as Pi's function identity.

func (*IpcLink) Receive

func (link *IpcLink) Receive(handler func(frame Frame))

func (*IpcLink) Send

func (link *IpcLink) Send(frame Frame) (int, error)

type IpcListener

type IpcListener func(message any)

IpcListener is a listener on an IpcChannel. Off removes a listener by its pointer, as Node removes one by function identity (Go functions are not comparable). A "disconnect" listener is called with a nil message.

type Lifetime

type Lifetime string

Lifetime is how long objects of a type live: LifetimeReferenced (the default) or LifetimeHost.

const (
	// LifetimeReferenced creates an object at the first get of its address and disposes it after the last reference is
	// released (plus Linger).
	LifetimeReferenced Lifetime = "referenced"
	// LifetimeHost creates the type's one object when its facet loads (loading waits until it is live) and keeps it
	// until the host closes or a reload removes its facet.
	LifetimeHost Lifetime = "host"
)

Lifetimes.

type LingerOptions

type LingerOptions struct {
	Types map[string]time.Duration
	Cap   *int
}

LingerOptions are HostOptions.Linger: when the last reference to a remote object is released, its binding stays held for Types[type name] so a quick re-get reuses the hold and its hydrated state. At most Cap bindings (nil: 4) linger; beyond, the least recently released go first. Types not listed do not linger.

type Link interface {
	Closed() bool
	// Send transmits frame; it does nothing once the link is closed. It returns the size of the encoded frame as sent
	// (JSON text length in UTF-16 units, or bytes of a packed message) when the transport knows it, else 0. The
	// connection's flow control counts these sizes; a link that never reports sizes is not windowed (link.ts:7-12). A
	// transport failure is returned, as Pi's transmit throws to the caller of send.
	Send(frame Frame) (int, error)
	// Receive sets the single receiver. Frames arriving earlier are queued.
	Receive(handler func(frame Frame))
	OnClose(handler func(reason string))
	// Close closes both ends: the peer gets a bye. Without a reason the reason is "closed" (link.ts:43).
	Close(reason ...string)
}

Link is an ordered (FIFO), bidirectional frame channel between two hosts.

type LinkOptions

type LinkOptions struct {
	// PingInterval is the time between pings (default 15 s).
	PingInterval *time.Duration
	// PingTimeout closes the link when nothing arrived for this long (default 45 s). Everything held through it is
	// released.
	PingTimeout *time.Duration
	// Window is the unacknowledged frame bytes (JSON text length) beyond which state frames wait for the peer (default
	// 256 KiB). It applies only when both ends acknowledge frames and the link reports sizes; math.MaxInt never holds
	// state back.
	Window *int
	// PendingCap is the bytes of state ops that may wait for the peer on this link (default 4 windows). Beyond, the
	// oldest waiting streams are replaced by their current value (a reset), so memory stays bounded however long the
	// peer stalls.
	PendingCap *int
	// OnProtocolMismatch is called when the peer speaks another link protocol version (Peer is nil if it did not say): the
	// link closes, and should not be reconnected with the same code. A browser reloads its page, for instance.
	OnProtocolMismatch func(versions ProtocolVersions)
}

LinkOptions are the options of a link. Nil members are absent.

type ListenerDecl

type ListenerDecl struct {
	Source any
	// Select is nil (Pi's undefined) when the listener subscribes to the source itself.
	Select func(value any) Subscribable[any]
	// Fn runs for each event in a fresh root. Pi awaits it; a throw or rejection is the error.
	Fn func(event any, ctx Ctx) error
}

ListenerDecl is a listener as Self.On declares it.

type Liveness

type Liveness struct {
	// Booting is true when the child started but is not ready yet.
	Booting     bool
	ActiveCalls float64
	// Viewers the child reports (it counts heartbeating subscribers).
	Viewers      float64
	DurableTasks float64
	// IdleFor is the time since the child last reported work (calls, viewers or tasks), or since it became ready.
	IdleFor time.Duration
}

Liveness is manager.ts Liveness.

type LoadOptions

type LoadOptions struct {
	// AwaitHostObjects awaits the activation of the `lifetime: "host"` objects the facets serve (nil: true). False
	// starts them but leaves readiness to Ready (a child host whose objects need its parent, which admits it only
	// later).
	AwaitHostObjects *bool
}

LoadOptions are Install's and Load's options.

type LocalDef

type LocalDef struct {
	Version int
	Input   Schema
	Members Fields[any]
}

LocalDef defines a local contract. A member is a MethodSpec, an OpaqueSpec or a state Schema, in declaration order.

type MalformedFrame

type MalformedFrame struct{ Value any }

MalformedFrame is what a transport received that is not a valid Frame. Pi's links deliver any JSON object with a string "t" (link.ts:79-83) or any IPC chord2 payload (link.ts:140-141), and the connection rejects what fails isFrame (connection.ts:383); a Go Frame can only carry a valid frame, so the rest is delivered as this value.

func (MalformedFrame) T

func (frame MalformedFrame) T() string

T is the value's "t" member when it is a string.

type MemberDescription

type MemberDescription struct {
	Kind   string
	Args   Schema
	Result Schema
	Schema Schema
	ID     string
}

MemberDescription describes one member: a method (Args, Result), a state (Schema) or an opaque object (ID).

type MemoryLink struct {
	Peer *MemoryLink
	// contains filtered or unexported fields
}

MemoryLink is one end of an in-memory link pair.

func (*MemoryLink) Close

func (link *MemoryLink) Close(reason ...string)

func (*MemoryLink) Closed

func (link *MemoryLink) Closed() bool

func (*MemoryLink) OnClose

func (link *MemoryLink) OnClose(handler func(reason string))

OnClose registers handler; on a closed link it is called at once with "closed" (link.ts:38-41). Handlers are a set, as Pi's: the same func value registered again is not added twice. Identity is the func value itself (funcID), so it is the same handler only when the same value is passed again, as Pi's function identity.

func (*MemoryLink) Receive

func (link *MemoryLink) Receive(handler func(frame Frame))

func (*MemoryLink) Send

func (link *MemoryLink) Send(frame Frame) (int, error)

func (*MemoryLink) Sever

func (link *MemoryLink) Sever()

Sever simulates a dead network: frames are dropped silently in both directions and no close is signalled.

type MethodSpec

type MethodSpec struct {
	Args   Schema
	Result Schema
}

MethodSpec is a method member: its arguments and result schemas. A nil Args means the method takes no arguments (it is called `ref.name(ctx)`; in Go its handler is still a methodFunc, whose args are nil), a nil Result that it returns nothing (void).

func Method

func Method(schemas ...Schema) MethodSpec

Method is contract.ts method(args?, result?) (contract.ts:31-33, three overloads): `method()` is Method(), `method(args)` is Method(args) (no result, the handler returns nothing) and `method(undefined, result)` is Method(nil, result). Go has no overloads, so the parameters are variadic: a nil schema is Pi's undefined, and more than two panic with a TypeError.

type ModuleRef

type ModuleRef string

ModuleRef is a PluginRef naming a facet module by path or URL.

type NodeLoaderImpl

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

NodeLoaderImpl is a Node facet loader: its Load is a FacetLoader.

func NewNodeLoader

func NewNodeLoader(options NodeLoaderOptions) *NodeLoaderImpl

NewNodeLoader makes a Node facet loader. pig divergence (D178): the loader owns isolated Node children, not in-process module copies.

func (*NodeLoaderImpl) Close

func (loader *NodeLoaderImpl) Close() error

Close stops every child this loader started.

func (*NodeLoaderImpl) Load

func (loader *NodeLoaderImpl) Load(modules []string) ([]Facet, error)

Load imports the facet modules in a child process and returns their facets, named by module URL, in module order. A module whose default export is not a facet fails the load with a TypeError, as loader.ts does. pig divergence (D178): Load runs the facet modules in an isolated Node child, not in this process.

type NodeLoaderOptions

type NodeLoaderOptions struct {
	// Chord is the Chord package the child imports createHost from: its directory, its entry file or a file URL. Empty
	// finds @earendil-works/chord installed above the first module.
	Chord string
	// ExecArgv are Node flags for the child (default: none).
	ExecArgv []string
	// ReadyTimeout is how long Load waits for the child to import and install the modules (default 30s).
	ReadyTimeout *time.Duration
}

NodeLoaderOptions configure a NodeLoaderImpl.

type ObjectIdentity

type ObjectIdentity struct {
	Address   string
	TypeName  string
	Input     any
	Principal Principal
	// HostLifetime is the one object of a LifetimeHost type.
	HostLifetime bool
}

ObjectIdentity is what identifies an object.

type ObjectImpl

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

ObjectImpl is one live object served by a host.

type ObjectStatus

type ObjectStatus string

ObjectStatus is an object's lifetime state.

const (
	ObjectActivating ObjectStatus = "activating"
	ObjectLive       ObjectStatus = "live"
	ObjectFailed     ObjectStatus = "failed"
	ObjectDisposing  ObjectStatus = "disposing"
	ObjectDisposed   ObjectStatus = "disposed"
)

type OpaqueSpec

type OpaqueSpec struct{ ID string }

OpaqueSpec is a native in-process object identified by name@version (local contracts only).

func Opaque

func Opaque(id string) OpaqueSpec

Opaque is contract.ts opaque(id); it panics with a TypeError when id is not name@version.

type Peer

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

Peer is what is on the other end of a connection.

type PingFrame

type PingFrame struct{ N int }

func (PingFrame) T

func (PingFrame) T() string

type Placement

type Placement interface {
	// contains filtered or unexported methods
}

Placement is a remote type's placement (contract.ts Placement = HostNamed | HostFamily): where its objects live, as data, so a description carries it and every host can check it. It is a closed union of HostNamed and HostFamily.

type PlacementFor

type PlacementFor = Placement

PlacementFor is contract.ts PlacementFor<I> = HostNamed | HostFamily<StringKeys<I>>: the placements a remote type with input I may have. The TypeScript parameter restricts a family's key to I's required string fields at compile time; Go's input is untyped, so the same restriction is the runtime check resolveHost makes (invalid/placement when the field names no host), and the type is Placement.

type PluginRef

type PluginRef interface {
	// contains filtered or unexported methods
}

PluginRef is a facet object (*Facet), or a module (ModuleRef: a path or URL) whose default export is a FacetDefinition.

type PongFrame

type PongFrame struct{ N int }

func (PongFrame) T

func (PongFrame) T() string

type PrepareFrame

type PrepareFrame struct {
	Reload      int
	CodeVersion int
	Plugins     []string
	Options     WireReloadOptions
}

func (PrepareFrame) T

func (PrepareFrame) T() string

type Principal

type Principal = any

Principal is the app-defined, JSON-serializable identity of a caller, mapped to an object key by HostOptions.PrincipalKey. Pi's principal type is a parameter (`createHost<P>`, default `unknown`); the app supplies every principal and Chord makes none up.

type PrincipalMatch

type PrincipalMatch struct {
	Predicate func(principal Principal) bool
	Pattern   PrincipalPattern
}

PrincipalMatch is what InvalidatePrincipal matches: a Predicate (this host only), or a Pattern (fields that must be equal; propagates to child hosts). Exactly one is set.

type PrincipalPattern

type PrincipalPattern = *chordjson.Object

PrincipalPattern is host.ts PrincipalPattern<P>: the fields a principal must have, equal (DeepEqual), for an InvalidatePrincipal pattern. Pi's mapped type is P's own optional fields; Go's principal is untyped (Principal), so a pattern is the JSON object of the fields to match.

type Promise

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

Promise is a value or error settled once, on a loop. Callbacks registered with then run on the loop, in registration order, after the settling section, as upstream's promise reactions do.

func (*Promise[T]) Await

func (promise *Promise[T]) Await(ctx context.Context) (T, error)

Await blocks until the promise settles or ctx ends. It must not be called on the loop, which settles it.

func (*Promise[T]) Settled

func (promise *Promise[T]) Settled() bool

Settled reports whether the promise has settled.

type ProtocolVersions

type ProtocolVersions struct {
	Local int
	Peer  *int
}

ProtocolVersions are the link protocol versions of the two ends of a mismatch.

type Readable

type Readable[T any] interface {
	Value() T
	// Subscribe calls listener with the current value immediately, then with every new value.
	Subscribe(listener func(value T)) func()
	// Events is the delta stream: a snapshot immediately, then ops, or a reset after a migration or rebind.
	Events(listener func(event StateEvent[T])) func()
}

Readable is a readable state source: a cell, a derivation, or a reference's state member (types.ts:31-38). Values are immutable by contract.

type Ref

type Ref interface {
	RefBase
	Member(name string) any
}

Ref is contract.ts Ref<C> = RefBase<C> & MembersOf<C>: what a get returns for a contract (object.ts RefImpl locally, remote.ts RemoteRef over a link). Upstream's late-bound members are properties of a Proxy; Member reads one by name: a state member is a Readable[any], a method is a func(args any, ctx Ctx) (any, error) (ctx may be nil, as upstream's optional ctx), an opaque member is its native value, and nil is undefined.

type RefBase

type RefBase interface {
	// Contract is the consumer contract token this reference was bound with.
	Contract() *Contract
	Status() RefStatus
	// Ready blocks until Pi's ready Promise settles; its rejection is the error.
	Ready(ctx context.Context) error
	// Variant is the variant; nil is Pi's undefined.
	Variant() *string
	// Shape is nil (Pi's undefined) until the provider's shape is known.
	Shape() *Shape
	// Err is why the reference is gone, if it is: Pi's error member, which Go's error interface keeps from being Error.
	Err() error
	OnShape(listener func(shape Shape)) func()
	// OnStatus is called after every status change (loading → live, live → loading while a link reconnects, released,
	// gone with err). A UI watches for gone to get again.
	OnStatus(listener func(status RefStatus, err error)) func()
	Release()
}

RefBase is the members every reference has (types.ts:63-79). Ref (contract.ts) adds the contract's members.

type RefCore

type RefCore interface {
	Ref
	// contains filtered or unexported methods
}

RefCore is a claim on an object: a local *RefImpl, or a *RemoteRef on another host (no object here).

type RefImpl

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

RefImpl is one hold on an object. Its members bind late to the current implementation.

func (*RefImpl) Contract

func (ref *RefImpl) Contract() *Contract

Contract is the consumer contract token this reference was bound with.

func (*RefImpl) Err

func (ref *RefImpl) Err() (err error)

Err is why the reference is gone, if it is.

func (*RefImpl) Member

func (ref *RefImpl) Member(name string) (member any)

Member is a member by name: a method (methodFunc), a state member (Readable[any]), an opaque value, or nil.

func (*RefImpl) OnShape

func (ref *RefImpl) OnShape(listener func(shape Shape)) func()

OnShape calls listener with every new shape; the returned function removes it.

func (*RefImpl) OnStatus

func (ref *RefImpl) OnStatus(listener func(status RefStatus, err error)) func()

OnStatus is called after every status change; the returned function removes it.

func (*RefImpl) Ready

func (ref *RefImpl) Ready(ctx context.Context) error

Ready waits until the reference is live; it fails when the reference is released or gone first, or when ctx ends.

func (*RefImpl) Release

func (ref *RefImpl) Release()

Release releases the hold.

func (*RefImpl) Shape

func (ref *RefImpl) Shape() (shape *Shape)

Shape is the provider's shape while the reference is live.

func (*RefImpl) Status

func (ref *RefImpl) Status() (status RefStatus)

Status is the reference's status.

func (*RefImpl) Variant

func (ref *RefImpl) Variant() (variant *string)

Variant is the current variant, nil for none.

type RefOwner

type RefOwner string

RefOwner is who a hold belongs to. "connection": a peer host over a link; "client": a browser (not a reload participant).

type RefStatus

type RefStatus string

RefStatus is a reference's status (types.ts:53).

const (
	RefLoading  RefStatus = "loading"
	RefLive     RefStatus = "live"
	RefReleased RefStatus = "released"
	RefGone     RefStatus = "gone"
)

RefStatus values (types.ts:53).

type Registration

type Registration struct {
	Registry Registry[any]
	Key      string
	Value    any
}

Registration is registry.ts Registration: one object's registration of value under key in registry. A Registry[V] converts to the Registry[any] it holds with Registry[any](registry): the token is plain data.

type Registry

type Registry[V any] struct {
	Name string
	// Conflict is ConflictError or ConflictLast.
	Conflict string
}

Registry is a registry token: plain data, as upstream's is. The host keys a registry's tables by Name, so two tokens with one name share a table, as upstream's do. V, the type of its values, is carried by the type parameter (upstream's never-set `value?: V`).

func DefineRegistry

func DefineRegistry[V any](name string, options ...RegistryOptions) Registry[V]

DefineRegistry is registry.ts defineRegistry(name, options = {}): conflict defaults to "error". Options are optional, as upstream's are.

type RegistryOptions

type RegistryOptions struct {
	Conflict string
}

RegistryOptions are DefineRegistry's options; an empty Conflict is ConflictError (upstream's omitted conflict).

type RegistryTable

type RegistryTable[V any] struct {
	// contains filtered or unexported fields
}

RegistryTable is registry.ts RegistryTable<V> = ReadonlyMap<string, V>: one code version's table, by key in insertion order. It is a typed view of an untyped store, so the host keeps every registry's tables untyped and a view hands them out typed without a copy. The zero RegistryTable is the empty table.

func NewRegistryTable

func NewRegistryTable(keys []string, values map[string]any) RegistryTable[any]

NewRegistryTable is a table of values under keys, in the order of keys (the host's Map insertion order). The table keeps keys and values; callers must not change them afterwards.

func (RegistryTable[V]) All

func (table RegistryTable[V]) All() iter.Seq2[string, V]

All is ReadonlyMap.entries(): key and value pairs in insertion order.

func (RegistryTable[V]) Get

func (table RegistryTable[V]) Get(key string) (V, bool)

Get is ReadonlyMap.get: the value under key, and whether there is one.

func (RegistryTable[V]) Has

func (table RegistryTable[V]) Has(key string) bool

Has is ReadonlyMap.has.

func (RegistryTable[V]) Keys

func (table RegistryTable[V]) Keys() []string

Keys is ReadonlyMap.keys(), in insertion order, as a fresh slice.

func (RegistryTable[V]) Len

func (table RegistryTable[V]) Len() int

Len is ReadonlyMap.size.

type RegistryView

type RegistryView[V any] interface {
	// Table is the table of ctx's code version, or of the current code version when ctx is nil (upstream's omitted ctx).
	Table(ctx Ctx) RegistryTable[V]
	// Get is Table(ctx).Get(key).
	Get(key string, ctx Ctx) (V, bool)
	// Subscribe calls listener with the current table immediately and whenever a new table is installed; the result
	// unsubscribes.
	Subscribe(listener func(table RegistryTable[V], codeVersion int)) func()
}

RegistryView is registry.ts RegistryView<V>, a host's view of one registry.

type RelayCall

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

RelayCall is one relayed call: settles once, by result, cancellation or the relay closing; removes both mappings.

type RelayRef

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

RelayRef is a hold relayed from an origin link to a downstream link. It owns everything done through it: state and calls queued while the route resolves, and the downstream twins once forwarded. close undoes all of it exactly once (cancels calls downstream, drops what waits for the origin, releases the downstream hold, rejects waiters).

type ReleaseFrame

type ReleaseFrame struct{ ID int }

func (ReleaseFrame) T

func (ReleaseFrame) T() string

type Reload

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

Reload is one reload on one host: prepare (load, prepare, gate), then commit or rollback (Pi reload.ts:147-659). Its state is touched on the host's loop.

type ReloadOptions

type ReloadOptions struct {
	// Remove names the facets to remove.
	Remove []string
	// GateDeadline is how long the gate waits for grandfathered roots. Missed: the reload aborts.
	GateDeadline *time.Duration
	// RetireDeadline is how long to wait for the previous code version to retire first. Missed: it is retired anyway.
	RetireDeadline *time.Duration
	// Remote is, on a server, the facet modules for child hosts by host-name prefix (longest wins). Every connected
	// host participates.
	Remote map[string][]string
	// RemoteRemove is, on a server, the facet names to remove on child hosts, by the same host-name prefix rules.
	RemoteRemove map[string][]string
	// VoteDeadline is, on a server, how long to wait for every child's vote.
	VoteDeadline *time.Duration
}

ReloadOptions are the options of HostImpl.Reload (Pi reload.ts:21-34). A nil deadline is Pi's undefined (5000 ms; the vote deadline defaults to gate + retire + 5000 ms); a nil map is undefined.

type ReloadReport

type ReloadReport struct {
	CodeVersion int
	Previous    int
	Changed     []string
	Removed     []string
	// Prepared are the addresses of objects whose new factory was installed.
	Prepared []string
	// Gated are the addresses of objects that went through the gate.
	Gated []string
	// Children is, for cluster reloads, what each participating child host prepared, by host name (its vote; the child
	// commits it after the server). Nil for local reloads.
	Children map[string]ReloadReport
}

ReloadReport is what a reload committed (Pi reload.ts:36-50).

type RemoteBinding

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

RemoteBinding is one hold per host and key (type, normalized input, principal key, contract fingerprint), shared by every reference to it: one hold over the link, one stream per state member, calls over the same hold. References are views onto it.

A hold implies the state of its variant (unless no view wants state): the provider answers with a unit, the shape followed by a snapshot of each state member the binding lacks. A shape is applied only once all of its snapshots are here, so a live binding always has every state member of its variant. After the first hydration the values stay readable while the binding re-holds (link loss): status loading, last values kept.

type RemoteChannel

type RemoteChannel interface {
	// contains filtered or unexported methods
}

RemoteChannel is what a binding needs from the link it is bound to (implemented by *Connection). Its methods run on the loop; call's promise settles with the result.

type RemoteDef

type RemoteDef struct {
	Version  int
	Input    Schema
	Host     Placement
	Variants Fields[VariantDef]
}

RemoteDef defines a remote contract. Variants are in declaration order. Host is required: where its objects live.

type RemoteRef

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

RemoteRef is a reference to an object on another host: a view onto the host's shared binding for its key. Each view has its own owner, status, observers and Release; ending by the provider and re-holding belong to the binding.

func (*RemoteRef) Contract

func (ref *RemoteRef) Contract() *Contract

Contract is the consumer contract token this reference was bound with.

func (*RemoteRef) Err

func (ref *RemoteRef) Err() (err error)

func (*RemoteRef) Member

func (ref *RemoteRef) Member(name string) (member any)

Member is a member by name: a method (methodFunc), a state member (Readable[any]) or nil.

func (*RemoteRef) OnShape

func (ref *RemoteRef) OnShape(listener func(shape Shape)) func()

func (*RemoteRef) OnStatus

func (ref *RemoteRef) OnStatus(listener func(status RefStatus, err error)) func()

func (*RemoteRef) Ready

func (ref *RemoteRef) Ready(ctx context.Context) error

func (*RemoteRef) Release

func (ref *RemoteRef) Release()

func (*RemoteRef) Shape

func (ref *RemoteRef) Shape() (shape *Shape)

func (*RemoteRef) Status

func (ref *RemoteRef) Status() (status RefStatus)

func (*RemoteRef) Variant

func (ref *RemoteRef) Variant() (variant *string)

type Resource

type Resource[T any] interface {
	Key() string
	// Value is the opened value; the error is not_ready until it is opened.
	Value() (T, error)
}

Resource is an object's opened resource.

type ResourceDeclaration

type ResourceDeclaration[T any] struct {
	// Version is bumped to replace the resource at the next reload (a native value has no schema to detect a change).
	Version int
	// Deps are references or resources that must be live/open first; a change replaces the resource. Nil is undefined.
	Deps []any
	// Exclusive resources are replaced at the gate: old closed before new opened. Pi reads `exclusive === true`, so
	// false and undefined are the same.
	Exclusive bool
	// Open opens the resource. Pi awaits its `T | Promise<T>`, so it is a blocking call; a throw or rejection is the
	// error.
	Open func(options ResourceOpenOptions) (T, error)
	// Close is optional: nil is undefined. Pi awaits it; a throw or rejection is the error.
	Close func(value T) error
}

ResourceDeclaration is what Self.Resource declares: something the object opens and later closes (a database, a watch, a socket).

type ResourceDeclarer

type ResourceDeclarer interface {
	// contains filtered or unexported methods
}

ResourceDeclarer is a ResourceDeclaration of any value type: what Self.Resource takes, as Pi's generic `resource<T>(name, declaration: ResourceDeclaration<T>)`.

type ResourceImpl

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

ResourceImpl is one declared resource of an object.

func (*ResourceImpl) Key

func (resource *ResourceImpl) Key() string

Key is the resource's declared name.

func (*ResourceImpl) Value

func (resource *ResourceImpl) Value() (value any, err error)

Value is the open resource's value; it fails not_ready until opened.

type ResourceOpenOptions

type ResourceOpenOptions struct {
	Signal context.Context
}

ResourceOpenOptions is the argument of ResourceDeclaration.Open (`{ readonly signal: AbortSignal }`).

type ResultFrame

type ResultFrame struct {
	ID       int
	Value    any
	HasValue bool
	Error    *WireError
}

func (ResultFrame) T

func (ResultFrame) T() string

type ResyncFrame

type ResyncFrame struct {
	Hold int
	M    string
}

ResyncFrame sends member M again as a reset (a relay that had to drop what waited for it).

func (ResyncFrame) T

func (ResyncFrame) T() string

type RetireFrame

type RetireFrame struct{ CodeVersion int }

RetireFrame: the parent dropped CodeVersion, so roots of it may no longer come from there.

func (RetireFrame) T

func (RetireFrame) T() string

type RootEndFrame

type RootEndFrame struct{ RootID string }

RootEndFrame: the root ended at its origin, so its leases on objects end (sent on every link the root's calls used).

func (RootEndFrame) T

func (RootEndFrame) T() string

type RootOptions

type RootOptions struct {
	// Principal is nil for the host principal.
	Principal Principal
	// Signal cancels the root; nil never cancels.
	Signal context.Context
	// CodeVersion starts the root in a retained code version (links carry code versions); nil is the current code version.
	CodeVersion *int
}

RootOptions are Root's options.

type RootRef

type RootRef struct {
	RootID      string
	CodeVersion int
}

RootRef names a root at its origin.

type Route

type Route struct {
	// Authorize is checked before resolving (or spawning) and again after: grants may change meanwhile.
	Authorize func(principal Principal, hostName string) (bool, error)
	// Resolve is a link to the host, spawned if needed.
	Resolve func(hostName string) (Link, error)
	// Principal is the principal the resolved host acts as when it calls back. Required: Route panics with a TypeError
	// when it is nil.
	Principal func(hostName string) Principal
}

Route is where requests for hosts named `prefix…` go (on the server).

type Run

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

Run is one factory run: its implementation, declarations and the objects it created.

type Schema

type Schema = *pischema.Object

Schema is JSON Schema as data: pi-schema's builders, or any JSON Schema object (a nil Schema is `undefined`). The object keeps the order its members were declared in, as a JavaScript object does. Nested schemas are *Object, or map[string]any when a caller built them as maps.

type Self

type Self interface {
	// State declares a state cell named name: its schema (required: there is no TypeScript at runtime) and its initial
	// value (validated), or a StateInit to read the first value from its source before the object goes live. The name
	// identifies the cell across reloads: a reload keeps the cell and its value (initial is ignored, Init does not run),
	// migrates it when its version rises, and refuses a schema change without a version bump. A cell a reload adds runs
	// its Init while the reload prepares. options nil is Pi's undefined.
	State(name string, schema Schema, initial any, options *StateOptions) (*Cell[any], error)
	// Get makes an object-owned reference, identified by its address.
	Get(typ *Contract, input any, options *GetOptions) (Ref, error)
	// Resource declares a resource named name: opened before the object goes live, closed after it is disposed. A reload
	// keeps it unless its Version, Deps or Exclusive changed. declaration is a ResourceDeclaration.
	Resource(name string, declaration ResourceDeclarer) (Resource[any], error)
	// On reacts to source once the object is live: a readable (cell, derivation, reference state member) delivers its
	// current value, then every new value; an event source (or a resource whose value is one) delivers its events. Each
	// event runs handler in a fresh root. The name keeps the subscription across reloads while its source and select are
	// unchanged; a listener on state whose source the reload replaced (a derivation is new at every reload) subscribes
	// again and gets the current value again, so a handler of state must reconcile, not count.
	On(name string, source any, handler func(event any, ctx Ctx) error) error
	// OnSelect is On with select: it subscribes to select(value) instead (the opened value for a resource).
	OnSelect(name string, source any, selector func(value any) Subscribable[any], handler func(event any, ctx Ctx) error) error
	// Task declares long-running work of the live object (a code holder: its calls start fresh roots), restarted at
	// every reload.
	Task(fn func(ctx Ctx) error) error
	// Derive declares a synchronous projection of readables, recomputed when they change; a new one at every reload.
	Derive(sources Sources, fn func(values ...any) any) (Readable[any], error)
	// Register registers entries in registry. Objects of LifetimeHost only; keys are the registry's own keys.
	Register(registry Registry[any], entries []Entry) error
	// Expose is a member backed by one of this object's resources, for local contracts: references read the resource's
	// value once the object is live (nil before).
	Expose(resource Resource[any]) (Exposed, error)
}

Self is the factory's `self`: how a factory declares the object's state, references, resources, listeners, tasks, derivations, registrations and exposed resources.

type SelfImpl

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

SelfImpl is the self one factory run gets.

func (*SelfImpl) Derive

func (s *SelfImpl) Derive(sources Sources, fn func(values ...any) any) (Readable[any], error)

Derive declares a derivation, by position: new at every run.

func (*SelfImpl) Expose

func (s *SelfImpl) Expose(resource Resource[any]) (Exposed, error)

Expose is a member backed by one of this object's resources.

func (*SelfImpl) Get

func (s *SelfImpl) Get(typ *Contract, input any, options *GetOptions) (Ref, error)

Get makes an object-owned hold.

func (*SelfImpl) On

func (s *SelfImpl) On(name string, source any, handler func(event any, ctx Ctx) error) error

On declares a listener named name.

func (*SelfImpl) OnSelect

func (s *SelfImpl) OnSelect(name string, source any, selector func(value any) Subscribable[any], handler func(event any, ctx Ctx) error) error

OnSelect declares a listener named name that subscribes to selector(value).

func (*SelfImpl) Register

func (s *SelfImpl) Register(registry Registry[any], list []Entry) error

Register registers entries in registry (objects of LifetimeHost only).

func (*SelfImpl) Resource

func (s *SelfImpl) Resource(name string, declaration ResourceDeclarer) (Resource[any], error)

Resource declares a resource named name.

func (*SelfImpl) State

func (s *SelfImpl) State(name string, schema Schema, initial any, options *StateOptions) (*Cell[any], error)

State declares a state cell (on the loop: the factory runs there).

func (*SelfImpl) Task

func (s *SelfImpl) Task(fn func(ctx Ctx) error) error

Task declares a task, by position.

type Serve

type Serve func(typ *Contract, factory Factory, options ServeOptions) error

Serve registers a factory for a type (Pi's overloaded Serve over remote and local contracts).

type ServeOptions

type ServeOptions struct {
	// Lifetime is how long objects of the type live; empty is LifetimeReferenced.
	Lifetime Lifetime
	// Linger is how long an object stays alive after its last reference is released (LifetimeReferenced only).
	Linger time.Duration
	// HasLinger is true when Linger is present: Pi's `linger !== undefined`, which LifetimeHost refuses even for 0.
	HasLinger bool
	// Accepts are adapters for consumers built against older contract versions.
	Accepts Accepts
}

ServeOptions are the options of serving a contract. Nil and zero members are absent. LifetimeHost is for local types whose input accepts `{}`; every get reaches the one object, created for the host principal. Only such objects may register into registries. Pi's types refuse the rest at compile time (ServeOptionsFor); Go has no type-level check, so Serve refuses a remote type, an input that does not accept `{}` and a Linger at runtime.

type Service

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

Service is a served contract: its factory, options and the facet that serves it.

type Shape

type Shape struct {
	// Variant is the variant; nil is Pi's undefined.
	Variant *string
	Members []string
	// Contract is the fingerprint of the provider contract.
	Contract string
}

Shape is the provider's shape for a reference (types.ts:55-61).

type ShapeFrame

type ShapeFrame struct {
	ID int
	// Variant is nil for a local contract.
	Variant  *string
	Members  []string
	Contract string
	// State lists the state members whose snapshots follow this frame; the consumer applies the shape once they
	// are here.
	State []string
}

func (ShapeFrame) T

func (ShapeFrame) T() string

type Source

type Source[T any] struct {
	Key string
	Seq int64
	// Dependents are the derivations computed from this source (Pi's dependents Set).
	Dependents *dependents
	// Schemas are the schemas of remote state members currently exposing this source (checked per write in dev mode).
	Schemas []Schema
	// contains filtered or unexported fields
}

Source is cell.ts Source, the abstract object-owned state source (cell or derivation). Cell and Derived embed it.

func (*Source[T]) Events

func (source *Source[T]) Events(listener func(StateEvent[T])) func()

Events calls listener with a snapshot now and with every later delta event.

func (*Source[T]) Subscribe

func (source *Source[T]) Subscribe(listener func(T)) func()

Subscribe calls listener with the current value now and with every later value.

func (*Source[T]) Validate

func (source *Source[T]) Validate(value any) error

Validate is the per-write validation, dev mode only.

type SourceOptions

type SourceOptions struct {
	Dev    bool
	Report func(err error)
	// Exec runs one write (change or replace) as a single section of the owning host's loop; nil runs it in the caller.
	// Upstream's writes are synchronous on one thread, so methods and tasks that write from several goroutines must not
	// interleave a write's read of the current revision with another write's commit.
	Exec func(write func())
	// contains filtered or unexported fields
}

SourceOptions is cell.ts SourceOptions.

type Sources

type Sources = []Readable[any]

Sources is cell.ts Sources: the readables a derivation is computed from.

type StagedListeners

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

StagedListeners are listener subscriptions made ahead of a commit: activate switches over, discard drops them.

type StateEvent

type StateEvent[T any] struct {
	// Type is StateEventSnap, StateEventOps or StateEventReset.
	Type  StateEventType
	Value T
	// Ops are set for StateEventOps only.
	Ops []delta.Op
}

StateEvent is one event of a delta stream (types.ts:26-29): a snapshot, ops with the value after them, or a reset after a migration or rebind.

type StateEventType

type StateEventType string

StateEventType is the discriminator of a StateEvent (types.ts:26-29): the closed union "snap" | "ops" | "reset".

const (
	StateEventSnap  StateEventType = "snap"
	StateEventOps   StateEventType = "ops"
	StateEventReset StateEventType = "reset"
)

StateEvent types (types.ts:26-29).

type StateFrame

type StateFrame struct {
	Hold int
	M    string
	As   string
	// Value is a snap or reset's value; HasValue false is `undefined`.
	Value    any
	HasValue bool
	// Ops are encoded with the stream's delta encoder; nil is absent.
	Ops   []delta.WireOp
	Error *WireError
}

StateFrame is a state member's frame, addressed by hold and member. As is "snap", "reset", "ops" or "error".

func (StateFrame) T

func (StateFrame) T() string

type StateInit

type StateInit struct {
	Init func(ctx Ctx) (any, error)
}

StateInit is object.ts StateInit: a cell's first value from its source. Pass it as the initial value of Self.State. Init runs after the object's resources are open and its references are live, before the object goes live, so no call, listener or subscriber sees a value that is not from the source. It runs in a root of its own (acting as the host's own principal) and may block; the inits of one object run in parallel. Its value is validated against the schema; an error or an invalid value fails the activation. A Go value is never a StateInit unless it is one, as a JSON value never holds a function.

type StateOptions

type StateOptions struct {
	// Version is the meaning of the cell's value; 0 is the default 1. A reload that raises it runs Migrate.
	Version int
	// Migrate maps the value of an older version (from) to this version's, at the reload that raised the version. The
	// cell may be several versions behind. Without it, the value is kept and must fit the new schema.
	Migrate func(old any, from int) (any, error)
}

StateOptions are the options of Self.State.

type StateSink

type StateSink = StateFrame

StateSink is a state frame as a binding receives it (its hold and member select the binding and the stream).

type SubFrame

type SubFrame struct{ Hold int }

SubFrame starts the state of a hold opened with NoState (answered with a unit).

func (SubFrame) T

func (SubFrame) T() string

type Subscribable

type Subscribable[E any] interface {
	// Subscribe registers listener and returns the unsubscribe function.
	Subscribe(listener func(event E)) func()
}

Subscribable is an event source.

type TypeError

type TypeError struct{ Message string }

TypeError is a contract definition error, thrown where upstream throws a TypeError. Remote, Local and Opaque panic with it: contracts are package-level definitions, as upstream's are module-level constants.

func (*TypeError) Error

func (err *TypeError) Error() string

type UnsubFrame

type UnsubFrame struct{ Hold int }

UnsubFrame stops the state of a hold.

func (UnsubFrame) T

func (UnsubFrame) T() string

type UpstreamOptions

type UpstreamOptions struct {
	Link Link
	ConnectOptions
}

UpstreamOptions are HostOptions.Upstream: the link to the parent with Connect's options.

type VariantDef

type VariantDef struct {
	State   Fields[Schema]
	Methods Fields[MethodSpec]
}

VariantDef is one variant of a remote contract: its state members, then its methods, each in declaration order.

type VoteFrame

type VoteFrame struct {
	Reload int
	Error  *WireError
	Report *WireReloadReport
}

func (VoteFrame) T

func (VoteFrame) T() string

type WebSocketAcceptOptions

type WebSocketAcceptOptions[Request any] struct {
	LinkOptions
	// Restamp is AcceptOptions.Restamp: on invalidatePrincipal a new principal keeps the link, false closes it.
	Restamp func(principal Principal) (Principal, bool)
	// MaxCalls is AcceptOptions.MaxCalls: the calls the client may have in progress on its link (nil: no limit); further
	// ones are answered at once with unavailable (reason too_many_calls).
	MaxCalls *int
	// Principal is the authenticator: the principal of the connecting client, or false to refuse it. An error is a
	// failed authentication. It may block; acceptWebSockets calls it off the server's connection listener, as Pi
	// resolves the authenticator's result asynchronously.
	Principal func(request Request) (Principal, bool, error)
}

WebSocketAcceptOptions are AcceptOptions without principal, kind and name: WebSocket peers are always accepted as clients, so they have no roots, no code versions, no reload votes and are not addressable (Pi websocket.ts:11-15).

type WebSocketLike

type WebSocketLike interface {
	ReadyState() int
	// Send sends a string as a text message and a []byte as a binary message.
	Send(data any) error
	// Close closes the socket; code 0 and reason "" are absent.
	Close(code int, reason string)
	// AddEventListener adds listener for "message" (called with the message: a string for a text message, a []byte
	// for a binary one, as binaryType "arraybuffer") or "open", "close" and "error" (called with a zero
	// WebSocketMessage).
	AddEventListener(typ string, listener func(event WebSocketMessage))
}

WebSocketLike is the WHATWG WebSocket surface.

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

WebSocketLink is a link over a WebSocket.

func NewWebSocketLink(socket WebSocketLike, options WebSocketLinkOptions) *WebSocketLink

NewWebSocketLink is Pi's webSocketLink.

func (*WebSocketLink) Close

func (link *WebSocketLink) Close(reason ...string)

func (*WebSocketLink) Closed

func (link *WebSocketLink) Closed() bool

func (*WebSocketLink) OnClose

func (link *WebSocketLink) OnClose(handler func(reason string))

OnClose registers handler; on a closed link it is called at once with "closed" (link.ts:38-41). Handlers are a set, as Pi's: the same func value registered again is not added twice. Identity is the func value itself (funcID), so it is the same handler only when the same value is passed again, as Pi's function identity.

func (*WebSocketLink) Receive

func (link *WebSocketLink) Receive(handler func(frame Frame))

func (*WebSocketLink) Send

func (link *WebSocketLink) Send(frame Frame) (int, error)

type WebSocketLinkOptions

type WebSocketLinkOptions struct {
	// Compress deflates large payloads of outgoing frames (default false; the server's side of client sockets).
	Compress bool
	// AcceptPacked accepts packed (binary) frames from the peer (nil: true; false for a server's untrusted clients).
	AcceptPacked *bool
}

WebSocketLinkOptions are link.ts WebSocketLinkOptions.

type WebSocketMessage

type WebSocketMessage struct{ Data any }

WebSocketMessage is the event of a WebSocket "message" listener.

type WebSocketServerLike

type WebSocketServerLike[Request any] interface {
	On(event string, listener func(socket WebSocketLike, request Request))
}

WebSocketServerLike is a WebSocket server (e.g. `ws`'s WebSocketServer), structurally: Chord does not depend on a WebSocket library (Pi websocket.ts:6-9). On registers listener for event; acceptWebSockets registers "connection".

type WireError

type WireError struct {
	Code    ChordErrorCode
	Message string
	Reason  string
}

WireError is a ChordError on the wire; Reason is empty when absent.

func ToWireError

func ToWireError(err error) WireError

ToWireError is wire.ts toWireError. As upstream's instanceof, it does not look through a wrapper: an AggregateError of ChordErrors is unavailable with the aggregate's message.

type WireReloadOptions

type WireReloadOptions struct {
	Remove         []string
	GateDeadline   *float64
	RetireDeadline *float64
}

WireReloadOptions are the reload options a parent sends with prepare; nil fields are absent.

type WireReloadReport

type WireReloadReport struct {
	CodeVersion int
	Previous    int
	Changed     []string
	Removed     []string
	Prepared    []string
	Gated       []string
}

WireReloadReport is a child's prepared reload, sent with its vote (the fields of ReloadReport, without children).

type WriteGuard

type WriteGuard func(ctx Ctx) error

WriteGuard is cell.ts WriteGuard: it checks that ctx may write an object's cells now and returns the refusal.

Jump to

Keyboard shortcuts

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