chord

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package chord is the local Go runtime for the subset of Pi 0.87.1's packages/chord that the experimental service graph consumes: replicated state, the remote service provider and its endpoint, the operation-stream replica binding, and JSON-copy transports.

Upstream source: .upstream/v0.87.1/packages/chord/src/{types,api}.ts and services/{state,provider,consumer,instances,wire,errors,loopback}.ts. packages/chord is outside PORT_MAP package scope (see docs/parity/PORT_MAP.md); this package exists so experimental service lanes share one concrete runtime instead of consumer-owned stand-ins.

Go mapping decisions (not wire changes):

  • Chord's Context is context.Context. Synthetic deliveries (hydration, provider lifecycle) use context.Background(), matching upstream's BACKGROUND_CONTEXT.
  • Service tokens are pico3.ServiceDefinition[T] created by pico3.DefineService; this package does not define a second token type.
  • Replicated state satisfies pico3.ReplicatedStateOf[T] and pico3.MutableReplicatedStateOf[T]. A state value is stored as its strict JSON representation; Value returns a detached decoded copy, which is the Go equivalent of upstream's immutable revisions.
  • Operations are pico3.Op tuples (the chord/delta vocabulary already ported in agent/harness/pico3/delta.go). Operation shape is not canonical upstream either; consumers depend only on the resulting value.
  • A provider classifies a Go implementation by reflection over the service type's method set. Member names are the method names with a lower-case first letter ("CycleThinking" -> "cycleThinking"), which is the upstream TypeScript member name. A method member has the signature func(context.Context, args...) error or func(context.Context, args...) (R, error); a state member takes no arguments and returns a replicated state created by NewReplicatedState.
  • Go cannot synthesize a typed proxy, so the consumer side exposes an untyped RemoteService facade (Call, State, CallResult). Typed client adapters over that facade belong to the owning service lane, which registers them with RegisterRemoteClient (or passes FacetOptions.RemoteClients). A facet host needs one for every remotely exposable singleton a facet uses: in-host ones go through the host's internal loopback binding, as upstream, so retained state subscriptions follow provider replacement. Keyed in-host observation still resolves through the local registry.
  • Value accessors on state handles panic with the access error after revocation (upstream throws); Load returns it.
  • Facets require a guarded service view registered with RegisterServiceView next to the contract's pico3.DefineService token, including for in-host services. Register once before acquiring or observing the service. Every method invocation must resolve the current target and check access; never cache the resolved implementation. State members use StateView. A missing registration fails Get or observation instead of exposing the raw implementation.
  • Mutate callbacks receive a detached decoded copy of the state rather than upstream's revocable copy-on-write Draft proxy.

ServiceStateEncoder and ServiceStateDecoder maintain independent path dictionaries per subscription, instance, and state member. ParseService* and ParseWireService* validate their distinct tuple grammars before conversion. The JSON-copy transport remains local; framed routing supplies a separate transport boundary.

Index

Constants

View Source
const (
	DeliveryHydrate = "hydrate"
	DeliveryUpdate  = "update"
)

Delivery kinds carried by pico3.ReplicatedStateDelivery.Kind.

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

Service member kinds.

View Source
const (
	UpdateState       = "state"
	UpdateUnavailable = "unavailable"
	UpdateReplaced    = "replaced"
	UpdateSpawned     = "spawned"
	UpdateClosed      = "closed"
)

Provider update types.

Variables

View Source
var ErrInvocationAdmissionUnavailable = errors.New("Remote service transport does not expose invocation admission")

ErrInvocationAdmissionUnavailable reports a transport or implementation without an explicit Promise admission boundary.

Functions

func AdaptRemoteClient

func AdaptRemoteClient[T any](definition pico3.ServiceDefinition[T], service *RemoteService) (T, error)

AdaptRemoteClient applies the same registered typed facade used by a FacetHost to an explicitly opened remote service. Go cannot synthesize TypeScript's generic service proxy from a type parameter.

func AssertFacetRunning

func AssertFacetRunning(env *FacetEnvironment, operation string) error

AssertFacetRunning applies the existing lifecycle guard before an isolated environment creates mutable state.

func AssertFacetSettingUp

func AssertFacetSettingUp(env *FacetEnvironment, operation string) error

AssertFacetSettingUp applies the shared setup-only declaration guard before a foreign bridge materializes a declaration.

func AssertValidOp

func AssertValidOp(value any) error

AssertValidOp validates decoded tuples without recursively inspecting payload objects.

func AssertValidWireOp

func AssertValidWireOp(value any) error

AssertValidWireOp validates the distinct path-reference/short-form vocabulary and all index/permutation constraints.

func CallResult

func CallResult[R any](ctx context.Context, service *RemoteService, member string, args ...any) (R, error)

CallResult invokes member and decodes its JSON result into R.

func ContinueObservation

func ContinueObservation(ctx context.Context, continuation func() error)

ContinueObservation runs the settlement of a keyed observation handler's returned Promise: instances.ts#start leaves that Promise unawaited and reports its rejection unless the observation was cancelled. ctx must be the observation Context passed to the handler; it cancels nothing by itself, so continuation must stop when ctx is done.

func CurrentGoroutineID

func CurrentGoroutineID() uint64

CurrentGoroutineID identifies the current internal owner for synchronous reentry checks. It is not a wire identity, a persisted value or an application identifier.

func IsRemoteServiceErrorCode

func IsRemoteServiceErrorCode(err error, code RemoteServiceErrorCode) bool

IsRemoteServiceErrorCode reports whether err is a RemoteServiceError with code.

func ObserveFacetService

func ObserveFacetService(env *FacetEnvironment, serviceId string, local bool, handler func(context.Context, *FacetService) error) error

ObserveFacetService acquires a keyed service for an isolated facet. Each observed handle checks the owning facet and observation lifetime on every resolution. Remote in-host observations use the same loopback binding as external remote observations.

func ObserveRemote

func ObserveRemote[T any](binding *RemoteServiceBinding, def pico3.ServiceDefinition[T], handler func(context.Context, *RemoteService) error) (func(), error)

ObserveRemote observes each live instance of keyed service def. The handler runs synchronously within the delivery that admits the instance, before that snapshot or update completes, with a context cancelled when the instance closes, is replaced by a newer generation, or the observation stops. It must not block on that delivery; work that outlives the call runs in a task the handler owns and ties to the context. The returned stop function is idempotent.

func ObserveService

func ObserveService[T any](env *FacetEnvironment, def pico3.ServiceDefinition[T], handler func(context.Context, T) error) error

ObserveService declares a hard dependency on keyed def. After activation, handler runs synchronously within the delivery that admits each live instance, with a context cancelled when that instance closes or the facet is disposed. It must not block on that delivery; work that outlives the call runs in a task the handler owns and ties to the context.

func Provide

func Provide[T any](provider *RemoteServiceProvider, def pico3.ServiceDefinition[T], implementation T) error

Provide installs the singleton implementation of def.

func ProvideService

func ProvideService[T any](env *FacetEnvironment, def pico3.ServiceDefinition[T], implementation T) error

ProvideService declares and installs this facet's singleton implementation of def. Remote (non-local) implementations are classified immediately.

func RegisterRemoteClient

func RegisterRemoteClient[T any](def pico3.ServiceDefinition[T], adapter func(*RemoteService) T)

RegisterRemoteClient registers the typed client adapter for def: a T whose methods call the remote facade (Call/CallResult/State). A facet host uses it for remotely exposable services, in-host (through its internal loopback binding, as upstream) and from external sources. FacetOptions.RemoteClients overrides it per host. Registering the same service twice panics.

func RegisterServiceView

func RegisterServiceView[T any](def pico3.ServiceDefinition[T], view func(resolve func() (T, error)) T)

RegisterServiceView registers the guarded view for def. view must return a T whose methods call resolve on every invocation and never cache its result. Registering the same service twice panics.

func Replace

func Replace[T any](provider *RemoteServiceProvider, def pico3.ServiceDefinition[T], implementation T) error

Replace swaps a singleton implementation without making the stable remote facade unavailable; subscribers receive "replaced" with a new snapshot.

func Spawn

func Spawn[T any](provider *RemoteServiceProvider, def pico3.ServiceDefinition[T], key string, implementation T) (func() error, error)

Spawn publishes one keyed instance at the next generation for key. The returned close function is idempotent, including from a lifecycle listener, and closes only this generation.

func StateView

func StateView[T any](resolve func() (pico3.ReplicatedStateOf[T], error)) pico3.ReplicatedStateOf[T]

StateView is the guarded counterpart of a replicated state member for service views: Value and Subscribe resolve the current state on each call. Value panics with the resolution error (revoked access, disconnected service) because upstream's value property throws and Value has no error result; Subscribe returns the error.

func Use

func Use[T any](provider *RemoteServiceProvider, def pico3.ServiceDefinition[T]) (T, error)

Use returns the local singleton implementation of def.

func UseRemoteClient

func UseRemoteClient[T any](binding RemoteServices, definition pico3.ServiceDefinition[T]) (T, error)

UseRemoteClient acquires a singleton and returns its registered typed client view without bypassing binding access/readiness checks.

func ValidateReplacement

func ValidateReplacement[T any](provider *RemoteServiceProvider, def pico3.ServiceDefinition[T], implementation T) error

ValidateReplacement checks a singleton replacement without changing the active provider.

func Withdraw

func Withdraw[T any](provider *RemoteServiceProvider, def pico3.ServiceDefinition[T]) error

Withdraw disconnects a singleton while preserving subscriptions; subscribers receive "unavailable".

Types

type AggregateError

type AggregateError struct {
	Message string
	Errors  []any
}

AggregateError retains every failure while exposing the upstream aggregate message, as JavaScript's AggregateError(errors, message) does: Error() is the message alone and the causes are reachable through Unwrap.

func NewAggregateError

func NewAggregateError(message string, failures []error) *AggregateError

NewAggregateError builds an AggregateError over failures in order.

func (*AggregateError) Error

func (err *AggregateError) Error() string

func (*AggregateError) Unwrap

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

Unwrap exposes each cause that is an error to errors.Is and errors.As.

type BindingWait

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

BindingWait is an already-started binding operation. The caller owns any goroutine waiting for it; constructing it never detaches a waiter.

func (*BindingWait) Settled

func (waiting *BindingWait) Settled() (bool, error)

func (*BindingWait) Wait

func (waiting *BindingWait) Wait() error

type Decoder

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

Decoder retains defined path IDs across batches. A replacement clears the dictionary; path omission never crosses a batch boundary.

func NewDecoder

func NewDecoder() *Decoder

func (*Decoder) Decode

func (d *Decoder) Decode(wire []WireOp) ([]pico3.Op, error)

type Encoder

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

Encoder owns the path dictionary for one ordered state stream.

func NewEncoder

func NewEncoder() *Encoder

func (*Encoder) Encode

func (e *Encoder) Encode(ops []pico3.Op) ([]WireOp, error)

type Facet

type Facet struct {
	Id    string
	Setup func(env *FacetEnvironment) error
}

Facet is one unit of composition (upstream Facet). Setup declares the facet's service requirements and provisions synchronously; it must not start work, which belongs in OnActivate.

func DefineFacet

func DefineFacet(facet Facet) Facet

DefineFacet returns facet unchanged (upstream defineFacet).

type FacetEnvironment

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

FacetEnvironment is passed to Facet.Setup (upstream FacetEnvironment). The generic operations are package functions: ProvideService, ProvideMany, UseService and ObserveService.

func (*FacetEnvironment) OnActivate

func (env *FacetEnvironment) OnActivate(callback func(context.Context) error) error

OnActivate registers initialization run after dependencies are bound.

func (*FacetEnvironment) OnDeactivate

func (env *FacetEnvironment) OnDeactivate(callback func(context.Context) error) error

OnDeactivate registers final teardown (upstream: same as own).

func (*FacetEnvironment) Own

func (env *FacetEnvironment) Own(disposal func(context.Context) error) error

Own gives the facet ownership of a cleanup, run in reverse order when the facet is disposed or replaced.

type FacetHost

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

FacetHost is an active facet generation (upstream FacetHost).

func CreateFacetHost

func CreateFacetHost(ctx context.Context, options FacetOptions) (*FacetHost, error)

CreateFacetHost sets up, validates, assembles and activates facets in dependency order. Binding readiness uses a background context. On failure everything already set up is disposed.

func (*FacetHost) Dispose

func (host *FacetHost) Dispose(ctx context.Context) error

Dispose disposes facets in reverse activation order, then services.

func (*FacetHost) Reload

func (host *FacetHost) Reload(ctx context.Context, facets []Facet) error

Reload activates replacements for facets with matching IDs and cuts over their provisions without disconnecting consumer handles.

func (*FacetHost) Services

func (host *FacetHost) Services() *RemoteServiceProvider

Services is the host's remote service provider, for an endpoint.

type FacetLoader

type FacetLoader interface {
	Load(ctx context.Context) (LoadedFacets, error)
}

FacetLoader loads a facet set (upstream FacetLoader).

func CombineFacetLoaders

func CombineFacetLoaders(loaders ...FacetLoader) FacetLoader

CombineFacetLoaders loads each loader in order. A load failure releases the already loaded sets in reverse order. The combined release runs once and releases every set in reverse order; repeated or reentrant calls return immediately.

func CreateStaticFacetLoader

func CreateStaticFacetLoader(facets []Facet) FacetLoader

CreateStaticFacetLoader always loads the same facets with a no-op release.

type FacetOptions

type FacetOptions struct {
	Facets []Facet
	// ServiceSources offer external services for requirements no facet
	// provides (upstream serviceSources).
	ServiceSources []RemoteServiceSource
	// RemoteClients adapts an external service facade to the Go contract T a
	// facet receives from UseService/ObserveService, keyed by service ID. Go
	// cannot synthesize upstream's typed proxy; the owning service lane
	// supplies the adapter.
	RemoteClients map[string]func(*RemoteService) any
	// OnError receives asynchronous observer and binding errors.
	OnError func(error)
}

FacetOptions configures CreateFacetHost.

type FacetReplicaIdentity

type FacetReplicaIdentity replicaCore

FacetReplicaIdentity is the opaque identity of one underlying state replica across guarded consumer views.

type FacetService

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

FacetService is an invocation-time view for an isolated facet whose service contract is known only at runtime. Resolve checks the same generation and facet access guards as a typed ServiceRef. The returned implementation is borrowed for that invocation; callers must not cache it across a reload.

func UseFacetService

func UseFacetService(env *FacetEnvironment, serviceId string, local bool) (*FacetService, error)

UseFacetService acquires a singleton for an isolated facet without requiring a compile-time Go service interface. Native consumers retain their registered typed adapters; otherwise remote services use their actual RemoteService facade.

func (*FacetService) Remote

func (service *FacetService) Remote() (*RemoteService, error)

Remote returns the real binding behind a dynamic remote service, retaining its initiating-transport capability and the holder's facet/observation guards. Native typed adapters remain the result of Resolve and are not replaced.

func (*FacetService) Resolve

func (service *FacetService) Resolve() (any, error)

Resolve returns the current service implementation after checking the holder's lifetime.

type FacetServiceImplementation

type FacetServiceImplementation struct {
	Members []FacetServiceMember
}

FacetServiceImplementation carries a runtime method/state inventory through the existing provider's install, replace and spawn paths. Callbacks belong to the isolated loaded generation.

type FacetServiceMember

type FacetServiceMember struct {
	Name   string
	Invoke func(context.Context, []json.RawMessage) (json.RawMessage, error)
	State  *FacetState
}

FacetServiceMember is one validated runtime-declared remote member. Exactly one of Invoke and State is present. The declaration owns neither a second provider nor a separate update stream.

type FacetState

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

FacetState imports the state of an isolated provider into the existing Chord state publication path. It preserves the source's sequence and operation batches rather than recomputing a different diff.

func NewFacetState

func NewFacetState(value pico3.JsonValue, sequence int) (*FacetState, error)

NewFacetState installs an initialized source snapshot. The loaded generation owns subsequent Apply calls and source-listener cleanup.

func (*FacetState) Apply

func (state *FacetState) Apply(ctx context.Context, sequence int, ops []pico3.Op) error

Apply publishes one gap-free source operation batch before returning to its producer. Listener failures surface after the value commits, as for native mutable state.

type InitiatingServiceTransport

type InitiatingServiceTransport interface {
	RemoteServiceTransport
	BeginInvoke(context.Context, ServiceCall) (*ServiceInvocation, error)
}

InitiatingServiceTransport exposes the Promise-returning invocation boundary without inferring it from a blocking Go method.

type LoadedFacets

type LoadedFacets struct {
	Facets  []Facet
	Dispose func(context.Context) error
}

LoadedFacets is one loaded facet set and its release function.

type MutableReplicatedState

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

MutableReplicatedState is upstream replicatedState(initial): initialized, publishable state suitable for exposing as a service member. It implements pico3.MutableReplicatedStateOf[T] and is safe for concurrent use.

Change and Replace serialize with each other. Calling Change or Replace on the same state from inside a mutate callback is rejected, as upstream. Listener failures are returned by the Change/Replace/Subscribe call that drained the delivery, after the value has been committed, as upstream.

func NewReplicatedState

func NewReplicatedState[T any](initial T) (*MutableReplicatedState[T], error)

NewReplicatedState creates state whose strict JSON representation is an object or array, as upstream's `T extends object`.

func (*MutableReplicatedState[T]) Change

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

Change applies mutate to a detached draft and atomically publishes the result. A mutate error or panic discards the draft and returns the failure. An unchanged draft publishes nothing.

func (*MutableReplicatedState[T]) Replace

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

Replace atomically publishes a complete detached value.

func (*MutableReplicatedState[T]) Sequence

func (state *MutableReplicatedState[T]) Sequence() int

Sequence is the number of committed publications.

func (*MutableReplicatedState[T]) Subscribe

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

Subscribe delivers a hydrate at the current sequence, then each later update in sequence order. A failing hydration unregisters the listener and returns its error.

func (*MutableReplicatedState[T]) Value

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

Value returns a detached copy of the current value.

type PathError

type PathError struct{ Path any }

PathError reports an unresolved path or dictionary reference.

func (*PathError) Error

func (e *PathError) Error() string

type RemoteService

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

RemoteService is a consumer facade over one remote service instance.

func UseRemote

func UseRemote[T any](binding *RemoteServiceBinding, def pico3.ServiceDefinition[T]) (*RemoteService, error)

UseRemote returns the stable singleton facade for def and, while bound, starts its subscription. Repeated calls return the same facade.

func (*RemoteService) Address

func (service *RemoteService) Address() *ServiceInstanceAddress

Address is the keyed instance address, or nil for a singleton.

func (*RemoteService) BeginCall

func (service *RemoteService) BeginCall(ctx context.Context, member string, args ...any) (*ServiceInvocation, error)

BeginCall applies the same access/member/value checks as Call, then returns only after transport admission. Transports without an explicit admission boundary are rejected, never emulated by a prematurely signalled goroutine.

func (*RemoteService) Call

func (service *RemoteService) Call(ctx context.Context, member string, args ...any) (json.RawMessage, error)

Call invokes method member with JSON-encodable arguments and returns the raw JSON result (nil for void).

func (*RemoteService) State

func (service *RemoteService) State(member string) (*ReplicatedStateReplica, error)

State returns the replica for state member. It is unhydrated until the subscription snapshot installs.

type RemoteServiceBinding

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

RemoteServiceBinding is the consumer side of remote services: stable service facades whose state members are hydrated replicas fed by the provider operation stream (upstream RemoteServiceBindingImpl).

func CreateRemoteServiceBinding

func CreateRemoteServiceBinding(options RemoteServiceBindingOptions) (*RemoteServiceBinding, error)

CreateRemoteServiceBinding creates a binding. Duplicate allowlist IDs are rejected.

func (*RemoteServiceBinding) BeginReady

func (binding *RemoteServiceBinding) BeginReady(ctx context.Context) *BindingWait

BeginReady captures the current hydration work synchronously. Cancellation rejects only this waiter, never the underlying subscriptions.

func (*RemoteServiceBinding) BeginRebind

func (binding *RemoteServiceBinding) BeginRebind(ctx context.Context, bound bool) *BindingWait

BeginRebind performs revision changes and replica fencing before returning. Its continuation joins all transitions, as upstream rebind's Promise.allSettled does.

func (*RemoteServiceBinding) Dispose

func (binding *RemoteServiceBinding) Dispose(ctx context.Context) error

Dispose closes every subscription exactly once and waits for pending starts. Later calls are no-ops.

func (*RemoteServiceBinding) Observe

func (binding *RemoteServiceBinding) Observe(serviceId string, handler func(context.Context, *RemoteService) error) (func(), error)

Observe is the untyped form of ObserveRemote for a transport-visible service ID.

func (*RemoteServiceBinding) Ready

func (binding *RemoteServiceBinding) Ready(ctx context.Context) error

Ready waits until every currently acquired service has installed its initial snapshot, repeating while new services are acquired concurrently.

func (*RemoteServiceBinding) Rebind

func (binding *RemoteServiceBinding) Rebind(ctx context.Context, bound bool) error

Rebind closes every subscription, clears replicas, and when bound resubscribes and rehydrates. It waits for every transition; context cancellation belongs to underlying operations, not this join.

func (*RemoteServiceBinding) Use

func (binding *RemoteServiceBinding) Use(serviceId string) (*RemoteService, error)

Use is the untyped form of UseRemote for a transport-visible service ID.

type RemoteServiceBindingOptions

type RemoteServiceBindingOptions struct {
	// Services is the allowlist of service IDs this binding may use.
	Services []string
	// Transport carries calls and subscriptions.
	Transport RemoteServiceTransport
	// Unbound starts the binding unbound (upstream bound: false).
	Unbound bool
	// OnError receives asynchronous subscription, replica and observer errors.
	OnError func(error)
	// AssertAccess guards every handle access (for example facet revocation).
	AssertAccess func() error
}

RemoteServiceBindingOptions configures CreateRemoteServiceBinding.

type RemoteServiceEndpoint

type RemoteServiceEndpoint interface {
	Invoke(ctx context.Context, call ServiceCall, publish ServiceUpdatePublisher) (json.RawMessage, error)
	Dispose()
}

RemoteServiceEndpoint hosts one provider for one remote consumer and owns that consumer's subscriptions (upstream RemoteServiceEndpoint).

func CreateRemoteServiceEndpoint

func CreateRemoteServiceEndpoint(provider *RemoteServiceProvider) RemoteServiceEndpoint

CreateRemoteServiceEndpoint serves $chord.service catalogue, subscribe and unsubscribe control calls and routes every other call to provider.Invoke.

type RemoteServiceError

type RemoteServiceError struct {
	Code    RemoteServiceErrorCode
	Message string
}

RemoteServiceError is a typed service routing or validation failure.

func (*RemoteServiceError) Error

func (err *RemoteServiceError) Error() string

type RemoteServiceErrorCode

type RemoteServiceErrorCode string

RemoteServiceErrorCode is one of the upstream REMOTE_SERVICE_ERROR_CODES.

const (
	ErrServiceNotAllowed       RemoteServiceErrorCode = "service_not_allowed"
	ErrServiceNotFound         RemoteServiceErrorCode = "service_not_found"
	ErrServiceModeMismatch     RemoteServiceErrorCode = "service_mode_mismatch"
	ErrServiceMemberNotFound   RemoteServiceErrorCode = "service_member_not_found"
	ErrServiceMemberMismatch   RemoteServiceErrorCode = "service_member_mismatch"
	ErrServiceInstanceNotFound RemoteServiceErrorCode = "service_instance_not_found"
	ErrServiceStaleInstance    RemoteServiceErrorCode = "service_stale_instance"
	ErrServiceInvalidValue     RemoteServiceErrorCode = "service_invalid_value"
)

Remote service error codes.

type RemoteServiceProvider

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

RemoteServiceProvider hosts the allowlisted remote services of one process (upstream RemoteServiceProvider). It is safe for concurrent use; provider updates are delivered outside its lock in publication order.

func NewRemoteServiceProvider

func NewRemoteServiceProvider(definitions ...ServiceProviderDefinition) (*RemoteServiceProvider, error)

NewRemoteServiceProvider creates a provider for exactly the given services. Local services and duplicate IDs are rejected.

func (*RemoteServiceProvider) BeginInvoke

func (provider *RemoteServiceProvider) BeginInvoke(ctx context.Context, call ServiceCall) (*ServiceInvocation, error)

BeginInvoke applies Invoke's allowlist, instance and member checks, then delegates admission to an implementation that exposes it. Implementations without an admission boundary are rejected rather than started on a prematurely signalled goroutine.

func (*RemoteServiceProvider) Catalogue

func (provider *RemoteServiceProvider) Catalogue() []ServiceCatalogueEntry

Catalogue returns the provider's catalogue in registration order.

func (*RemoteServiceProvider) Dispose

func (provider *RemoteServiceProvider) Dispose() error

Dispose deactivates every instance, emits unavailable/closed to active subscribers, and terminates subscriptions. It is idempotent.

func (*RemoteServiceProvider) Invoke

func (provider *RemoteServiceProvider) Invoke(ctx context.Context, call ServiceCall) (json.RawMessage, error)

Invoke routes one method call and returns implementation failures, including panics, as errors. The result is nil for a void method.

func (*RemoteServiceProvider) Subscribe

func (provider *RemoteServiceProvider) Subscribe(serviceId string, mode ServiceMode, listener UpdateListener) (ServiceSubscription, error)

Subscribe opens a subscription whose snapshot is coherent with the update stream: updates already covered by the snapshot are never delivered, and later updates are buffered until Activate.

type RemoteServiceSource

type RemoteServiceSource interface {
	// AcceptsUnavailableServices reports whether this currently unavailable
	// source may provisionally own requirements absent from every catalogue.
	AcceptsUnavailableServices() bool
	Catalogue(ctx context.Context) ([]ServiceCatalogueEntry, error)
	Open(options RemoteServiceSourceOpenOptions) (RemoteServices, error)
}

RemoteServiceSource offers external services to a facet host (upstream RemoteServiceSource).

type RemoteServiceSourceOpenOptions

type RemoteServiceSourceOpenOptions struct {
	Services     []string
	AssertAccess func() error
	OnError      func(error)
}

RemoteServiceSourceOpenOptions is passed to RemoteServiceSource.Open.

type RemoteServiceTransport

type RemoteServiceTransport interface {
	Invoke(ctx context.Context, call ServiceCall) (json.RawMessage, error)
	Subscribe(ctx context.Context, serviceId string, mode ServiceMode, listener UpdateListener) (ServiceSubscription, error)
}

RemoteServiceTransport is the pluggable wire boundary consumed by a RemoteServiceBinding. Invoke returns nil for a void result. Implementations own serialization and isolation copies.

func NewJSONCopyTransport

func NewJSONCopyTransport(endpoint RemoteServiceEndpoint) RemoteServiceTransport

NewJSONCopyTransport connects a binding to an endpoint through JSON serialization of every call, result, snapshot and update, in memory. It is the local stand-in for a framed connection: subscription control goes through the endpoint's $chord.service calls, and updates published before the consumer activates are buffered in order.

func NewLoopbackTransport

func NewLoopbackTransport(provider *RemoteServiceProvider) RemoteServiceTransport

NewLoopbackTransport connects a provider directly to a binding without changing remote service semantics (upstream createLoopbackServiceTransport). Values are shared, not copied; use NewJSONCopyTransport for isolation.

type RemoteServices

type RemoteServices interface {
	Use(serviceId string) (*RemoteService, error)
	Observe(serviceId string, handler func(context.Context, *RemoteService) error) (func(), error)
	Ready(ctx context.Context) error
	Dispose(ctx context.Context) error
}

RemoteServices is one opened set of external services (upstream RemoteServices). *RemoteServiceBinding implements it.

type ReplicaOf

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

ReplicaOf is a typed read view of a replica. It implements pico3.ReplicatedStateOf[T]; Value returns the zero T before hydration (use Load to distinguish).

func TypedReplica

func TypedReplica[T any](replica *ReplicatedStateReplica) ReplicaOf[T]

TypedReplica returns a typed view of replica.

func (ReplicaOf[T]) Load

func (view ReplicaOf[T]) Load() (T, bool, error)

Load returns a detached decoded value and whether the replica is hydrated.

func (ReplicaOf[T]) Subscribe

func (view ReplicaOf[T]) Subscribe(listener func(T, context.Context, pico3.ReplicatedStateDelivery)) (func(), error)

Subscribe decodes each delivery into a detached T; it fails only the access check.

func (ReplicaOf[T]) Value

func (view ReplicaOf[T]) Value() T

Value returns a detached decoded value, or the zero T before hydration (upstream undefined). An access or decoding failure panics with its error instead of reading as an empty value; use Load to handle it.

type ReplicatedStateReplica

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

ReplicatedStateReplica is a consumer's guarded handle to a replicated state member of a remote service. Like upstream's member view, each Value/Load/ Subscribe checks the holder's access (binding disposal, facet revocation, closed keyed observation). It is untyped; use TypedReplica for a typed view.

func (*ReplicatedStateReplica) FacetIdentity

func (replica *ReplicatedStateReplica) FacetIdentity() *FacetReplicaIdentity

FacetIdentity lets an isolated callback bridge retain JavaScript listener identity without comparing Go function pointers.

func (*ReplicatedStateReplica) Load

func (replica *ReplicatedStateReplica) Load() (pico3.JsonValue, bool, error)

Load returns the current JSON value and whether the replica is hydrated, or the access error. The value is immutable by contract.

func (*ReplicatedStateReplica) Subscribe

func (replica *ReplicatedStateReplica) Subscribe(listener func(pico3.JsonValue, context.Context, pico3.ReplicatedStateDelivery) error) (func(), error)

Subscribe registers listener after an access check; a hydrated replica delivers its retained value immediately as kind "hydrate".

func (*ReplicatedStateReplica) Value

func (replica *ReplicatedStateReplica) Value() (pico3.JsonValue, bool)

Value is Load for callers that treat revocation as a contract violation: an access failure panics with its error (upstream's value property throws) rather than reading as unhydrated. Use Load to handle it as an error.

type ServiceCall

type ServiceCall struct {
	ServiceId string                  `json:"serviceId"`
	Instance  *ServiceInstanceAddress `json:"instance,omitempty"`
	Member    string                  `json:"member"`
	Args      []json.RawMessage       `json:"args"`
}

ServiceCall addresses one method invocation. Args are strict JSON values.

func CreateServiceCatalogueCall

func CreateServiceCatalogueCall() ServiceCall

CreateServiceCatalogueCall builds the catalogue control call.

func CreateServiceSubscribeCall

func CreateServiceSubscribeCall(subscriptionId, serviceId string, mode ServiceMode) ServiceCall

CreateServiceSubscribeCall builds the subscribe control call.

func CreateServiceUnsubscribeCall

func CreateServiceUnsubscribeCall(subscriptionId string) ServiceCall

CreateServiceUnsubscribeCall builds the unsubscribe control call.

func ParseServiceCall

func ParseServiceCall(raw json.RawMessage) (ServiceCall, error)

ParseServiceCall validates the closed invocation shape and optional keyed instance address. Argument payloads are not recursively inspected.

type ServiceCatalogueEntry

type ServiceCatalogueEntry struct {
	ServiceId string      `json:"serviceId"`
	Mode      ServiceMode `json:"mode"`
}

ServiceCatalogueEntry is one provider catalogue row.

func ParseServiceCatalogue

func ParseServiceCatalogue(raw json.RawMessage) ([]ServiceCatalogueEntry, error)

type ServiceControlCall

type ServiceControlCall struct {
	Type           string
	SubscriptionId string
	ServiceId      string
	Mode           ServiceMode
}

ServiceControlCall is a decoded $chord.service control call.

func DecodeServiceControlCall

func DecodeServiceControlCall(call ServiceCall) (ServiceControlCall, bool)

DecodeServiceControlCall returns the control call, or false for an ordinary service call (including malformed control calls, as upstream).

type ServiceInstanceAddress

type ServiceInstanceAddress struct {
	Key        string `json:"key"`
	Generation int    `json:"generation"`
}

ServiceInstanceAddress identifies one generation of a keyed instance.

type ServiceInstanceSnapshot

type ServiceInstanceSnapshot struct {
	Instance *ServiceInstanceAddress `json:"instance,omitempty"`
	Members  []ServiceMemberSnapshot `json:"members"`
}

ServiceInstanceSnapshot describes one live instance. Instance is nil for a singleton.

type ServiceInvocation

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

ServiceInvocation is a service operation whose synchronous admission has completed. Cancelling Wait cancels only that observer, not the admitted operation or its original Context.

func NewServiceInvocation

func NewServiceInvocation(wait func(context.Context) (json.RawMessage, error)) *ServiceInvocation

NewServiceInvocation binds an admitted operation to its owned completion. The producer retains cancellation, response correlation, and cleanup ownership.

func (*ServiceInvocation) Wait

func (operation *ServiceInvocation) Wait(ctx context.Context) (json.RawMessage, error)

type ServiceMemberInitiator

type ServiceMemberInitiator interface {
	BeginServiceMember(ctx context.Context, member string, args []json.RawMessage) (*ServiceInvocation, error)
}

ServiceMemberInitiator is a provided implementation's admission boundary. provider.ts:234 applies a JavaScript member synchronously during invoke, so its synchronous prefix is admitted before the Promise settles; a Go implementation exposes that prefix explicitly.

type ServiceMemberSnapshot

type ServiceMemberSnapshot struct {
	Name     string
	Kind     string
	Sequence int
	Ops      []pico3.Op
}

ServiceMemberSnapshot describes a method member, or a state member with its current sequence and a base ["r", value] operation batch. Sequence and Ops are serialized only for state members.

func (ServiceMemberSnapshot) MarshalJSON

func (member ServiceMemberSnapshot) MarshalJSON() ([]byte, error)

MarshalJSON emits the upstream discriminated member shape.

func (*ServiceMemberSnapshot) UnmarshalJSON

func (member *ServiceMemberSnapshot) UnmarshalJSON(data []byte) error

UnmarshalJSON validates the upstream discriminated member shape.

type ServiceMode

type ServiceMode string

ServiceMode is "singleton" or "keyed".

const (
	ServiceSingleton ServiceMode = "singleton"
	ServiceKeyed     ServiceMode = "keyed"
)

Service modes.

type ServiceProviderDefinition

type ServiceProviderDefinition struct {
	ServiceId string
	Local     bool
	Mode      ServiceMode
}

ServiceProviderDefinition registers one service in a provider catalogue.

func KeyedService

func KeyedService[T any](def pico3.ServiceDefinition[T]) ServiceProviderDefinition

KeyedService registers def as a keyed (multi-instance) catalogue entry.

func SingletonService

func SingletonService[T any](def pico3.ServiceDefinition[T]) ServiceProviderDefinition

SingletonService registers def as a singleton catalogue entry.

type ServiceProviderUpdate

type ServiceProviderUpdate struct {
	Type     string
	Address  *ServiceInstanceAddress
	Member   string
	Sequence int
	Ops      []pico3.Op
	Snapshot *ServiceInstanceSnapshot
}

ServiceProviderUpdate is one ordered provider publication.

  • "state": Address (nil for a singleton), Member, Sequence, Ops.
  • "unavailable": no fields.
  • "replaced": Snapshot.
  • "spawned": Snapshot (serialized under the upstream "instance" key).
  • "closed": Address (serialized under the upstream "instance" key).

func ParseServiceProviderUpdate

func ParseServiceProviderUpdate(raw json.RawMessage) (ServiceProviderUpdate, error)

func (ServiceProviderUpdate) MarshalJSON

func (update ServiceProviderUpdate) MarshalJSON() ([]byte, error)

MarshalJSON emits the upstream ServiceProviderUpdate union.

func (*ServiceProviderUpdate) UnmarshalJSON

func (update *ServiceProviderUpdate) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the upstream ServiceProviderUpdate union.

type ServiceRef

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

ServiceRef is a facet's stable handle to a singleton service (upstream ServiceSlot view). Get returns the service's registered view, whose every method resolves the currently bound implementation and checks the facet's access, so a retained view or method value follows a reload cutover and fails after revocation or disposal.

func UseService

func UseService[T any](env *FacetEnvironment, def pico3.ServiceDefinition[T]) (*ServiceRef[T], error)

UseService declares a hard dependency on singleton def and returns its stable handle. The handle is usable once the facet activates.

func (*ServiceRef[T]) Get

func (ref *ServiceRef[T]) Get() (T, error)

Get returns the guarded view, or an error when the facet's service access is currently revoked or no view is registered for the service.

type ServiceResultInvocation

type ServiceResultInvocation[R any] struct {
	// contains filtered or unexported fields
}

ServiceResultInvocation is the typed completion of an admitted operation. Its observer does not own or cancel the producer. BeginCallResult applies the same decoding rules as CallResult.

func BeginCallResult

func BeginCallResult[R any](ctx context.Context, service *RemoteService, member string, args ...any) (*ServiceResultInvocation[R], error)

BeginCallResult admits a typed call through the selected facade. Admission errors return before an operation exists; response and decoding errors belong to Wait.

func NewServiceResultInvocation

func NewServiceResultInvocation[R any](wait func(context.Context) (R, error)) *ServiceResultInvocation[R]

NewServiceResultInvocation binds an already admitted producer to its typed completion. The producer retains ownership of work, cancellation and shutdown.

func (*ServiceResultInvocation[R]) Wait

func (operation *ServiceResultInvocation[R]) Wait(ctx context.Context) (R, error)

type ServiceSpawner

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

ServiceSpawner spawns keyed instances owned by a facet (upstream StagedServiceSpawner). Instances spawned before the host connects the provision are staged and installed at connection.

func ProvideMany

func ProvideMany[T any](env *FacetEnvironment, def pico3.ServiceDefinition[T]) (*ServiceSpawner[T], error)

ProvideMany declares ownership of keyed service def and returns its deferred spawning capability.

func (*ServiceSpawner[T]) Spawn

func (spawner *ServiceSpawner[T]) Spawn(key string, implementation T) (func(), error)

Spawn publishes one instance while the facet is active. The returned close function is idempotent and is also owned by the facet.

type ServiceStateDecoder

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

ServiceStateDecoder keeps independent path dictionaries for each keyed instance and member, resetting them on snapshot, replacement, unavailability, or a member's base operation.

func CreateServiceStateDecoder

func CreateServiceStateDecoder() *ServiceStateDecoder

func (*ServiceStateDecoder) DecodeSnapshot

func (*ServiceStateDecoder) DecodeUpdate

type ServiceStateEncoder

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

ServiceStateEncoder owns one delta encoder per replicated member in one subscription. Callers preserve update order; sequence-gap handling belongs to replicas.

func CreateServiceStateEncoder

func CreateServiceStateEncoder() *ServiceStateEncoder

func (*ServiceStateEncoder) EncodeSnapshot

func (*ServiceStateEncoder) EncodeUpdate

type ServiceSubscription

type ServiceSubscription interface {
	Snapshot() ServiceSubscriptionSnapshot
	Activate() error
	Close(ctx context.Context) error
}

ServiceSubscription is an opened provider subscription. Updates published after the snapshot are buffered until Activate; Close is idempotent.

type ServiceSubscriptionSnapshot

type ServiceSubscriptionSnapshot struct {
	ServiceId string                    `json:"serviceId"`
	Mode      ServiceMode               `json:"mode"`
	Instances []ServiceInstanceSnapshot `json:"instances"`
}

ServiceSubscriptionSnapshot is the coherent state a subscription starts from.

func ParseServiceSubscriptionSnapshot

func ParseServiceSubscriptionSnapshot(raw json.RawMessage) (ServiceSubscriptionSnapshot, error)

type ServiceUpdatePublisher

type ServiceUpdatePublisher func(ctx context.Context, subscriptionId string, update ServiceProviderUpdate) error

ServiceUpdatePublisher sends one subscription update to the remote consumer. Its failure is ignored by the endpoint, as upstream.

type UnsafePathError

type UnsafePathError struct{ Segment any }

UnsafePathError rejects prototype-chain keys and invalid array indices.

func (*UnsafePathError) Error

func (e *UnsafePathError) Error() string

type UpdateListener

type UpdateListener func(ctx context.Context, update ServiceProviderUpdate)

UpdateListener receives ordered provider updates for one subscription.

type WireOp

type WireOp []any

WireOp is a delta tuple with optional path interning or batch-local path omission. Decode it before applying operations to a replica.

type WireServiceInstanceSnapshot

type WireServiceInstanceSnapshot struct {
	Instance *ServiceInstanceAddress     `json:"instance,omitempty"`
	Members  []WireServiceMemberSnapshot `json:"members"`
}

type WireServiceMemberSnapshot

type WireServiceMemberSnapshot struct {
	Name, Kind string
	Sequence   int
	Ops        []WireOp
}

WireServiceMemberSnapshot carries compressed WireOps, never decoded operations.

func (WireServiceMemberSnapshot) MarshalJSON

func (m WireServiceMemberSnapshot) MarshalJSON() ([]byte, error)

func (*WireServiceMemberSnapshot) UnmarshalJSON

func (m *WireServiceMemberSnapshot) UnmarshalJSON(data []byte) error

type WireServiceProviderUpdate

type WireServiceProviderUpdate struct {
	Type     string
	Address  *ServiceInstanceAddress
	Member   string
	Sequence int
	Ops      []WireOp
	Snapshot *WireServiceInstanceSnapshot
}

func ParseWireServiceProviderUpdate

func ParseWireServiceProviderUpdate(raw json.RawMessage) (WireServiceProviderUpdate, error)

func (WireServiceProviderUpdate) MarshalJSON

func (u WireServiceProviderUpdate) MarshalJSON() ([]byte, error)

func (*WireServiceProviderUpdate) UnmarshalJSON

func (u *WireServiceProviderUpdate) UnmarshalJSON(data []byte) error

type WireServiceSubscriptionSnapshot

type WireServiceSubscriptionSnapshot struct {
	ServiceId string                        `json:"serviceId"`
	Mode      ServiceMode                   `json:"mode"`
	Instances []WireServiceInstanceSnapshot `json:"instances"`
}

func ParseWireServiceSubscriptionSnapshot

func ParseWireServiceSubscriptionSnapshot(raw json.RawMessage) (WireServiceSubscriptionSnapshot, error)

Jump to

Keyboard shortcuts

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