core

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: Apache-2.0 Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go structural core

Package github.com/Bitspark/bitruntime/core/go implements the full structural contract declared by bitwire 0.3.0. It uses Go 1.26, matching that dependency.

import (
    core "github.com/Bitspark/bitruntime/core/go"
    wire "github.com/Bitspark/bitwire/wire/go"
)

func service(root, echo wire.Wire) (wire.WireTree, error) {
    leaf, err := core.Compose[wire.Wire](echo, nil)
    if err != nil {
        return nil, err
    }
    return core.Compose[wire.Wire](root, []wire.Child[wire.Wire]{
        {Key: []byte("echo"), Tree: leaf},
    })
}

Wire.Send(message) is addressless. WireTree is exactly wire.DeixisNode[wire.Wire]: every node has an own primitive and a complete finite map of exact byte keys to child nodes. The generic constructor also accepts other payload types; it never invokes a payload while building a tree.

Operations

tree, err := core.Compose(own, children)
selected, exists := core.Select(tree, path)
selected, exists = tree.At(path)
own, children = tree.Decompose()
rebuilt, err := core.Compose(own, children)

err = core.Send(wireTree, path, message)
addressed := core.AsAddressed(wireTree)
  • Own returns the retained own value. Children and Decompose return the complete child collection, copying keys and the collection itself.
  • Compose preserves own and child identity, snapshots keys, and rejects nil children and duplicate byte keys. Empty keys and arbitrary binary keys work.
  • Select and At follow exact byte keys. An empty path returns the original node. An absent edge returns (nil, false), including when a prefix exists.
  • Reconstruction preserves structure, own capability identity, and retained child identity. Shared child instances are allowed under different keys.
  • Send selects a node and calls its own Wire.Send exactly once. It returns ErrMissingPath for absent paths, without falling back to an ancestor. A selected primitive's refusal is returned unchanged. The complete message and return capability pass through unchanged.

Collection order has no routing meaning. The current implementation preserves construction order; consumers use exact keys rather than positional meaning.

Independent nodes

Children may come from another implementation of wire.DeixisNode[T], including Go value implementations with non-comparable slice payloads. The constructor retains the actual child implementation rather than replacing it with a wrapper. Such children must meet the same finite, acyclic, stable topology contract. Their continued stability is their implementation's responsibility.

Validation walks complete child maps iteratively, rejects duplicates and nil children throughout, and detects cycles where Go node identities can be tracked. Comparable, reflexive identities permit deduplication of shared nodes. Nodes without such an identity are traversed under the finite-tree precondition. The runtime does not claim it can prove termination of arbitrary foreign Children implementations. Locally constructed nodes already enforce their structure and need no repeated traversal.

bitstore's Go declarations have the same semantics but define their own recursive DeixisNode[T] and Child[T] types. They are not directly assignable to bitwire's Go interfaces: At, Children, and Decompose name different return types. Interoperation requires an explicit adapter preserving own capability identity, complete children, exact keys, and selection/reconstruction laws. The TypeScript presentations are structurally assignable; that does not create Go type aliases or add a bitstore dependency to this package.

Addressed access

AsAddressed is a one-way bridge from a full WireTree to the existing wire.AddressedWire carrier access contract. It maps every Unicode-scalar string segment to its exact UTF-8 bytes. It validates the entire path before sending and returns ErrInvalidPath for malformed UTF-8, including encoded surrogates. Empty strings, dots, slashes, and Unicode normalization differences retain their literal meaning. Binary keys outside the UTF-8 image remain usable through the native tree but are unreachable through this unchanged profile.

An opaque addressed router cannot be converted to a full tree without supplying the missing structural information. The bridge supplies no receiving, closing, dispatch, or carrier lifecycle implementation.

Verification

From the repository root:

go test ./core/go
go vet ./core/go
go test -race ./core/go

The tests cover exact binary and empty keys, defensive copies, child and own identity, decomposition/reconstruction, partial selection, shared nodes, independent value implementations, identifiable cycles, deep foreign trees, derived sending, unchanged refusals, and Unicode-safe addressed access. TestBitwireStructuralOracle runs production operations against bitwire's independent observations.

Documentation

Overview

Package core constructs full Deixis trees and derives sending from selection. It implements Bitwire's structural contract without a carrier or dispatcher.

Index

Constants

View Source
const (
	// InvocationCapture claims one immutable routing decision for this
	// traversal. Its message carries the capture's control sink as the return
	// address. Admission is the capture; a refusal is an error from Send.
	InvocationCapture = "invocation.capture"
	// InvocationReady says the captured request has been delivered. A control
	// latched before this arrives is pushed to the sink now.
	InvocationReady = "invocation.ready"
	// InvocationRelease drops a capture whose traversal wants no more controls.
	InvocationRelease = "invocation.release"
	// InvocationBegin takes one execution lease. Admission is the lease.
	InvocationBegin = "invocation.begin"
	// InvocationDone reports that an executing body actually finished.
	InvocationDone = "invocation.done"
	// InvocationControl relays a cancellation into the invocation, which
	// latches it and pushes it to every ready capture exactly once.
	InvocationControl = "invocation.control"
)

An admitted request's return capability is the invocation, presented as addressed access. The empty path carries its outcome, as it always has; these operations carry its lifecycle. They are ordinary events of the profile — a layer's own vocabulary, as `channel.` is the tunnel's — and a participant needs nothing of bitruntime's to speak them but the return capability it was handed.

The capture or body a verb is about is one opaque segment after the operation, because a path is what addresses a thing. The verbs never reach a peer root and never cross a physical hop, so they take no built-in family and reserve no namespace there; a return capability's path space is the invocation's alone.

View Source
const DefaultInvocationBodies = 64

DefaultInvocationBodies bounds the execution leases one admitted invocation may take.

View Source
const DefaultInvocationCaptures = 64

DefaultInvocationCaptures bounds the captures one admitted invocation may take. It bounds traversal depth and shallow fan-out together, since a capture is taken once per routing boundary crossed.

Variables

View Source
var (
	// ErrInvocationUnsupported is the refusal a participant receives from a
	// return capability that does not speak this vocabulary. A dispatcher
	// answers it explicitly rather than routing with weaker guarantees.
	ErrInvocationUnsupported = errors.New("return capability does not carry an invocation lifecycle")
	// ErrInvocationEnded refuses participation once the invocation retired.
	ErrInvocationEnded = errors.New("invocation no longer admits participation")
	// ErrInvocationLimit refuses participation beyond a bound.
	ErrInvocationLimit = errors.New("invocation participation limit reached")
	// ErrInvocationDuplicate refuses a participant identifier already in use.
	ErrInvocationDuplicate = errors.New("invocation participant already exists")
)
View Source
var (
	ErrDuplicateKey = errors.New("bitruntime: duplicate child key")
	ErrInvalidTree  = errors.New("bitruntime: invalid tree")
	ErrCycle        = errors.New("bitruntime: structural cycle")
	ErrMissingPath  = errors.New("bitruntime: missing tree path")
	ErrInvalidPath  = errors.New("bitruntime: invalid addressed path")
	ErrInvalidWire  = errors.New("bitruntime: missing own wire")
)
View Source
var ErrBackpressure = errors.New("bitruntime: consumer is stalled")

ErrBackpressure is why a carrier ended when a bounded queue stayed full: a consumer that does not drain is disconnected rather than allowed to hold the carrier up. A carrier that ended this way is closed, so errors.Is(err, transports.ErrClosed) also holds for the error it reports.

View Source
var ErrReceiverExists = errors.New("bitruntime: endpoint already has a receiver")

ErrReceiverExists refuses a second receive attachment to an endpoint.

Functions

func AsAddressed

func AsAddressed(tree wire.WireTree) wire.AddressedWire

AsAddressed exposes a full tree through the existing bitwire/1 addressed access contract. Each Unicode-scalar string segment maps to its exact UTF-8 byte key; malformed UTF-8 is refused before any primitive is called. Empty strings, slashes, dots, and Unicode normalization differences stay literal.

Binary tree keys outside the UTF-8 image remain valid tree keys but cannot be selected through this facade. This adapter grants no receiver or lifecycle authority and provides no inverse conversion from an opaque AddressedWire.

func At added in v0.2.0

func At(root wire.AddressedWire, path []string) wire.AddressedWire

At binds a relative path prefix to addressed access without allocating a peer, channel or queue: at(w, []) ≃ w and at(at(w, a), b) ≃ at(w, a ++ b). The result grants only send access, even when path is empty. This is addressed prefix binding, not structural selection: it succeeds for every path, and whether the root admits what is sent through it is the root's to decide. Select is the structural operation on a WireTree.

func Compose

func Compose[T any](own T, children []wire.Child[T]) (wire.DeixisNode[T], error)

Compose constructs a full node. It copies the child collection and all keys, preserves own and child capability identity, and rejects duplicate keys, nil children, and cycles identifiable by Go node identity. Empty and arbitrary binary keys are valid.

Independently implemented children must satisfy DeixisNode's finite, stable topology contract. Compose validates their complete Children graph; continued stability is their implementation's responsibility. Comparable node identities permit cycle detection and shared-node deduplication. Value implementations without comparable identity are also supported under the same finite-tree precondition; no generic traversal can guarantee termination for a foreign implementation that violates it. Payloads need not be comparable. Construction and validation do not call Own, At, or any payload operation on children. There is no transformation from an opaque AddressedWire to a tree.

func Ended added in v0.2.0

func Ended(cause error) error

Ended classifies the terminal cause of a carrier as a closed carrier while keeping the cause itself: errors.Is(Ended(cause), transports.ErrClosed) holds, and so does errors.Is(Ended(cause), cause).

func Forward added in v0.2.0

func Forward(inbound, outbound wire.Endpoint) (func(), error)

Forward joins two existing origins without allocating a peer or channel: what either endpoint delivers is sent through the other unchanged, with its return capability and context, in the order the source delivers it. The returned detach removes only the forwarding attachments; both endpoints stay owned by their callers, and each root remains responsible for ending its failed carrier.

A message the destination refuses fails only that message: a refused request is answered through its return capability, and forwarding goes on. Forwarding ends when either endpoint ends or detach is called.

func Mount added in v0.2.0

func Mount(children map[string]wire.Endpoint) wire.Endpoint

Mount consumes one path segment and delegates to that child. The map is copied. A mount has no leaf at []; [""] can select an empty-string key. Its single receive attachment borrows one attachment from each child. Closing a mount detaches those attachments and leaves every child usable: at(mount({k: w}), [k]) ≃ w while the mount is open.

func NewPair added in v0.2.0

func NewPair(options PairOptions) (left, right wire.Endpoint, err error)

NewPair constructs a bounded local carrier with two relative origins. Sending on either endpoint delivers to the receiver on the other. It allocates no peer, serializes nothing, and preserves structured frames, the original return capability's identity and received context. Each admitted request gets a fresh return capability that carries its invocation lifecycle.

func RelayInvocationControl added in v0.2.0

func RelayInvocationControl(message wire.Message) error

RelayInvocationControl hands a cancellation to the invocation it names, which latches it and pushes it to the traversals that captured it. A router that receives a control frame relays it here rather than resolving a route of its own: the capture, not the current registration, decides where it goes.

func Respond added in v0.2.0

func Respond(request wire.Message, result json.RawMessage, err error) error

Respond answers a request through its return capability, normalizing err to the public error the protocol carries: a PublicError as it is, a cancellation as cancelled, a closed carrier as disconnected, and anything else as internal. An oversized or unencodable result is answered with a bounded internal error instead, so the caller is never left waiting.

It returns the outcome it reported: nil for a delivered success, the normalized refusal, or the return capability's own refusal.

func Select

func Select[T any](tree wire.DeixisNode[T], path wire.TreePath) (wire.DeixisNode[T], bool)

Select follows exact child keys. An empty path selects tree itself; a missing edge returns (nil, false). It never manufactures a view or uses own as fallback. The tree must satisfy the full, stable DeixisNode contract.

func Send

func Send(tree wire.WireTree, path wire.TreePath, message wire.Message) error

Send is exactly selection followed by the selected own Wire.Send. Missing selection is ErrMissingPath; a selected primitive's refusal is returned intact. Message and return capability identity are preserved. This operation does not attach receivers, dispatch handlers, or assume ownership of an endpoint.

func Unpublished added in v0.2.0

func Unpublished(err error) error

Unpublished marks an error only at a boundary that can prove its own payload was neither queued nor dispatched locally. It preserves a nil error. Never use it to classify a received error code or an uncertain transport outcome.

func WithMeta added in v0.2.0

func WithMeta(ctx context.Context, meta Meta) context.Context

WithMeta says what the requests and events sent from ctx carry. The map is copied, so a later write to the caller's does not reach a frame already sent; a nil or empty map carries nothing. Keys under the reserved prefix are the protocol's and are dropped rather than sent, since the peer at the far end refuses a frame carrying one.

func WithoutUnpublishedProof added in v0.2.0

func WithoutUnpublishedProof(err error) error

WithoutUnpublishedProof preserves the ordinary cause of an error crossing a dispatch boundary, but removes evidence that belongs to a nested send attempt. Transport adapters and local implementations can return another call's error; that error cannot prove that the surrounding request was never published.

Types

type Invocation added in v0.2.0

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

Invocation is the lifecycle an admitting runtime keeps for one admitted request, and the answer its return capability gives to the vocabulary above. A runtime that is not bitruntime composes it — or answers the same paths itself — and the same participants work against either.

func NewInvocation added in v0.2.0

func NewInvocation(limits InvocationLimits, onRetired func()) *Invocation

NewInvocation creates the lifecycle of one admitted request. onRetired runs once, outside every lifecycle lock, when no permitted future participation and no already admitted control can still need the captures.

func (*Invocation) Deliver added in v0.2.0

func (v *Invocation) Deliver(path []string, message wire.Message) error

Deliver answers one operation of the invocation vocabulary. A return capability routes every nonempty path here; the empty path stays its own.

func (*Invocation) DispatchDone added in v0.2.0

func (v *Invocation) DispatchDone()

DispatchDone reports that the admitted request's own delivery has returned.

func (*Invocation) Retired added in v0.2.0

func (v *Invocation) Retired() bool

Retired reports whether the invocation has released its captures.

func (*Invocation) Settle added in v0.2.0

func (v *Invocation) Settle()

Settle fixes the outcome. It neither finishes a body nor drains a control.

type InvocationBodyHandle added in v0.2.0

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

InvocationBodyHandle is one execution lease of one admitted invocation.

func BeginInvocationBody added in v0.2.0

func BeginInvocationBody(message wire.Message) (*InvocationBodyHandle, error)

BeginInvocationBody takes an execution lease for work this participant owns. The invocation does not retire while the lease is held, so an early answer to the caller — a deadline, a withdrawal — never retires an invocation whose body is still running.

func (*InvocationBodyHandle) Done added in v0.2.0

func (b *InvocationBodyHandle) Done()

Done reports that the body actually finished. It is idempotent and releases only the lease it took: a participant cannot finish another owner's work.

type InvocationCaptureHandle added in v0.2.0

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

InvocationCaptureHandle is one immutable routing decision a participant took for one traversal of one admitted invocation. Repeated traversal of the same dispatcher takes a fresh handle, so no two traversals share a slot.

func CaptureInvocation added in v0.2.0

func CaptureInvocation(message wire.Message, control func(wire.Message)) (*InvocationCaptureHandle, error)

CaptureInvocation claims a routing decision for this traversal and supplies the sink the invocation pushes its cancellation to. The sink receives the control at most once, after Ready and never before.

A return capability that does not speak the vocabulary refuses, and the refusal is the caller's to answer: routing an invocation-aware request with weaker cancellation guarantees is exactly what this reports instead.

func (*InvocationCaptureHandle) Ready added in v0.2.0

func (c *InvocationCaptureHandle) Ready()

Ready says the captured request has been delivered. A cancellation latched while the capture was being installed reaches the sink now.

func (*InvocationCaptureHandle) Release added in v0.2.0

func (c *InvocationCaptureHandle) Release()

Release drops the capture. Ready and Release are each idempotent, and a release after Ready gives up only this traversal's remaining controls.

type InvocationLimits added in v0.2.0

type InvocationLimits struct{ Captures, Bodies int }

InvocationLimits bounds the total captures and execution leases of one admitted invocation. Both are totals, so neither depth nor fan-out can grow the state an invocation retains.

func DefaultInvocationLimits added in v0.2.0

func DefaultInvocationLimits() InvocationLimits

DefaultInvocationLimits are the bounds an admitting runtime uses when it states none of its own.

type Meta added in v0.2.0

type Meta = map[string]string

Meta is what a frame carries about a call rather than of it: a flat map of strings — a tenant, an idempotency key, a credential that is per request — which the profile carries verbatim and reads nothing into.

func MetaFrom added in v0.2.0

func MetaFrom(ctx context.Context) Meta

MetaFrom is the meta of the frame whose handler ctx runs under, and nil where the frame carried none or ctx is no handler's. The map is a copy: a handler may read it, and what it writes reaches no frame.

type PairOptions added in v0.2.0

type PairOptions struct {
	// MaxConcurrentHandlers bounds the requests a direction runs at once; the
	// one past it is refused busy.
	MaxConcurrentHandlers int
	// MaxPendingRequests bounds the requests a direction holds admitted and
	// unanswered; the one past it is refused busy.
	MaxPendingRequests int
	// QueueCapacity bounds the requests and events a direction holds queued.
	// A full queue ends the pair with ErrBackpressure.
	QueueCapacity int
	// MaxFrameBytes bounds the envelope each message would travel as.
	MaxFrameBytes int64
	// RequestTimeout answers a request whose handler has not answered by then.
	RequestTimeout time.Duration
	// WriteTimeout bounds how long an event consumer may take before the pair
	// ends as stalled.
	WriteTimeout time.Duration
	// Propagator moves a trace between a frame and a handler's context.
	Propagator Propagator
}

PairOptions bounds a local pair. Zero values select the defaults, which are the protocol engine's: 64 concurrent handlers and 128 pending requests and queued messages per direction, frames of at most 1 MiB, a 30-second request deadline and a 10-second stall deadline for event consumers.

type Propagator added in v0.2.0

type Propagator interface {
	Extract(ctx context.Context, trace Trace) context.Context
	Inject(ctx context.Context) Trace
}

Propagator moves a trace between a context and a frame. Extract places an incoming frame's trace in the context its handler runs under; Inject says what an outgoing frame carries — a child of the trace the context holds, or a new trace where it holds none. Both members reach it verbatim, and a peer sends what it returns as it returns it.

var DefaultPropagator Propagator = w3cPropagator{}

DefaultPropagator is what a carrier with no Propagator option uses: it keeps an incoming trace verbatim and mints an outgoing one's ids itself, so that frames correlate across hops with no tracing library installed.

type PublicError added in v0.2.0

type PublicError struct {
	Code    string          `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

PublicError is safe to send to the remote caller. Other handler errors are replaced by a generic internal error; their messages are not disclosed.

func (*PublicError) Error added in v0.2.0

func (e *PublicError) Error() string

Error is the code and the message, as a log line shows them.

type Trace added in v0.2.0

type Trace struct{ Parent, State string }

Trace is the W3C Trace Context a frame carries: the two members verbatim, neither of them read by the runtime beyond the form the decoder holds a traceparent to. The runtime imports no tracing library; one binds to it as a Propagator and nowhere else.

func TraceOf added in v0.2.0

func TraceOf(ctx context.Context) (Trace, bool)

TraceOf is the trace DefaultPropagator placed in ctx, and whether one is there. A propagator of another making keeps its trace where it chooses.

type UnpublishedError added in v0.2.0

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

UnpublishedError reports a local refusal before a frame entered a carrier's outbound queue or a local implementation dispatched. Its underlying cause retains the ordinary public error or cancellation identity. A queued write failure or a remote response never supplies this proof, even if it has the same error code or message.

The proof belongs to this send attempt. A handler must not treat a nested call's refusal as proof that its own already-dispatched request was unsent.

func (*UnpublishedError) Error added in v0.2.0

func (e *UnpublishedError) Error() string

func (*UnpublishedError) Unwrap added in v0.2.0

func (e *UnpublishedError) Unwrap() error

Unwrap preserves errors.Is and errors.As for the original refusal.

Jump to

Keyboard shortcuts

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