pkg/jsonlpipe/jsonlpipe.go
// Package jsonlpipe is a generic bidirectional JSONL transport over arbitrary
// readers/writers. It owns the read loop, the serialized write path, pause/resume,
// flush, close/error state, and an optional mandatory two-frame initialization
// exchange. It has no knowledge of any application protocol.
package jsonlpipe
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"sync"
"time"
)
const startupErrorFlushTimeout = time.Second
// Frame is one decoded JSONL line. Type is the value of the top-level "type"
// field; Raw is the full JSON payload.
type Frame struct {
Type string
Raw json.RawMessage
release func()
}
// Handler is invoked for every normal frame the reader decodes. By default it
// runs in its own goroutine without blocking the reader. SynchronousDispatch
// instead runs it on the reader, borrowing Frame.Raw until it returns. Wait
// joins dispatch in either mode.
type Handler func(Frame)
// InitReplyValidator validates the single initialization response frame read by
// an initiator. Returning an error aborts startup.
type InitReplyValidator func(Frame) error
// InitReplyBuilder is called by an acceptor with the single initialization
// request frame it read. It returns the response frame to send, or an error to
// abort startup.
type InitReplyBuilder func(Frame) (reply any, err error)
// QueueStats is a snapshot of the connection's pending write queue. Frames
// includes flush markers; Bytes counts only frame data. The in-progress write
// is excluded. Queue capacity is unlimited by default; MaxQueueFrames and
// MaxQueueBytes bound configured queues.
type QueueStats struct {
Frames int
Bytes int64
}
// State errors returned by Send, Flush, and Start.
var (
ErrNotStarted = errors.New("jsonlpipe: connection not started")
ErrStarting = errors.New("jsonlpipe: connection initialization not complete")
ErrClosed = errors.New("jsonlpipe: connection closed")
)
// Conn is one JSONL connection: one writer goroutine, one reader goroutine, and
// an optional mandatory two-frame initialization exchange.
type Conn struct {
options Options
readingStartup bool
r io.Reader
w io.Writer
closeFn func() error
handler Handler
// Initialization hooks. nil for a plain pipe.
initRequest any // initiator: frame to send first
initValidate InitReplyValidator // initiator: validate the reply
initBuildReply InitReplyBuilder // acceptor: build reply from request
// One buffered reader shared by init-phase reads and the read loop, so
// bytes buffered during init are not lost when the read loop starts.
br *bufio.Reader
mu sync.Mutex
pauseCond *sync.Cond
state state
err error
readyCh chan struct{}
doneCh chan struct{} // closed when all connection-owned goroutines exit
closeCh chan struct{}
writeMu sync.Mutex
writeCond *sync.Cond
writeQ []writeReq
writeBytes int64
loopsWG sync.WaitGroup
handlersWG sync.WaitGroup
closeOnce sync.Once
doneOnce sync.Once
startupErrorFlushTimeout time.Duration
startupErrorFlushTimer func(time.Duration) flushTimer
}
type flushTimer struct {
c <-chan time.Time
stop func() bool
}
func newFlushTimer(timeout time.Duration) flushTimer {
timer := time.NewTimer(timeout)
return flushTimer{c: timer.C, stop: timer.Stop}
}
type writeReq struct {
data []byte
flush chan error
deadline time.Time
release func()
reserved bool
}
type state int
const (
stateNew state = iota
stateStarting
stateReady
statePaused
stateClosed
)
func newConn(r io.Reader, w io.Writer, closeFn func() error, h Handler) *Conn {
c := &Conn{
readingStartup: true,
r: r,
w: w,
closeFn: closeFn,
handler: h,
br: bufio.NewReader(r),
readyCh: make(chan struct{}),
doneCh: make(chan struct{}),
closeCh: make(chan struct{}),
startupErrorFlushTimeout: startupErrorFlushTimeout,
startupErrorFlushTimer: newFlushTimer,
}
c.pauseCond = sync.NewCond(&c.mu)
c.writeCond = sync.NewCond(&c.writeMu)
return c
}
// New returns a plain pipe with no initialization exchange.
func New(r io.Reader, w io.Writer, closeFn func() error, h Handler) *Conn {
return newConn(r, w, closeFn, h)
}
// NewRW is New over a single ReadWriter.
func NewRW(rw io.ReadWriter, closeFn func() error, h Handler) *Conn {
return New(rw, rw, closeFn, h)
}
// NewInitiator returns a pipe that sends init as the first frame, then reads and
// validates exactly one response frame before normal traffic begins.
func NewInitiator(r io.Reader, w io.Writer, closeFn func() error, init any, validate InitReplyValidator, h Handler) *Conn {
c := newConn(r, w, closeFn, h)
c.initRequest = init
c.initValidate = validate
return c
}
// NewInitiatorRW is NewInitiator over a single ReadWriter.
func NewInitiatorRW(rw io.ReadWriter, closeFn func() error, init any, validate InitReplyValidator, h Handler) *Conn {
return NewInitiator(rw, rw, closeFn, init, validate, h)
}
// NewAcceptor returns a pipe that reads exactly one request frame, calls
// buildReply, and sends the returned reply before normal traffic begins.
func NewAcceptor(r io.Reader, w io.Writer, closeFn func() error, buildReply InitReplyBuilder, h Handler) *Conn {
c := newConn(r, w, closeFn, h)
c.initBuildReply = buildReply
return c
}
// NewAcceptorRW is NewAcceptor over a single ReadWriter.
func NewAcceptorRW(rw io.ReadWriter, closeFn func() error, buildReply InitReplyBuilder, h Handler) *Conn {
return NewAcceptor(rw, rw, closeFn, buildReply, h)
}
// Ready returns a channel closed when initialization completes and the
// connection is ready for normal traffic. If startup fails, Ready is not closed;
// Done closes and Err reports the failure.
func (c *Conn) Ready() <-chan struct{} { return c.readyCh }
// Done returns a channel closed when all connection-owned goroutines have
// exited: the reader loop, writer loop, and handler goroutines started by the
// connection.
func (c *Conn) Done() <-chan struct{} { return c.doneCh }
// Closed returns a channel closed as soon as the connection enters its
// terminal state, before connection-owned handler goroutines necessarily
// return. Use Done when joining goroutines and Closed when interrupting work
// that cannot make progress after EOF, Close, or transport failure.
func (c *Conn) Closed() <-chan struct{} { return c.closeCh }
// Wait blocks until all connection-owned goroutines have exited and returns the
// terminal connection error. A local Close records ErrClosed.
func (c *Conn) Wait() error {
<-c.doneCh
return c.Err()
}
// Err returns the terminal connection error, or nil while the connection is not
// closed.
func (c *Conn) Err() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.err
}
// QueueStats returns a snapshot of frames and bytes waiting in the internal
// ordered write queue. It is observability only; Configure selects optional
// queue limits, while owners supply write deadlines and slow-peer policy.
func (c *Conn) QueueStats() QueueStats {
c.writeMu.Lock()
defer c.writeMu.Unlock()
return QueueStats{Frames: len(c.writeQ), Bytes: c.writeBytes}
}
// Start launches the writer and reader goroutines and performs the
// initialization exchange if one is configured. It returns nil once the
// connection is ready, or the first error from initialization.
func (c *Conn) Start() error {
c.mu.Lock()
if c.state != stateNew {
c.mu.Unlock()
return fmt.Errorf("jsonlpipe: Start already called")
}
c.state = stateStarting
c.mu.Unlock()
c.loopsWG.Add(1)
go func() {
defer c.loopsWG.Done()
c.writeLoop()
}()
if err := c.doInit(); err != nil {
c.fail(err)
go c.closeDoneWhenStopped()
return err
}
c.mu.Lock()
if c.state == stateClosed {
c.mu.Unlock()
go c.closeDoneWhenStopped()
return c.Err()
}
c.readingStartup = false
c.state = stateReady
close(c.readyCh)
c.mu.Unlock()
c.loopsWG.Add(1)
c.handlersWG.Add(1) // read-loop producer: prevents Add/Wait handoff race
go func() {
defer c.loopsWG.Done()
defer c.handlersWG.Done()
c.readLoop()
}()
go c.closeDoneWhenStopped()
return nil
}
func (c *Conn) closeDoneWhenStopped() {
c.loopsWG.Wait()
c.handlersWG.Wait()
if c.options.EraseBuffers {
if buffered, err := c.br.Peek(c.br.Buffered()); err == nil {
clear(buffered)
}
}
c.closeDone()
}
func (c *Conn) closeDone() {
c.doneOnce.Do(func() { close(c.doneCh) })
}
type InitErrorWithReply interface {
error
InitReply() any
}
func (c *Conn) doInit() error {
switch {
case c.initRequest != nil:
if err := c.enqueueMarshal(c.initRequest); err != nil {
return err
}
if err := c.flush(); err != nil {
return err
}
f, err := c.readOneFrame()
if err != nil {
return fmt.Errorf("jsonlpipe: read init response: %w", err)
}
defer c.retireFrame(f)
if f.Type == "error" {
var pe struct {
Code string `json:"code"`
Message string `json:"message"`
}
_ = json.Unmarshal(f.Raw, &pe)
if pe.Message != "" {
return errors.New(pe.Message)
}
return fmt.Errorf("jsonlpipe: init error response")
}
if c.initValidate != nil {
if err := c.initValidate(f); err != nil {
return err
}
}
return nil
case c.initBuildReply != nil:
f, err := c.readOneFrame()
if err != nil {
return fmt.Errorf("jsonlpipe: read init request: %w", err)
}
defer c.retireFrame(f)
reply, err := c.initBuildReply(f)
if err != nil {
var withReply InitErrorWithReply
if errors.As(err, &withReply) {
if marshalErr := c.enqueueMarshal(withReply.InitReply()); marshalErr == nil {
_ = c.flushTimeoutWithTimer(c.startupErrorFlushTimeout, c.startupErrorFlushTimer)
}
}
return err
}
if err := c.enqueueMarshal(reply); err != nil {
return err
}
return c.flush()
default:
return nil
}
}
func (c *Conn) readOneFrame() (Frame, error) {
if c.options.MaxLineBytes > 0 || c.readingStartup && c.options.MaxStartupLineBytes > 0 {
return c.readBoundedFrame()
}
line, err := c.br.ReadBytes('\n')
if err != nil {
return Frame{}, err
}
return decodeFrame(line)
}
func (c *Conn) enqueueMarshal(msg any) error {
return c.enqueueMarshalDeadline(msg, time.Time{})
}
func (c *Conn) enqueueMarshalDeadline(msg any, deadline time.Time) error {
return c.enqueueMarshalReserved(msg, deadline, false)
}
func (c *Conn) enqueueMarshalReserved(msg any, deadline time.Time, reserved bool) error {
return c.enqueueMarshalWaiting(msg, deadline, reserved, false)
}
func (c *Conn) enqueueMarshalWaiting(msg any, deadline time.Time, reserved, wait bool) error {
data, err := json.Marshal(msg)
if err != nil {
return err
}
if c.options.EraseBuffers {
// Appending LF may reallocate. Erase the original marshal allocation
// explicitly rather than losing its only reference in append.
payload := data
data = make([]byte, len(payload)+1)
copy(data, payload)
data[len(payload)] = '\n'
clear(payload[:cap(payload)])
} else {
data = append(data, '\n')
}
req := writeReq{data: data, deadline: deadline, reserved: reserved}
if c.options.ReserveOutput != nil {
req.release, err = c.options.ReserveOutput(cap(data))
if err != nil {
c.retireWrite(req)
return err
}
if req.release == nil {
c.retireWrite(req)
return errors.New("jsonlpipe: nil reservation release")
}
}
if err := c.enqueueWriteWaiting(req, wait); err != nil {
c.retireWrite(req)
return err
}
return nil
}
func (c *Conn) enqueueWrite(req writeReq) error {
return c.enqueueWriteWaiting(req, false)
}
func (c *Conn) enqueueWriteWaiting(req writeReq, wait bool) error {
select {
case <-c.closeCh:
return ErrClosed
default:
}
c.writeMu.Lock()
var timer *time.Timer
var timerDone chan struct{}
defer func() {
// A fired wakeup borrows the connection mutex. Unlock before joining
// it so no timer callback survives retirement of this waiting send.
c.writeMu.Unlock()
if timer != nil && !timer.Stop() {
<-timerDone
}
}()
select {
case <-c.closeCh:
return ErrClosed
default:
}
frameLimit, byteLimit := c.options.MaxQueueFrames, c.options.MaxQueueBytes
if !req.reserved {
frameLimit -= c.options.ReservedQueueFrames
byteLimit -= c.options.ReservedQueueBytes
}
// A frame which cannot fit even an empty queue must not wait.
if c.options.MaxQueueFrames > 0 && frameLimit == 0 || c.options.MaxQueueBytes > 0 && int64(len(req.data)) > byteLimit {
return ErrQueueFull
}
if wait {
if req.deadline.IsZero() {
return errors.New("jsonlpipe: queue wait requires deadline")
}
timerDone = make(chan struct{})
timer = time.AfterFunc(time.Until(req.deadline), func() {
defer close(timerDone)
c.writeMu.Lock()
c.writeCond.Broadcast()
c.writeMu.Unlock()
})
}
for c.options.MaxQueueFrames > 0 && len(c.writeQ) >= frameLimit || c.options.MaxQueueBytes > 0 && c.writeBytes+int64(len(req.data)) > byteLimit {
if !wait || !time.Now().Before(req.deadline) {
return ErrQueueFull
}
c.writeCond.Wait()
select {
case <-c.closeCh:
return ErrClosed
default:
}
}
if wait && !time.Now().Before(req.deadline) {
return ErrQueueFull
}
c.writeQ = append(c.writeQ, req)
if req.data != nil {
c.writeBytes += int64(len(req.data))
}
c.writeCond.Broadcast()
return nil
}
func (c *Conn) flush() error {
return c.flushTimeout(0)
}
func (c *Conn) flushTimeout(timeout time.Duration) error {
return c.flushTimeoutWithTimer(timeout, newFlushTimer)
}
func (c *Conn) flushTimeoutWithTimer(timeout time.Duration, newTimer func(time.Duration) flushTimer) error {
ch := make(chan error, 1)
if err := c.enqueueWrite(writeReq{flush: ch}); err != nil {
return err
}
if timeout <= 0 {
select {
case err := <-ch:
return err
case <-c.closeCh:
return ErrClosed
}
}
timer := newTimer(timeout)
defer timer.stop()
select {
case err := <-ch:
return err
case <-c.closeCh:
return ErrClosed
case <-timer.c:
return fmt.Errorf("jsonlpipe: flush timed out after %s", timeout)
}
}
func (c *Conn) writeLoop() {
defer c.retireQueue()
for {
req, ok := c.nextWriteReq()
if !ok {
return
}
if req.flush != nil {
req.flush <- nil
continue
}
var err error
if c.options.BeforeWrite != nil {
err = c.options.BeforeWrite(req.deadline)
}
if err == nil {
err = writeAll(c.w, req.data)
}
c.retireWrite(req)
if err != nil {
c.fail(err)
return
}
}
}
func writeAll(w io.Writer, data []byte) error {
for len(data) > 0 {
n, err := w.Write(data)
if n < 0 || n > len(data) {
return fmt.Errorf("jsonlpipe: invalid write count %d", n)
}
data = data[n:]
if err != nil {
return err
}
if n == 0 {
return io.ErrShortWrite
}
}
return nil
}
func (c *Conn) nextWriteReq() (writeReq, bool) {
c.writeMu.Lock()
defer c.writeMu.Unlock()
for len(c.writeQ) == 0 {
select {
case <-c.closeCh:
return writeReq{}, false
default:
}
c.writeCond.Wait()
}
req := c.writeQ[0]
copy(c.writeQ, c.writeQ[1:])
c.writeQ[len(c.writeQ)-1] = writeReq{}
c.writeQ = c.writeQ[:len(c.writeQ)-1]
if req.data != nil {
c.writeBytes -= int64(len(req.data))
}
c.writeCond.Broadcast()
return req, true
}
func (c *Conn) readLoop() {
for {
c.mu.Lock()
for c.state == statePaused {
c.pauseCond.Wait()
}
closed := c.state == stateClosed
c.mu.Unlock()
if closed {
return
}
f, err := c.readOneFrame()
if err != nil {
c.mu.Lock()
closed = c.state == stateClosed
c.mu.Unlock()
if !closed {
c.fail(err)
}
return
}
if h := c.handler; h != nil {
if c.options.SynchronousDispatch {
h(f)
c.retireFrame(f)
continue
}
c.handlersWG.Add(1)
go func() {
defer c.handlersWG.Done()
defer c.retireFrame(f)
h(f)
}()
} else {
c.retireFrame(f)
}
}
}
// Send marshals msg and queues it for the writer without waiting for an
// in-flight underlying Write. The queue is unlimited by default. Configured
// MaxQueueFrames or MaxQueueBytes cause ErrQueueFull rather than a capacity wait.
// It also fails when not ready, closed, or unable to marshal the message.
func (c *Conn) Send(msg any) error {
return c.SendDeadline(msg, time.Time{})
}
// SendDeadline queues a frame with an absolute owner deadline for BeforeWrite.
func (c *Conn) SendDeadline(msg any, deadline time.Time) error {
return c.sendDeadline(msg, deadline, false)
}
// SendReservedDeadline may consume capacity withheld from ordinary sends.
// The owner decides which bounded frames qualify; total limits still apply.
func (c *Conn) SendReservedDeadline(msg any, deadline time.Time) error {
return c.sendDeadline(msg, deadline, true)
}
func (c *Conn) sendDeadline(msg any, deadline time.Time, reserved bool) error {
return c.sendWaiting(msg, deadline, reserved, false)
}
// SendWaitDeadline waits for ordinary queue capacity until the absolute deadline.
// It retains one marshaled frame and its output reservation in the caller, not
// in a background sender. Callers must bound concurrent waiting sends. A frame
// that cannot fit or a capacity wait that expires returns ErrQueueFull.
func (c *Conn) SendWaitDeadline(msg any, deadline time.Time) error {
return c.sendWaiting(msg, deadline, false, true)
}
// SendReservedWaitDeadline is SendWaitDeadline with access to reserved capacity.
// Total configured queue bounds still apply.
func (c *Conn) SendReservedWaitDeadline(msg any, deadline time.Time) error {
return c.sendWaiting(msg, deadline, true, true)
}
func (c *Conn) sendWaiting(msg any, deadline time.Time, reserved, wait bool) error {
c.mu.Lock()
switch c.state {
case stateNew:
c.mu.Unlock()
return ErrNotStarted
case stateStarting:
c.mu.Unlock()
return ErrStarting
case stateClosed:
c.mu.Unlock()
return ErrClosed
}
c.mu.Unlock()
return c.enqueueMarshalWaiting(msg, deadline, reserved, wait)
}
// Flush blocks until all frames queued before the flush are on the wire.
func (c *Conn) Flush() error {
c.mu.Lock()
st := c.state
c.mu.Unlock()
switch st {
case stateNew:
return ErrNotStarted
case stateClosed:
return ErrClosed
}
return c.flush()
}
// Pause stops the reader goroutine from reading. While paused, unread bytes
// remain in the kernel/socket/pipe buffers; OS flow control is the only bound.
func (c *Conn) Pause() {
c.mu.Lock()
defer c.mu.Unlock()
if c.state == stateReady {
c.state = statePaused
}
}
// Resume restarts reading after Pause.
func (c *Conn) Resume() {
c.mu.Lock()
defer c.mu.Unlock()
if c.state == statePaused {
c.state = stateReady
c.pauseCond.Broadcast()
}
}
// Close shuts down the connection. It is safe to call multiple times. Close
// initiates shutdown; use Wait or Done to wait for all owned goroutines to exit.
func (c *Conn) Close() error {
var err error
c.closeOnce.Do(func() {
c.mu.Lock()
wasNew := c.state == stateNew
c.state = stateClosed
if c.err == nil {
c.err = ErrClosed
}
c.pauseCond.Broadcast()
c.mu.Unlock()
close(c.closeCh)
c.writeMu.Lock()
c.writeCond.Broadcast()
c.writeMu.Unlock()
if c.closeFn != nil {
err = c.closeFn()
}
if wasNew {
c.closeDone()
}
})
return err
}
func (c *Conn) fail(err error) {
if err == nil {
err = ErrClosed
}
c.closeOnce.Do(func() {
c.mu.Lock()
wasNew := c.state == stateNew
c.state = stateClosed
c.err = err
c.pauseCond.Broadcast()
c.mu.Unlock()
close(c.closeCh)
c.writeMu.Lock()
c.writeCond.Broadcast()
c.writeMu.Unlock()
if c.closeFn != nil {
_ = c.closeFn()
}
if wasNew {
c.closeDone()
}
})
}
func decodeFrame(line []byte) (Frame, error) {
var probe struct {
Type string `json:"type"`
}
if err := json.Unmarshal(line, &probe); err != nil {
return Frame{}, fmt.Errorf("jsonlpipe: decode: %w: %w", ErrMalformedFrame, err)
}
return Frame{Type: probe.Type, Raw: json.RawMessage(line)}, nil
}
// Abort enters the terminal state with an owner-supplied error. It interrupts
// I/O immediately; Wait still joins all transport work.
func (c *Conn) Abort(err error) { c.fail(err) }