Documentation
¶
Index ¶
- Constants
- Variables
- func NewMessageID() string
- func TypeName(t uint32) string
- func ValidMessageID(id string) bool
- func WriteFrame(w io.Writer, f *Frame) error
- func WriteTraceFrame(w io.Writer, tf *TraceFrame) error
- type Client
- func (c *Client) Close() error
- func (c *Client) Recv() (*Frame, error)
- func (c *Client) Send(frame *Frame) (*SendResult, error)
- func (c *Client) SendBinary(data []byte) error
- func (c *Client) SendFile(name string, data []byte) error
- func (c *Client) SendFileStream(name string, r io.ReadSeeker, size int64, stepTimeout time.Duration) (*StreamResult, error)
- func (c *Client) SendJSON(data []byte) error
- func (c *Client) SendText(text string) error
- func (c *Client) SendTrace(innerType uint32, data []byte) (sentAtNs int64, err error)
- type Frame
- type Handler
- type SendResult
- type Server
- type Service
- type ServiceConfig
- type StreamReceiver
- func NewStreamReceiver(receivedDir string, nameSuffix func(base string) string, ...) *StreamReceiver
- func NewStreamReceiverWithQuota(receivedDir string, nameSuffix func(base string) string, ...) *StreamReceiver
- func NewStreamReceiverWithQuotaAndCommit(receivedDir string, nameSuffix func(base string) string, ...) *StreamReceiver
- func NewStreamReceiverWithQuotaAndPrepareAndCommit(receivedDir string, nameSuffix func(base string) string, ...) *StreamReceiver
- type StreamResult
- type TraceFrame
Constants ¶
const ( TypeText uint32 = 1 TypeBinary uint32 = 2 TypeJSON uint32 = 3 TypeFile uint32 = 4 // TypeTrace wraps another frame type with nanosecond-precision timing. // Wire layout: [4-byte TypeTrace][4-byte len][4-byte inner_type][8-byte sent_at_ns][inner_payload] TypeTrace uint32 = 5 // Type 6 is reserved (see Alex's reply-on-conn PR chain / TypeAutoAnswer). // // TypeFileStream is the chunked/ACK'd/resumable file-transfer protocol // (see docs/PROPOSAL-reliable-file-transfer.md and filestream.go). Each // TypeFileStream frame carries a small control header + at most one // chunk of file data, so a multi-GiB transfer never collapses into a // single giant frame the way TypeFile does. Backward compatible: a // peer that does not understand TypeFileStream never sends INIT-ACK, so // the sender falls back to TypeFile. TypeFileStream uint32 = 7 // TypeGoverned and TypeGovernedFileStream are reserved. They carried a // data frame (8) or a TypeFileStream INIT (9) inside an envelope signed // by the hosted control plane, which has been retired; the envelope // codec and its receiver gates were removed with it. The numbers must // not be reused: senders built before the removal can still emit them, // and a receiver refuses both as unsupported frame types without // storing anything. TypeGoverned uint32 = 8 TypeGovernedFileStream uint32 = 9 // TypeTagged wraps another frame with optional correlation metadata // (Frame.MessageID / Frame.ReplyTo). Callers never set it directly: // WriteFrame emits it when either field is set and ReadFrame unwraps it, // returning the inner frame with the fields populated. See tagged.go for // the wire layout and the fallback rule for receivers that predate it. TypeTagged uint32 = 10 )
Frame types for data exchange on port 1001.
const ( // DefaultInboxMaxBytes caps inbox JSON at 256 MiB total. DefaultInboxMaxBytes int64 = 256 << 20 // DefaultReceivedMaxBytes caps received files + partials at 2 GiB total. DefaultReceivedMaxBytes int64 = 2 << 30 // DefaultIdleTimeout drops a connection idle for 2 minutes between frames. DefaultIdleTimeout = 2 * time.Minute )
Defensible defaults applied when the corresponding ServiceConfig field is left at its zero value. A negative field value disables the limit.
const DefaultDedupeWindow = 10 * time.Minute
DefaultDedupeWindow is how long a stored frame that carried a MessageID is remembered for duplicate suppression when ServiceConfig.DedupeWindow is 0.
const DefaultMaxFrameSize uint32 = 64 << 20
DefaultMaxFrameSize caps a single data-exchange frame at 64 MiB.
The wire format's length field is a uint32 (see Frame docstring below), so the absolute ceiling is ~4 GiB; this cap exists to bound the memory a single hostile peer can make the receiver commit for one transfer. The receiver no longer pre-allocates the attacker-declared length up front (see ReadFrame) — it grows the buffer as bytes actually arrive — but the cap still bounds the steady-state worst case, so it is deliberately set well below the wire ceiling.
64 MiB comfortably covers inbox messages and the deprecated legacy single-frame TypeFile path; anything larger should ride the chunked TypeFileStream protocol (filestream.go), which never buffers a whole file in memory. Operators who genuinely need bigger single frames can raise the cap via PILOT_DATAEXCHANGE_MAX_FRAME (both ends must agree).
History: 256 MiB pre-2026-06-14, then briefly 1 GiB (sized for the test fleet's 100 MiB payloads on multi-GiB-RAM hosts). 1 GiB let a single hostile peer OOM the receiver, so the default was lowered to 64 MiB and the up-front allocation was removed.
const MaxMessageIDLen = 128
MaxMessageIDLen is the longest MessageID or ReplyTo value accepted on the wire. IDs are 1..MaxMessageIDLen bytes of ASCII letters, digits, '-', '_', '.' or ':' — enough for UUIDs, ULIDs and hex nonces, and safe to embed in file names, JSON and log lines without escaping.
const MaxTaggedOverhead = 2 + len(`{"message_id":"","reply_to":""}`) + 2*MaxMessageIDLen + 4
MaxTaggedOverhead is the most a MessageID/ReplyTo header adds to a frame's payload: the 2-byte header length, the JSON header with two MaxMessageIDLen IDs ({"message_id":"…","reply_to":"…"}, 287 bytes) and the 4-byte inner type. A frame stays taggable if its untagged payload is at most MaxFrameSize - MaxTaggedOverhead bytes.
const (
StreamChunkSize = 48 * 1024
)
Defaults. Chunk size is deliberately held below 64 KiB: on the Mac↔GCP-VM rig, single tunnel writes at/above ~256 KiB are silently swallowed by the reliable-stream layer (a 64 KiB TypeFile transfer succeeds byte-perfect; 256 KiB stalls), so a large chunk would reproduce the very failure this protocol exists to avoid. 48 KiB chunks each ride the known-good path, and the per-chunk ACK keeps the reverse direction busy so the tunnel's blackhole heuristic does not flip the link mid-transfer. Window bounds the in-flight (unacked) bytes; 16 × 48 KiB = 768 KiB.
Variables ¶
var ErrRejected = errors.New("dataexchange: receiver rejected frame")
ErrRejected is wrapped by the error Client.Send returns when the receiver answered with an "ERR ..." acknowledgement instead of storing the frame.
var ErrStreamUnsupported = errors.New("dataexchange: peer does not support TypeFileStream")
ErrStreamUnsupported is returned by SendFileStream when the peer does not answer INIT with an INIT-ACK within the negotiation window — i.e. it is a pre-TypeFileStream receiver. The caller should fall back to SendFile on a fresh connection.
var ErrTaggedFrameTooLarge = errors.New("dataexchange: frame with MessageID/ReplyTo exceeds MaxFrameSize")
ErrTaggedFrameTooLarge is returned (wrapped) by WriteFrame when a frame with a MessageID or ReplyTo would exceed MaxFrameSize once its header is added. Nothing is written in that case. Client.Send handles it by sending the frame untagged, which succeeds when the payload alone fits; a raw WriteFrame caller can do the same, or shrink the payload by up to MaxTaggedOverhead bytes.
var MaxFrameSize uint32 = func() uint32 { v := os.Getenv("PILOT_DATAEXCHANGE_MAX_FRAME") if v == "" { return DefaultMaxFrameSize } n, err := strconv.ParseUint(v, 10, 32) if err != nil || n < 1<<16 || n >= 1<<31 { return DefaultMaxFrameSize } return uint32(n) }()
MaxFrameSize is the runtime-effective frame cap. Set at package init from the PILOT_DATAEXCHANGE_MAX_FRAME env var (in bytes) if present and within the safe range [64 KiB, 2 GiB); otherwise DefaultMaxFrameSize.
Both ends of a transfer must agree on the cap — a sender that exceeds the receiver's cap will see the receiver return "frame too large" and drop the connection. The env var is honored at process start, so rolling out a higher cap means restarting daemons on both sides.
Functions ¶
func NewMessageID ¶ added in v0.2.3
func NewMessageID() string
NewMessageID returns a random 128-bit message ID as 32 lowercase hex characters, suitable for Frame.MessageID.
func ValidMessageID ¶ added in v0.2.3
ValidMessageID reports whether id is acceptable as a Frame.MessageID or Frame.ReplyTo value on the wire.
func WriteFrame ¶
WriteFrame writes a frame to a writer. A frame with MessageID or ReplyTo set is written as a TypeTagged wrapper around its own type; receivers that predate TypeTagged do not store it, so prefer Client.Send, which falls back to the untagged form for them. If the wrapper would push the frame over MaxFrameSize, WriteFrame writes nothing and returns an error wrapping ErrTaggedFrameTooLarge.
func WriteTraceFrame ¶
func WriteTraceFrame(w io.Writer, tf *TraceFrame) error
WriteTraceFrame serialises a TraceFrame as a TypeTrace outer frame.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client connects to a remote data exchange service on port 1001.
func (*Client) Send ¶ added in v0.2.3
func (c *Client) Send(frame *Frame) (*SendResult, error)
Send writes frame, waits for the receiver's acknowledgement and reports the outcome. It is the preferred way to send a frame that carries a MessageID or ReplyTo, because it delivers the frame untagged (and reports SendResult.Tagged == false) in the two cases where the tagged form cannot get through:
- The receiver predates TypeTagged. Send recognises its answer (see untaggedReceiverAckPrefixes) and re-sends the same frame without the metadata on the same connection. Such a receiver never stores the tagged copy, so the message is stored exactly once.
- The tagged header would push the frame over MaxFrameSize. Send writes the frame untagged in the first place instead of sending a frame the receiver would drop the connection over.
If the receiver answers "ERR ...", Send returns the result together with an error wrapping ErrRejected. Send reads from the connection, so do not use it concurrently with Recv on the same Client.
func (*Client) SendBinary ¶
SendBinary sends a binary frame.
func (*Client) SendFileStream ¶ added in v0.2.1
func (c *Client) SendFileStream(name string, r io.ReadSeeker, size int64, stepTimeout time.Duration) (*StreamResult, error)
SendFileStream transfers a file using the chunked TypeFileStream protocol with a sliding window, end-to-end SHA-256 verification, and automatic resume (the receiver reports how many contiguous bytes it already has).
Returns ErrStreamUnsupported if the peer never answers INIT with an INIT-ACK within the negotiation window — the caller should fall back to SendFile on a fresh connection. stepTimeout bounds the wait for any single ACK and for the final COMPLETE (0 ⇒ default).
type Frame ¶
type Frame struct {
Type uint32
Payload []byte
Filename string // only for TypeFile
// MessageID optionally identifies this message so the receiver can drop
// an identical re-delivery and the recipient can answer it. Use
// NewMessageID to generate one. Empty means "no ID" (the pre-existing
// wire format). See tagged.go.
MessageID string
// ReplyTo optionally names the MessageID of the message this frame
// answers, so the original sender can match the reply to its request.
// Empty means "not a correlated reply".
ReplyTo string
}
Frame is a typed data unit exchanged between agents. Wire format: [4-byte type][4-byte length][payload] For TypeFile, payload is: [2-byte name length][name bytes][file data]
type SendResult ¶ added in v0.2.3
type SendResult struct {
// Ack is the receiver's acknowledgement frame, normally a TypeText
// "ACK <TYPE> <n> bytes" (or "ERR ..." on rejection).
Ack *Frame
// Tagged is true when the frame's MessageID/ReplyTo reached the
// receiver. It is false when the frame carried neither, and also when
// Send delivered the frame without them: because the receiver predates
// TypeTagged, or because the tagged header would have pushed the frame
// over MaxFrameSize (see ErrTaggedFrameTooLarge). A requester that sees
// Tagged == false cannot expect a reply carrying reply_to, and should
// match the answer on the sender alone.
Tagged bool
// Duplicate is true when the receiver recognised the frame as an
// identical re-delivery of one it had already stored, and did not store
// it a second time.
Duplicate bool
}
SendResult reports what the receiver did with a frame sent by Client.Send.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server listens on port 1001 and dispatches incoming frames to a handler.
func (*Server) ListenAndServe ¶
ListenAndServe binds port 1001 and starts accepting connections.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the L11 plugin adapter. Daemon (L7) holds it only as coreapi.Service; cmd/daemon/main.go (L12) constructs it.
func NewService ¶
func NewService(cfg ServiceConfig) *Service
type ServiceConfig ¶
type ServiceConfig struct {
ReceivedDir string
InboxDir string
// IncludeBase64 adds a lossless `data_b64` field to inbox JSON
// alongside `data`. Off by default — only enable when binary
// payloads (e.g. zlib-compressed envelopes) need to round-trip
// without UTF-8 mangling.
IncludeBase64 bool
// InboxMaxFiles caps the number of inbox files retained on disk.
// On exceeding the cap, oldest files (by mtime) are evicted FIFO.
// Zero or negative ⇒ default 10000. Without this cap, a
// misbehaving peer or sustained inbound load fills the operator's
// disk indefinitely.
InboxMaxFiles int
// InboxMaxBytes caps the total on-disk bytes used by the inbox. Every
// write is checked against a running total; when a message would not
// fit, the oldest messages are evicted until the inbox plus the new
// message is at or below 90% of the cap. A single message larger than the
// cap is rejected without evicting anything. Zero ⇒ DefaultInboxMaxBytes;
// a negative value disables the byte cap entirely (escape hatch).
InboxMaxBytes int64
// DedupeWindow is how long a stored frame that carried a MessageID is
// remembered, so an identical re-delivery (same sender, MessageID,
// ReplyTo, type, filename and bytes) is acknowledged without being
// stored again. Zero ⇒ DefaultDedupeWindow (10 min); negative disables.
// Frames without a MessageID are unaffected unless DedupeContentWindow
// is set.
DedupeWindow time.Duration
// DedupeContentWindow, when positive, also suppresses byte-identical
// frames WITHOUT a MessageID from the same sender that arrive within this
// window (for example a peer that answers one request over two paths).
// Zero (the default) keeps the historical behaviour of storing every
// such frame: two identical legacy messages can be deliberate, and a
// sender cannot mark them otherwise. Keep it short (a few seconds).
DedupeContentWindow time.Duration
// ReceivedMaxBytes caps the total on-disk bytes used by the received-
// files directory (completed TypeFile / TypeFileStream files plus any
// retained .partial fragments). Enforced before every write so a peer
// cannot fill the disk. Zero ⇒ DefaultReceivedMaxBytes; a negative
// value disables the quota entirely (escape hatch).
ReceivedMaxBytes int64
// IdleTimeout bounds how long a single connection may sit without
// delivering the next frame. Reset before every read, so a slowloris
// peer that opens a connection and dribbles (or stalls) is dropped
// instead of pinning the goroutine and its buffers indefinitely.
// Zero ⇒ DefaultIdleTimeout; a negative value disables the deadline.
IdleTimeout time.Duration
}
ServiceConfig configures the daemon-side dataexchange handler. Both paths default to ~/.pilot/{received,inbox} when empty.
type StreamReceiver ¶ added in v0.2.1
type StreamReceiver struct {
// contains filtered or unexported fields
}
StreamReceiver handles the receive side of TypeFileStream for a single connection. It writes incoming chunks contiguously to a .partial file (so the on-disk size is always the resume offset), verifies the full SHA-256 on DONE, and atomically renames into place. Decoupled from the daemon Service so it can be unit-tested with just a directory.
func NewStreamReceiver ¶ added in v0.2.1
func NewStreamReceiver(receivedDir string, nameSuffix func(base string) string, onSaved func(name, path string, size int64)) *StreamReceiver
NewStreamReceiver builds a receiver writing into receivedDir. nameSuffix maps a base filename to a final unique name (nil ⇒ a timestamped default). onSaved (nil ok) fires after a verified file is renamed into place. No disk quota is enforced — use NewStreamReceiverWithQuota to bound on-disk bytes.
func NewStreamReceiverWithQuota ¶ added in v0.2.1
func NewStreamReceiverWithQuota(receivedDir string, nameSuffix func(base string) string, onSaved func(name, path string, size int64), quotaBytes int64) *StreamReceiver
NewStreamReceiverWithQuota is NewStreamReceiver with a disk quota: quotaBytes caps the total on-disk bytes under receivedDir (completed files plus retained .partial fragments). Enforced on INIT and on every chunk write so a peer cannot fill the disk mid-stream. Zero ⇒ unlimited.
func NewStreamReceiverWithQuotaAndCommit ¶ added in v0.2.2
func NewStreamReceiverWithQuotaAndCommit(receivedDir string, nameSuffix func(base string) string, onSaved func(name, path string, size int64), onCommit func([transferIDLen]byte, string, string, int64) error, quotaBytes int64) *StreamReceiver
NewStreamReceiverWithQuotaAndCommit extends the normal receiver with a transactional commit hook: the hook runs after the final file is durable but before consumers are notified. A hook failure removes the final file and reports COMPLETE failure.
func NewStreamReceiverWithQuotaAndPrepareAndCommit ¶ added in v0.2.2
func NewStreamReceiverWithQuotaAndPrepareAndCommit(receivedDir string, nameSuffix func(base string) string, onSaved func(name, path string, size int64), onPrepare, onCommit func([transferIDLen]byte, string, string, int64) error, quotaBytes int64) *StreamReceiver
NewStreamReceiverWithQuotaAndPrepareAndCommit adds a pre-rename durable preparation hook to the commit path. A preparation error leaves no final file visible; callers may keep the partial for retry/inspection.
func (*StreamReceiver) Close ¶ added in v0.2.1
func (sr *StreamReceiver) Close()
Close releases any open .partial handles (call on connection teardown). The .partial files themselves remain for resume.
func (*StreamReceiver) HandleFrame ¶ added in v0.2.1
func (sr *StreamReceiver) HandleFrame(f *Frame) *Frame
HandleFrame processes one TypeFileStream frame and returns the response frame to send back (nil ⇒ nothing to send). It never returns an error for protocol-level problems — those are reported to the peer via COMPLETE / ABORT frames so the connection loop stays simple.
type StreamResult ¶ added in v0.2.1
type StreamResult struct {
BytesSent int64 // chunk bytes actually written to the wire this run
BytesResumed int64 // bytes the receiver already had (skipped)
TotalBytes int64 // file size
Sha256 string // hex of the full-content hash declared in INIT
OK bool
Message string // receiver's COMPLETE message (empty on success)
}
StreamResult summarizes a completed (or failed) TypeFileStream transfer.
type TraceFrame ¶
TraceFrame carries timing metadata around an inner message frame.
func ReadTracePayload ¶
func ReadTracePayload(f *Frame) (*TraceFrame, error)
ReadTracePayload decodes a TraceFrame from a raw TypeTrace Frame.