| 1 | package pi |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "strconv" |
| 10 | "sync" |
| 11 | ) |
| 12 | |
| 13 | // Client speaks Pi's RPC mode: JSONL commands on stdin, each with an id, |
| 14 | // answered by a response record of the same id on stdout among the |
| 15 | // session's events. Records are split on LF only (Pi's framing rule). |
| 16 | type Client struct { |
| 17 | mu sync.Mutex |
| 18 | // wmu orders writes; it is never held by a caller that waits, so a |
| 19 | // Pi that stops reading cannot hold the client. |
| 20 | wmu sync.Mutex |
| 21 | w io.Writer |
| 22 | next int |
| 23 | pending map[string]chan Response |
| 24 | closed bool |
| 25 | // Records are every record that is not a command's response, in |
| 26 | // order; closed when stdout ends or a record is over the size limit. |
| 27 | // The reader of Records hands each one's bytes back with Release. |
| 28 | Records <-chan []byte |
| 29 | |
| 30 | // queued is how many bytes of Records are taken and not released; |
| 31 | // the client stops reading Pi's stdout while they are over budget. |
| 32 | qmu sync.Mutex |
| 33 | qcond *sync.Cond |
| 34 | queued int |
| 35 | budget int |
| 36 | } |
| 37 | |
| 38 | // Response is a command's answer. |
| 39 | type Response struct { |
| 40 | ID string `json:"id"` |
| 41 | Command string `json:"command"` |
| 42 | Success bool `json:"success"` |
| 43 | Error string `json:"error"` |
| 44 | Data json.RawMessage `json:"data"` |
| 45 | } |
| 46 | |
| 47 | // ErrClosed: Pi's stdout ended. |
| 48 | var ErrClosed = errors.New("pi: the process ended") |
| 49 | |
| 50 | // maxRecord bounds one record (a tool result can be large); maxQueued |
| 51 | // bounds the bytes waiting in the client. |
| 52 | const ( |
| 53 | maxRecord = 8 << 20 |
| 54 | maxQueued = 16 << 20 |
| 55 | ) |
| 56 | |
| 57 | // NewClient reads r until it ends. |
| 58 | func NewClient(r io.Reader, w io.Writer) *Client { |
| 59 | return newClientLimits(r, w, maxRecord, maxQueued) |
| 60 | } |
| 61 | |
| 62 | func newClientLimits(r io.Reader, w io.Writer, record, queued int) *Client { |
| 63 | records := make(chan []byte, 256) |
| 64 | c := &Client{w: w, pending: map[string]chan Response{}, Records: records, budget: queued} |
| 65 | c.qcond = sync.NewCond(&c.qmu) |
| 66 | go func() { |
| 67 | defer close(records) |
| 68 | defer c.fail() |
| 69 | s := bufio.NewScanner(r) |
| 70 | s.Buffer(make([]byte, 0, min(64<<10, record)), record) |
| 71 | for s.Scan() { |
| 72 | line := append([]byte(nil), s.Bytes()...) |
| 73 | if len(line) == 0 { |
| 74 | continue |
| 75 | } |
| 76 | var resp struct { |
| 77 | Type string `json:"type"` |
| 78 | Response |
| 79 | } |
| 80 | if json.Unmarshal(line, &resp) == nil && resp.Type == "response" && resp.ID != "" { |
| 81 | c.mu.Lock() |
| 82 | ch := c.pending[resp.ID] |
| 83 | delete(c.pending, resp.ID) |
| 84 | c.mu.Unlock() |
| 85 | if ch != nil { |
| 86 | ch <- resp.Response |
| 87 | continue |
| 88 | } |
| 89 | } |
| 90 | c.take(len(line)) |
| 91 | records <- line |
| 92 | } |
| 93 | }() |
| 94 | return c |
| 95 | } |
| 96 | |
| 97 | // take waits until n more bytes fit the budget (one record always does |
| 98 | // when nothing else waits). |
| 99 | func (c *Client) take(n int) { |
| 100 | c.qmu.Lock() |
| 101 | defer c.qmu.Unlock() |
| 102 | for c.queued > 0 && c.queued+n > c.budget { |
| 103 | c.qcond.Wait() |
| 104 | } |
| 105 | c.queued += n |
| 106 | } |
| 107 | |
| 108 | // Release hands back a record's bytes once it has been read. |
| 109 | func (c *Client) Release(n int) { |
| 110 | c.qmu.Lock() |
| 111 | c.queued -= n |
| 112 | c.qmu.Unlock() |
| 113 | c.qcond.Broadcast() |
| 114 | } |
| 115 | |
| 116 | func (c *Client) queuedBytes() int { |
| 117 | c.qmu.Lock() |
| 118 | defer c.qmu.Unlock() |
| 119 | return c.queued |
| 120 | } |
| 121 | |
| 122 | func (c *Client) fail() { |
| 123 | c.mu.Lock() |
| 124 | defer c.mu.Unlock() |
| 125 | c.closed = true |
| 126 | for id, ch := range c.pending { |
| 127 | close(ch) |
| 128 | delete(c.pending, id) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // Send writes one record as a line. It gives up when ctx ends: a Pi that |
| 133 | // stops reading its stdin holds only the write itself, which ends when |
| 134 | // the namespace is killed and the pipe closes. |
| 135 | func (c *Client) Send(ctx context.Context, v any) error { |
| 136 | raw, err := json.Marshal(v) |
| 137 | if err != nil { |
| 138 | return err |
| 139 | } |
| 140 | c.mu.Lock() |
| 141 | closed := c.closed |
| 142 | c.mu.Unlock() |
| 143 | if closed { |
| 144 | return ErrClosed |
| 145 | } |
| 146 | done := make(chan error, 1) |
| 147 | go func() { |
| 148 | c.wmu.Lock() |
| 149 | defer c.wmu.Unlock() |
| 150 | _, err := c.w.Write(append(raw, '\n')) |
| 151 | done <- err |
| 152 | }() |
| 153 | select { |
| 154 | case err := <-done: |
| 155 | return err |
| 156 | case <-ctx.Done(): |
| 157 | return ctx.Err() |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | // Call sends a command and waits for its response. |
| 162 | func (c *Client) Call(ctx context.Context, command map[string]any) (Response, error) { |
| 163 | c.mu.Lock() |
| 164 | if c.closed { |
| 165 | c.mu.Unlock() |
| 166 | return Response{}, ErrClosed |
| 167 | } |
| 168 | c.next++ |
| 169 | id := "equipo-" + strconv.Itoa(c.next) |
| 170 | ch := make(chan Response, 1) |
| 171 | c.pending[id] = ch |
| 172 | c.mu.Unlock() |
| 173 | cmd := map[string]any{"id": id} |
| 174 | for k, v := range command { |
| 175 | cmd[k] = v |
| 176 | } |
| 177 | if err := c.Send(ctx, cmd); err != nil { |
| 178 | c.mu.Lock() |
| 179 | delete(c.pending, id) |
| 180 | c.mu.Unlock() |
| 181 | return Response{}, err |
| 182 | } |
| 183 | select { |
| 184 | case <-ctx.Done(): |
| 185 | c.mu.Lock() |
| 186 | delete(c.pending, id) |
| 187 | c.mu.Unlock() |
| 188 | return Response{}, ctx.Err() |
| 189 | case r, ok := <-ch: |
| 190 | if !ok { |
| 191 | return Response{}, ErrClosed |
| 192 | } |
| 193 | if !r.Success { |
| 194 | return r, errors.New("pi: " + r.Command + " refused") |
| 195 | } |
| 196 | return r, nil |
| 197 | } |
| 198 | } |
| 199 | |