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, and Err.

Normal sends are intentionally non-blocking with respect to I/O pressure:

go
1err := 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:

go
1stats := conn.QueueStats()
2log.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:

go
1if err := conn.Send(msg); err != nil {
2 return err
3}
4if 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:

text
1frame #1: initiator -> acceptor: initialization request
2frame #2: acceptor -> initiator: initialization response
3frame #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:

go
1conn := jsonlpipe.NewRW(rw, rw.Close, func(f jsonlpipe.Frame) {
2 // Handle normal frames. This runs in a goroutine started by jsonlpipe.
3})
4
5if err := conn.Start(); err != nil {
6 return err
7}
8defer conn.Close()
9
10if 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 for Done() 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

go
1type Frame struct {
2 Type string
3 Raw json.RawMessage
4}
5
6type Handler func(Frame)
7
8type InitReplyValidator func(Frame) error
9type InitReplyBuilder func(Frame) (reply any, err error)
10
11type QueueStats struct {
12 Frames int
13 Bytes int64
14}
15
16func New(r io.Reader, w io.Writer, closeFn func() error, h Handler) *Conn
17func NewRW(rw io.ReadWriter, closeFn func() error, h Handler) *Conn
18func NewInitiator(r io.Reader, w io.Writer, closeFn func() error, init any, validate InitReplyValidator, h Handler) *Conn
19func NewInitiatorRW(rw io.ReadWriter, closeFn func() error, init any, validate InitReplyValidator, h Handler) *Conn
20func NewAcceptor(r io.Reader, w io.Writer, closeFn func() error, buildReply InitReplyBuilder, h Handler) *Conn
21func NewAcceptorRW(rw io.ReadWriter, closeFn func() error, buildReply InitReplyBuilder, h Handler) *Conn
22
23func (c *Conn) Start() error
24func (c *Conn) Ready() <-chan struct{}
25func (c *Conn) Closed() <-chan struct{}
26func (c *Conn) Done() <-chan struct{}
27func (c *Conn) Wait() error
28func (c *Conn) Err() error
29func (c *Conn) QueueStats() QueueStats
30func (c *Conn) Send(msg any) error
31func (c *Conn) Flush() error
32func (c *Conn) Pause()
33func (c *Conn) Resume()
34func (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.