README.md
jsonlpipe
jsonlpipe is a generic bidirectional JSONL transport over arbitrary
io.Reader/io.Writer pairs. It owns connection mechanics only: reading JSONL
frames, serializing writes, optional startup handshakes, pause/resume, flush,
close/error state, and goroutine lifecycle. It has no application protocol
knowledge.
Each JSONL object is expected to have a top-level type field. The reader
extracts that field into a Frame and leaves the full JSON payload in Raw.
Core model
A Conn owns:
- one writer goroutine,
- one reader goroutine after startup succeeds,
- handler goroutines started by the reader,
- an ordered per-connection write queue,
- lifecycle state observable through
Closed,Done,Wait, andErr.
Normal sends are intentionally non-blocking with respect to I/O pressure:
| 1 | err := conn.Send(msg) |
Send marshals the message, appends it to the connection's ordered write queue,
and returns without waiting for the underlying writer. The default queue has no fixed
library-imposed bound; owners can opt into atomic count/byte admission limits. jsonlpipe preserves order and does not silently drop
frames; slow-peer detection, memory policy, coalescing, and eviction belong to
the owner above the pipe.
Use QueueStats for observability:
| 1 | stats := conn.QueueStats() |
| 2 | log.Printf("queued frames=%d bytes=%d", stats.Frames, stats.Bytes) |
QueueStats is a snapshot only. It does not enforce limits.
Flush
Flush is the explicit synchronization primitive:
| 1 | if err := conn.Send(msg); err != nil { |
| 2 | return err |
| 3 | } |
| 4 | if err := conn.Flush(); err != nil { |
| 5 | return err |
| 6 | } |
Flush enqueues a barrier in the same FIFO queue as normal frames and waits
until all frames queued before that barrier have been written to the underlying
writer. Frames queued concurrently after the barrier do not delay that Flush.
Use Flush for initialization ordering, tests, and places where the caller
really wants a write synchronization point. Do not call it in normal fan-out
paths unless you intend to wait.
Optional initialization exchange
jsonlpipe can reserve the first two frames for a mandatory startup exchange:
| 1 | frame #1: initiator -> acceptor: initialization request |
| 2 | frame #2: acceptor -> initiator: initialization response |
| 3 | frame #3+: normal bidirectional JSONL messages |
Use NewInitiator on the side that writes the first frame and NewAcceptor on
the side that reads it and replies. Initialization frames are consumed by startup
callbacks and are never delivered to the normal handler. Normal Send is
rejected until Start succeeds.
Plain connections use New or NewRW and have no startup exchange.
Lifecycle
Typical usage:
| 1 | conn := jsonlpipe.NewRW(rw, rw.Close, func(f jsonlpipe.Frame) { |
| 2 | // Handle normal frames. This runs in a goroutine started by jsonlpipe. |
| 3 | }) |
| 4 | |
| 5 | if err := conn.Start(); err != nil { |
| 6 | return err |
| 7 | } |
| 8 | defer conn.Close() |
| 9 | |
| 10 | if err := conn.Send(map[string]any{"type": "ping"}); err != nil { |
| 11 | return err |
| 12 | } |
Important lifecycle calls:
Start()starts the writer, performs optional initialization, marks the connection ready, and starts the reader.Ready()closes only after successful startup.Close()initiates shutdown. It is idempotent.Closed()closes immediately when EOF, local close, or transport failure makes the connection terminal.Done()closes when all connection-owned goroutines have exited.Wait()blocks forDone()and returns the terminal error.Err()returns the stored terminal error.
The closeFn passed to the constructor must unblock pending reads and writes on
the underlying transport. For a net.Conn, pass conn.Close. For separate
pipes/files, close whatever ends are necessary to release blocked I/O.
Wait waits for handler goroutines started by the reader. A handler that never
returns can therefore keep Wait blocked. Closed does not wait for handlers
and should be used to release operation waiters that cannot outlive the
transport.
Pause and resume
Pause stops the reader between JSONL frames. While paused, unread data remains
in the OS/socket/pipe buffers; jsonlpipe does not add an application-level cap
or drop policy. Resume lets the reader continue.
API summary
| 1 | type Frame struct { |
| 2 | Type string |
| 3 | Raw json.RawMessage |
| 4 | } |
| 5 | |
| 6 | type Handler func(Frame) |
| 7 | |
| 8 | type InitReplyValidator func(Frame) error |
| 9 | type InitReplyBuilder func(Frame) (reply any, err error) |
| 10 | |
| 11 | type QueueStats struct { |
| 12 | Frames int |
| 13 | Bytes int64 |
| 14 | } |
| 15 | |
| 16 | func New(r io.Reader, w io.Writer, closeFn func() error, h Handler) *Conn |
| 17 | func NewRW(rw io.ReadWriter, closeFn func() error, h Handler) *Conn |
| 18 | func NewInitiator(r io.Reader, w io.Writer, closeFn func() error, init any, validate InitReplyValidator, h Handler) *Conn |
| 19 | func NewInitiatorRW(rw io.ReadWriter, closeFn func() error, init any, validate InitReplyValidator, h Handler) *Conn |
| 20 | func NewAcceptor(r io.Reader, w io.Writer, closeFn func() error, buildReply InitReplyBuilder, h Handler) *Conn |
| 21 | func NewAcceptorRW(rw io.ReadWriter, closeFn func() error, buildReply InitReplyBuilder, h Handler) *Conn |
| 22 | |
| 23 | func (c *Conn) Start() error |
| 24 | func (c *Conn) Ready() <-chan struct{} |
| 25 | func (c *Conn) Closed() <-chan struct{} |
| 26 | func (c *Conn) Done() <-chan struct{} |
| 27 | func (c *Conn) Wait() error |
| 28 | func (c *Conn) Err() error |
| 29 | func (c *Conn) QueueStats() QueueStats |
| 30 | func (c *Conn) Send(msg any) error |
| 31 | func (c *Conn) Flush() error |
| 32 | func (c *Conn) Pause() |
| 33 | func (c *Conn) Resume() |
| 34 | func (c *Conn) Close() error |
Opt-in bounds and owned buffers
Call Configure(Options) before Start. Zero values preserve the unbounded,
asynchronous defaults. MaxLineBytes and MaxStartupLineBytes include LF and
limit acquisition with the same buffered reader across startup and normal reads.
SynchronousDispatch runs short admission/correlation callbacks in receive order;
long work must be delegated. In that mode, Frame.Raw is borrowed until callback
return and must not be retained.
MaxQueueFrames and MaxQueueBytes are checked under the enqueue lock, never by
sampling QueueStats. Flush markers count against the frame ceiling. Optional
ReservedQueueFrames and ReservedQueueBytes withhold capacity from ordinary
sends; SendReservedDeadline can consume that capacity while still respecting
total bounds. A rejected enqueue returns ErrQueueFull without dropping an older
frame. Dequeued and abandoned queue slots release retained references.
SendWaitDeadline and SendReservedWaitDeadline optionally wait for capacity
until a required absolute deadline. They retain one marshaled frame and its
reservation in the calling owner, with no background sender. Owners must bound
concurrent waiting calls and never wait from a synchronous input handler.
Timeout or an impossible-to-fit frame returns ErrQueueFull; closure returns
ErrClosed. Ordinary Send keeps its non-waiting behavior.
ReserveInput and ReserveOutput charge retained allocations and require a
non-nil release on success. EraseBuffers clears owned input and output on every
exit, including partial-write failure and rejected enqueue, using the original
allocation rather than only an unwritten suffix. These guarantees do not erase
immutable strings or every temporary allocation inside encoding/json.
For bounded reads, BeforeRead(false) starts an idle read and BeforeRead(true)
marks the first partial-frame byte. An owner can keep idle connections open while
setting an absolute partial-line deadline. SendDeadline passes an owner deadline
to BeforeWrite; the owner installs the earlier of that deadline and its write
timeout. Stream closure must interrupt blocked I/O. The pipe supplies no
application-specific cancellation, authentication, or slow-peer policy.
The typed private Hub protocol uses these options in pkg/ezhubapi.
See the transport guide and
Hub API guide for composition contracts.