Repository navigation
Expand file tree
/
Copy pathstream.go
More file actions
71 lines (65 loc) · 1.58 KB
/
Copy pathstream.go
File metadata and controls
71 lines (65 loc) · 1.58 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
package synthient
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"iter"
"net/http"
)
const maxEventSize = 16 << 20
// Stream returns an iterator over the feed's real-time events. Each range
// opens a new connection, which the server can close at any time, such as
// during a deploy; that close ends the iteration without an error. Any other
// failure is yielded once and ends the iteration. Breaking out of the loop
// closes the connection. Events sent between connections are missed, so
// range again to reconnect.
func (f *Feed[T]) Stream(ctx context.Context) iter.Seq2[T, error] {
return func(yield func(T, error) bool) {
var zero T
resp, err := f.client.send(ctx, request{
method: http.MethodGet,
path: f.path + "/stream",
accept: "application/x-ndjson",
})
if err != nil {
yield(zero, err)
return
}
if resp.StatusCode != http.StatusOK {
defer closeBody(resp)
yield(zero, newAPIError(resp))
return
}
defer func() {
_ = resp.Body.Close()
}()
scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 0, 64<<10), maxEventSize)
for scanner.Scan() {
line := bytes.TrimSpace(scanner.Bytes())
if len(line) == 0 {
continue
}
var event T
err := json.Unmarshal(line, &event)
if err != nil {
yield(zero, fmt.Errorf("synthient: decode stream event: %w", err))
return
}
if !yield(event, nil) {
return
}
}
err = scanner.Err()
if err == nil {
return
}
ctxErr := ctx.Err()
if ctxErr != nil {
err = ctxErr
}
yield(zero, fmt.Errorf("synthient: read stream: %w", err))
}
}