docs/pkg/jsonlpipe.md

pkg/jsonlpipe — generic JSONL transport

jsonlpipe runs a bidirectional newline-delimited JSON connection over supplied io.Reader/io.Writer pairs. It owns transport mechanics, not Ez-Agent frame semantics. Typed Ez-Agent connections, hello/ack, and RPC: use pkg/ezagentapi. Wire-frame fields and examples: the JSONL API catalog. Go frame definitions: pkg/protocol. Socket endpoints and daemon-side use: pkg/ipcsocket and pkg/service.

What does a connection provide?

RolePublic shape
Decoded inputFrame exposes top-level Type and complete JSON Raw; a Handler receives normal frames.
ConstructionNew is a plain pipe; NewInitiator and NewAcceptor add a one-frame-each-way startup exchange completed before Start succeeds. *RW forms take one read-writer.
SendingSend queues one JSON value; Flush places a FIFO write barrier; QueueStats observes pending frames and bytes.
LifecycleStart, Pause/Resume, Close, Ready, Closed, Done, Wait, and Err control or observe the connection.

By default, a handler starts in its own goroutine for each decoded normal frame, so it must make any ordering or shared-state guarantees it needs. Startup frames are consumed internally and never reach that handler; ezagentapi serializes its callbacks instead. Opt-in synchronous dispatch runs only short admission/correlation work on the reader, with long work delegated by the owner.

What does the transport guarantee—and not guarantee?

  • A single writer goroutine serializes the per-connection FIFO queue. Send returns after queuing, not after the underlying writer finishes; partial writes are completed before the next item.
  • Flush waits only until frames queued before its barrier reach the supplied writer. It is not a peer acknowledgement or application-level durability guarantee.
  • Queue statistics are observational. The default queue is unbounded. Opt-in queue limits provide atomic admission, not eviction, coalescing, or an application-specific slow-peer policy.
  • Each JSONL value becomes a Frame. Type is merely the top-level "type" value: absent/unknown types and application fields are not validated here.
  • Pause stops reading between frames; unread bytes stay in the kernel/socket/pipe buffers, writes are unaffected, and there is no unread-data cap or drop policy.

How does optional startup work?

A plain connection has no handshake. An initiator sends and flushes one request, then reads exactly one reply and validates it with the supplied InitReplyValidator. An acceptor reads exactly one request, builds a reply with the supplied InitReplyBuilder, then sends and flushes it. Start returns successfully—and normal sending becomes ready—only after that exchange completes.

An acceptor can use InitErrorWithReply to send a structured startup failure; that final flush has a one-second timeout. Hello/ack meaning and version validation are supplied by ezagentapi, not by this package.

Opt-in bounded transport

Configure(Options) must run before Start, without concurrent configuration. Zero values preserve existing constructor defaults and EzAgent behavior. ezhubapi uses these options without adding Hub semantics to the pipe:

  • MaxLineBytes and MaxStartupLineBytes bound acquisition, including LF, before a complete line can accumulate. One buffered reader spans startup and traffic. Oversized lines return ErrLineTooLong; truncated lines fail rather than being delivered.
  • MaxQueueFrames and MaxQueueBytes check admission under the enqueue lock. The frame limit includes flush markers and excludes the current write. ReservedQueueFrames and ReservedQueueBytes withhold capacity from ordinary sends. SendReservedDeadline can use it, but cannot exceed total bounds. Rejected enqueue returns ErrQueueFull; owners decide whether to close.
  • SendWaitDeadline and SendReservedWaitDeadline optionally wait for queue capacity with a required absolute deadline. The caller retains one marshaled frame and its output reservation; the pipe creates no background sender. Callers must bound concurrent waiting sends and keep them out of synchronous input handlers. Timeout or an impossible-to-fit frame returns ErrQueueFull; closure returns ErrClosed. Ordinary Send remains non-waiting.
  • SynchronousDispatch calls handlers in receive order. A handler must be short, must not wait for application work, and must not retain borrowed Frame.Raw.
  • ReserveInput and ReserveOutput charge retained allocations and must return non-nil releases. Success, parse failure, rejected enqueue, short-write failure, startup failure, and shutdown all retire ownership. EraseBuffers clears original allocations, including written prefixes, and queue slots discard references on dequeue and abandonment.
  • BeforeRead can clear the idle deadline and set an absolute completion deadline after the first byte. It is used by bounded reads. BeforeWrite receives the absolute owner deadline supplied to SendDeadline. The stream owner implements deadlines and interruptible closure; the pipe does not force-stop arbitrary I/O.

These are generic transport controls, not an operation schema or cancellation protocol. No application names, errors, resource budget, or socket authentication policy belong here.

Which terminal signal should I wait on?

NeedUse
Normal traffic may beginReady(); it remains open when startup fails.
Interrupt work on EOF, close, or transport failureClosed(); handlers may still be running.
Join reader, writer, and transport-started handlersDone() or Wait(); Wait() returns the terminal error.
Inspect the terminal error without waitingErr().

Close is idempotent and records ErrClosed for local shutdown. A caller's closeFn must unblock blocked reads and writes, so terminal cleanup can finish. jsonlpipe.Conn.Wait joins its own handler goroutines; ezagentapi.Conn.Wait also joins its serialized callbacks.

Where do protocol meaning and implementation detail live?