-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstream.go
More file actions
315 lines (267 loc) · 7.87 KB
/
Copy pathstream.go
File metadata and controls
315 lines (267 loc) · 7.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package client
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"sync"
"sync/atomic"
// Packages
httpresponse "github.com/mutablelogic/go-server/pkg/httpresponse"
types "github.com/mutablelogic/go-server/pkg/types"
errgroup "golang.org/x/sync/errgroup"
)
///////////////////////////////////////////////////////////////////////////////
// TYPES
type jsonstream struct {
req *jsonrequest // The request payload used to send frames to the server
response *http.Response // The response from the server, used to read frames from the server
reader *bufio.Reader // The buffered reader used to read frames from the server
ready chan struct{} // A channel that signals when the stream is ready to receive frames
ctx context.Context // The context for the stream, used to cancel operations
cancel context.CancelFunc // Cancel the stream when the receive loop encounters a fatal error
recvch chan json.RawMessage // The channel used to receive JSON frames
cancelReadClose func() bool // A function to cancel the read and close operations
}
// JSONStream is an interface representing a bi-directional JSON streaming connection. Start a connection
// with Client.Stream, which provides a callback with a JSONStream to send and receive frames.
// Return from the callback to close the stream. The stream is also closed if the context passed
// to Client.Stream is canceled.
type JSONStream interface {
Recv() <-chan json.RawMessage
Send(json.RawMessage) error
}
///////////////////////////////////////////////////////////////////////////////
// LIFECYCLE
// Stream opens a bi-directional JSON streaming connection.
func (client *Client) Stream(ctx context.Context, callback func(context.Context, JSONStream) error, opts ...RequestOpt) error {
// Probe the server to ensure it supports JSON streaming before opening the stream
probe, err := client.request(ctx, http.MethodPost, types.ContentTypeJSONStream, types.ContentTypeJSONStream, bytes.NewReader([]byte{'\n'}))
if err != nil {
return err
} else if err := do(client.Client, probe, types.ContentTypeJSONStream, true, nil, opts...); err != nil {
return err
}
// Create a new context for the stream, which will be canceled when the stream is closed
streamctx, cancel := context.WithCancel(ctx)
defer cancel()
// Create an group of goroutines, and a new context
errgroup, errctx := errgroup.WithContext(streamctx)
// Create a new streaming request
req, err := client.NewStreamRequest(errctx)
if err != nil {
return err
}
// Create the JSON stream, which will be shared between the two go routines
self := types.Ptr(jsonstream{
req: req,
ctx: errctx,
cancel: cancel,
ready: make(chan struct{}),
recvch: make(chan json.RawMessage, 16),
})
go self.recvLoop()
// Open the stream in one go routine
errgroup.Go(func() error {
defer close(self.ready)
// Open the stream, return any errors
response, err := client.stream(req, opts...)
if err != nil {
return errors.Join(err, req.Close())
} else {
self.response = response
self.reader = bufio.NewReader(response.Body)
self.cancelReadClose = context.AfterFunc(errctx, func() {
response.Body.Close()
})
}
// Return success
return nil
})
// Start the callback in a second go routine
errgroup.Go(func() error {
// Cancel the stream context when the callback returns, which will signal the receive loop to exit
defer cancel()
// Return any errors from the callback
return callback(errctx, self)
})
// Wait for both go routines to finish, close request, and return any errors
result := errgroup.Wait()
if self.cancelReadClose != nil {
_ = self.cancelReadClose()
}
if self.response != nil && self.response.Body != nil {
result = errors.Join(result, self.response.Body.Close())
}
if self.req != nil {
result = errors.Join(result, self.req.Close())
}
return result
}
func (s *jsonstream) Recv() <-chan json.RawMessage {
return s.recvch
}
func (s *jsonstream) recvLoop() {
defer close(s.recvch)
select {
case <-s.ready:
case <-s.ctx.Done():
return
}
if s.reader == nil {
return
}
for {
line, err := s.reader.ReadBytes('\n')
if err != nil && (err != io.EOF || len(line) == 0) {
s.cancel()
return
}
frame := bytes.TrimSpace(line)
if len(frame) == 0 {
if !s.pushFrame(nil) {
return
}
if err == io.EOF {
s.cancel()
return
}
continue
}
var raw json.RawMessage
if err := json.Unmarshal(frame, &raw); err != nil {
s.cancel()
return
}
if !s.pushFrame(raw) {
return
}
if err == io.EOF {
s.cancel()
return
}
}
}
func (s *jsonstream) pushFrame(frame json.RawMessage) bool {
select {
case <-s.ctx.Done():
return false
case s.recvch <- frame:
return true
default:
// Avoid deadlocking the full-duplex connection when the callback stops
// draining the response side of the stream.
s.cancel()
return false
}
}
func (s *jsonstream) Send(frame json.RawMessage) error {
return s.req.Send(frame)
}
///////////////////////////////////////////////////////////////////////////////
// REQUEST PAYLOAD
type jsonrequest struct {
*http.Request
reader *io.PipeReader
writer *io.PipeWriter
mu sync.Mutex
closed atomic.Bool
}
var _ Payload = (*jsonrequest)(nil)
var _ io.ReadCloser = (*jsonrequest)(nil)
func (c *Client) NewStreamRequest(ctx context.Context) (*jsonrequest, error) {
r, w := io.Pipe()
body := types.Ptr(jsonrequest{
reader: r,
writer: w,
})
// Open the stream
req, err := c.request(ctx, http.MethodPost, types.ContentTypeJSONStream, types.ContentTypeJSONStream, body)
if err != nil {
body.Close()
return nil, err
} else {
body.Request = req
}
// Return success
return body, nil
}
func (r *jsonrequest) Method() string {
return http.MethodPost
}
func (r *jsonrequest) Accept() string {
return types.ContentTypeJSONStream
}
func (r *jsonrequest) Type() string {
return types.ContentTypeJSONStream
}
func (r *jsonrequest) Read(p []byte) (int, error) {
return r.reader.Read(p)
}
func (r *jsonrequest) Send(frame json.RawMessage) error {
if r.closed.Load() {
return io.ErrClosedPipe
}
// Encode the frame, pack it onto a single line
var buf bytes.Buffer
if err := json.Compact(&buf, frame); err != nil {
return httpresponse.ErrBadRequest.Withf("invalid json frame: %v", err)
}
// Write the frame followed by a newline
r.mu.Lock()
defer r.mu.Unlock()
if _, err := r.writer.Write(buf.Bytes()); err != nil {
return err
} else if _, err := r.writer.Write([]byte{'\n'}); err != nil {
return err
}
// Return success
return nil
}
func (r *jsonrequest) Close() error {
if r.closed.Swap(true) {
return nil
}
return r.writer.Close()
}
///////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
// Start the request and wait until response headers arrive, the context is
// canceled, or an error occurs. The returned response body remains open for
// streaming.
func (client *Client) stream(req *jsonrequest, opts ...RequestOpt) (*http.Response, error) {
// Apply request options
reqopts := requestOpts{
Request: req.Request,
}
for _, opt := range opts {
if err := opt(&reqopts); err != nil {
return nil, err
}
}
// Create a client, set timeout and add transports
httpclient := types.Value(client.Client)
if reqopts.noTimeout {
httpclient.Timeout = 0
}
if len(reqopts.transports) > 0 {
t := httpclient.Transport
for i := len(reqopts.transports) - 1; i >= 0; i-- {
t = reqopts.transports[i](t)
}
httpclient.Transport = t
}
// Perform the request, return any errors
response, err := httpclient.Do(req.Request)
if err != nil {
return nil, err
} else if response.StatusCode < 200 || response.StatusCode > 299 {
defer response.Body.Close()
return nil, httpresponse.Err(response.StatusCode).With(response.Status)
}
// Return success
return response, nil
}