package pi import ( "bufio" "context" "encoding/json" "errors" "io" "strconv" "sync" ) // Client speaks Pi's RPC mode: JSONL commands on stdin, each with an id, // answered by a response record of the same id on stdout among the // session's events. Records are split on LF only (Pi's framing rule). type Client struct { mu sync.Mutex // wmu orders writes; it is never held by a caller that waits, so a // Pi that stops reading cannot hold the client. wmu sync.Mutex w io.Writer next int pending map[string]chan Response closed bool // Records are every record that is not a command's response, in // order; closed when stdout ends or a record is over the size limit. // The reader of Records hands each one's bytes back with Release. Records <-chan []byte // queued is how many bytes of Records are taken and not released; // the client stops reading Pi's stdout while they are over budget. qmu sync.Mutex qcond *sync.Cond queued int budget int } // Response is a command's answer. type Response struct { ID string `json:"id"` Command string `json:"command"` Success bool `json:"success"` Error string `json:"error"` Data json.RawMessage `json:"data"` } // ErrClosed: Pi's stdout ended. var ErrClosed = errors.New("pi: the process ended") // maxRecord bounds one record (a tool result can be large); maxQueued // bounds the bytes waiting in the client. const ( maxRecord = 8 << 20 maxQueued = 16 << 20 ) // NewClient reads r until it ends. func NewClient(r io.Reader, w io.Writer) *Client { return newClientLimits(r, w, maxRecord, maxQueued) } func newClientLimits(r io.Reader, w io.Writer, record, queued int) *Client { records := make(chan []byte, 256) c := &Client{w: w, pending: map[string]chan Response{}, Records: records, budget: queued} c.qcond = sync.NewCond(&c.qmu) go func() { defer close(records) defer c.fail() s := bufio.NewScanner(r) s.Buffer(make([]byte, 0, min(64<<10, record)), record) for s.Scan() { line := append([]byte(nil), s.Bytes()...) if len(line) == 0 { continue } var resp struct { Type string `json:"type"` Response } if json.Unmarshal(line, &resp) == nil && resp.Type == "response" && resp.ID != "" { c.mu.Lock() ch := c.pending[resp.ID] delete(c.pending, resp.ID) c.mu.Unlock() if ch != nil { ch <- resp.Response continue } } c.take(len(line)) records <- line } }() return c } // take waits until n more bytes fit the budget (one record always does // when nothing else waits). func (c *Client) take(n int) { c.qmu.Lock() defer c.qmu.Unlock() for c.queued > 0 && c.queued+n > c.budget { c.qcond.Wait() } c.queued += n } // Release hands back a record's bytes once it has been read. func (c *Client) Release(n int) { c.qmu.Lock() c.queued -= n c.qmu.Unlock() c.qcond.Broadcast() } func (c *Client) queuedBytes() int { c.qmu.Lock() defer c.qmu.Unlock() return c.queued } func (c *Client) fail() { c.mu.Lock() defer c.mu.Unlock() c.closed = true for id, ch := range c.pending { close(ch) delete(c.pending, id) } } // Send writes one record as a line. It gives up when ctx ends: a Pi that // stops reading its stdin holds only the write itself, which ends when // the namespace is killed and the pipe closes. func (c *Client) Send(ctx context.Context, v any) error { raw, err := json.Marshal(v) if err != nil { return err } c.mu.Lock() closed := c.closed c.mu.Unlock() if closed { return ErrClosed } done := make(chan error, 1) go func() { c.wmu.Lock() defer c.wmu.Unlock() _, err := c.w.Write(append(raw, '\n')) done <- err }() select { case err := <-done: return err case <-ctx.Done(): return ctx.Err() } } // Call sends a command and waits for its response. func (c *Client) Call(ctx context.Context, command map[string]any) (Response, error) { c.mu.Lock() if c.closed { c.mu.Unlock() return Response{}, ErrClosed } c.next++ id := "equipo-" + strconv.Itoa(c.next) ch := make(chan Response, 1) c.pending[id] = ch c.mu.Unlock() cmd := map[string]any{"id": id} for k, v := range command { cmd[k] = v } if err := c.Send(ctx, cmd); err != nil { c.mu.Lock() delete(c.pending, id) c.mu.Unlock() return Response{}, err } select { case <-ctx.Done(): c.mu.Lock() delete(c.pending, id) c.mu.Unlock() return Response{}, ctx.Err() case r, ok := <-ch: if !ok { return Response{}, ErrClosed } if !r.Success { return r, errors.New("pi: " + r.Command + " refused") } return r, nil } }