forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
93 lines (80 loc) · 1.48 KB
/
stream.go
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
package sse
import (
"context"
"net/http"
"sync"
)
// Stream represents an output stream that data can be written to.
// Its methods must be safe to call concurrently.
type Stream interface {
Send(Event)
SentCount() int
Done()
SetLimit(limit int)
IsDone() bool
Err(error)
}
// NewStream creates a new stream against the provided response writer
func NewStream(ctx context.Context, w http.ResponseWriter, r *http.Request) Stream {
result := &stream{
ctx: ctx,
r: r,
w: w,
done: false,
sent: 0,
limit: 0,
}
return result
}
type stream struct {
ctx context.Context
r *http.Request
mu sync.Mutex // Mutex protects the following fields
w http.ResponseWriter
done bool
sent int
limit int
}
func (s *stream) Send(e Event) {
s.mu.Lock()
defer s.mu.Unlock()
if s.sent == 0 {
ok := WritePreamble(s.ctx, s.w)
if !ok {
s.done = true
return
}
}
WriteEvent(s.ctx, s.w, e)
s.sent++
}
func (s *stream) SentCount() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.sent
}
func (s *stream) SetLimit(limit int) {
s.mu.Lock()
defer s.mu.Unlock()
s.limit = limit
}
func (s *stream) Done() {
s.mu.Lock()
defer s.mu.Unlock()
WriteEvent(s.ctx, s.w, goodbyeEvent)
s.done = true
}
func (s *stream) IsDone() bool {
s.mu.Lock()
defer s.mu.Unlock()
if s.limit == 0 {
return s.done
}
return s.done || s.sent >= s.limit
}
func (s *stream) Err(err error) {
s.mu.Lock()
defer s.mu.Unlock()
WriteEvent(s.ctx, s.w, Event{Error: err})
s.done = true
}