bus

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 14 Imported by: 0 modules, 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.

Documentation

Overview

Package bus implements the WebSocket transport and wire protocol for node-to-node task delegation (design doc §10).

Index

Constants

View Source
const (
	MsgHello        = "hello"
	MsgJoin         = "join"
	MsgHeartbeat    = "heartbeat"
	MsgTaskDelegate = "task_delegate"
	MsgTaskAccept   = "task_accept"
	MsgTaskDecline  = "task_decline"
	MsgTaskProgress = "task_progress"
	MsgTaskResult   = "task_result"
	MsgTaskRetry    = "task_retry"
	MsgTaskTransfer = "task_transfer"
	MsgTaskCancel   = "task_cancel"
	MsgContextFetch = "context_fetch"
	MsgContextAck   = "context_ack"
)

Message types. These strings are the routing key in the envelope's "type" field and are part of the cross-node protocol.

Variables

This section is empty.

Functions

func HelloSig

func HelloSig(secret, nodeID string, ts int64) string

HelloSig computes the HMAC-SHA256 (hex) of nodeID and a unix timestamp under the shared secret. Binding the timestamp into the signature means a captured hello is only valid within the receiver's tolerance window, so it cannot be replayed after that window (design §16 / P0-1).

func VerifyHello

func VerifyHello(secret, nodeID string, ts int64, sig string, now time.Time) bool

VerifyHello reports whether sig is the valid HMAC for nodeID and ts under secret, and that ts is within maxHelloAge of now. An empty secret or empty signature always fails (fail-closed): a node without a shared secret must not authenticate any peer. A stale or future timestamp also fails, so a replayed hello ages out rather than remaining valid forever.

Types

type Client

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

Client dials a peer and returns a connected Conn (after hello exchange is handled by the caller).

func NewClient

func NewClient(url string, logger *slog.Logger) *Client

NewClient creates a client for a ws:// or wss:// endpoint.

func (*Client) Dial

func (c *Client) Dial(ctx context.Context) (*Conn, error)

Dial establishes a connection. Callers should then send hello and start reading.

type Conn

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

Conn wraps one websocket.Conn with a send mutex (one writer goroutine).

func (*Conn) Close

func (c *Conn) Close() error

Close closes the underlying socket.

func (*Conn) MarkOutbound

func (c *Conn) MarkOutbound()

MarkOutbound flags this connection as locally-initiated; Outbound reports it.

func (*Conn) Outbound

func (c *Conn) Outbound() bool

Outbound reports whether this connection was initiated by this side.

func (*Conn) PeerID

func (c *Conn) PeerID() string

PeerID returns the node id bound to this connection by the hello handshake.

func (*Conn) ReadJSON

func (c *Conn) ReadJSON(v any) error

ReadJSON reads one JSON message into v. Callers must set a read deadline if they want a timeout.

func (*Conn) ResetReadDeadline

func (c *Conn) ResetReadDeadline() error

ResetReadDeadline restores the normal keepalive read deadline (pongWait). Callers should invoke this once a hello handshake succeeds.

func (*Conn) Send

func (c *Conn) Send(v any) error

Send marshals v to JSON and writes it to the peer.

func (*Conn) SetPeerID

func (c *Conn) SetPeerID(id string)

SetPeerID binds the authenticated node id to this connection (set once, at hello). PeerID returns it, or "" before the handshake completes.

func (*Conn) StartPingLoop

func (c *Conn) StartPingLoop(ctx context.Context, pingPeriod time.Duration)

StartPingLoop sends a ping every pingPeriod and refreshes the read deadline, keeping the connection alive and letting the peer's pong reset our deadline. It returns when ctx is done. Runs on the single-writer mutex so it cannot race data messages.

type ContextAckPayload

type ContextAckPayload struct {
	TaskID string   `json:"task_id"`
	Hash   string   `json:"hash"`
	OK     bool     `json:"ok"`
	Data   []byte   `json:"data,omitempty"`
	Refs   []string `json:"refs,omitempty"`
}

ContextAckPayload is the source node's response to a context_fetch. On OK it carries the full snapshot blob (base64) whose SHA-256 must equal Hash; on failure OK is false and the executor fails the task rather than guessing.

type ContextFetchPayload

type ContextFetchPayload struct {
	TaskID      string `json:"task_id"`
	Hash        string `json:"hash"`
	ContextType string `json:"context_type,omitempty"`
}

ContextFetchPayload asks the source node for a full context snapshot.

type Envelope

type Envelope struct {
	V       int             `json:"v"`
	Type    string          `json:"type"`
	MsgID   string          `json:"msg_id"`
	From    string          `json:"from"`
	To      string          `json:"to,omitempty"`
	TS      int64           `json:"ts"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

Envelope is the JSON wire format (design doc §10.3). MsgID is a UUIDv7 used for dedup at the receiving end.

func NewEnvelope

func NewEnvelope(typ, from, msgID string, payload any) (Envelope, error)

NewEnvelope builds an envelope. msgID must be non-empty for idempotency.

func (*Envelope) PayloadInto

func (e *Envelope) PayloadInto(v any) error

PayloadInto decodes the envelope payload into v.

type HeartbeatPayload

type HeartbeatPayload struct {
	Status   string  `json:"status"`   // online|busy|offline
	Load     float64 `json:"load"`     // 0.0-1.0
	Capacity string  `json:"capacity"` // raw JSON from the card
}

HeartbeatPayload carries status + capacity.

type HelloPayload

type HelloPayload struct {
	NodeID string          `json:"node_id"`
	Ver    string          `json:"ver"`
	Card   json.RawMessage `json:"card,omitempty"`
	Ts     int64           `json:"ts,omitempty"` // unix seconds, bound into Sig
	Sig    string          `json:"sig"`
}

HelloPayload is sent when a node connects to declare its identity. Card is the node's capability summary (a compact JSON object); it is carried as raw JSON so the transport stays decoupled from the ledger package that owns the CapabilitySummary type. Sig is the HMAC-SHA256 (hex) of NodeID and Ts under the shared secret, proving the identity was minted by a node that holds the secret and bounding replay to maxHelloAge (design §16 / P0-1).

type Server

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

Server listens for inbound node connections.

func NewServer

func NewServer(addr string, logger *slog.Logger, onConn func(*Conn, string)) *Server

NewServer creates a WebSocket server on addr. onConn is invoked once a peer handshakes and identifies itself. onConn must block while the connection is alive so the server can accurately enforce connection limits.

func (*Server) Listen

func (s *Server) Listen(ctx context.Context) error

Listen blocks serving WebSocket requests until ctx is done.

func (*Server) SetLimits

func (s *Server) SetLimits(maxConns, maxConnsPerIP int)

SetLimits configures the global and per-IP concurrent connection limits. A limit <= 0 means unlimited.

type TaskAcceptPayload

type TaskAcceptPayload struct {
	TaskID string `json:"task_id"`
}

TaskAcceptPayload confirms acceptance.

type TaskCancelPayload

type TaskCancelPayload struct {
	TaskID string `json:"task_id"`
	Reason string `json:"reason,omitempty"`
}

TaskCancelPayload requests cancellation.

type TaskDeclinePayload

type TaskDeclinePayload struct {
	TaskID string `json:"task_id"`
	Reason string `json:"reason"`
}

TaskDeclinePayload rejects with a reason.

type TaskDelegatePayload

type TaskDelegatePayload struct {
	TaskID        string   `json:"task_id"`
	ParentID      string   `json:"parent_id,omitempty"`
	Project       string   `json:"project,omitempty"`
	Title         string   `json:"title,omitempty"`
	ContextType   string   `json:"context_type,omitempty"`
	ContextHash   string   `json:"context_hash,omitempty"`
	ContextLevel  string   `json:"context_level,omitempty"` // pointer|summary|full
	ContextData   []byte   `json:"context_data,omitempty"`  // inline full snapshot
	Intent        string   `json:"intent"`
	SpecJSON      string   `json:"spec_json,omitempty"`
	Requires      []string `json:"requires,omitempty"`
	PreferredNode string   `json:"preferred_node,omitempty"` // user-named node; honored when it matches
	Chain         []string `json:"chain"`
	TimeoutMS     int64    `json:"timeout_ms,omitempty"`
	MaxRetries    int      `json:"max_retries,omitempty"`
	Complexity    float64  `json:"complexity,omitempty"`
	Risk          string   `json:"risk,omitempty"`
	AttemptID     string   `json:"attempt_id,omitempty"`
}

TaskDelegatePayload is the task handoff (design doc §10.3 example). The context transfer fields (design doc §12.4) select how the executor obtains the task's full context:

  • context_level "pointer": context_hash references a snapshot the executor may already have; on miss it fetches from the source node.
  • context_level "summary": the intent/spec carried on the wire is the whole context (no snapshot transfer).
  • context_level "full": context_data carries the inline snapshot (base64).

func (*TaskDelegatePayload) TitleOrDefault

func (p *TaskDelegatePayload) TitleOrDefault() string

TitleOrDefault returns the explicit title, falling back to the intent.

type TaskResultPayload

type TaskResultPayload struct {
	TaskID    string  `json:"task_id"`
	AttemptID string  `json:"attempt_id"`
	OK        bool    `json:"ok"`
	ExitCode  int     `json:"exit_code"`
	Stdout    string  `json:"stdout,omitempty"`
	Stderr    string  `json:"stderr,omitempty"`
	Artifacts string  `json:"artifacts,omitempty"`
	Tokens    int     `json:"tokens,omitempty"`
	Cost      float64 `json:"cost,omitempty"`
}

TaskResultPayload is the completion result.

Jump to

Keyboard shortcuts

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