Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
183 lines (154 loc) · 4.34 KB
/
Copy pathclient.go
File metadata and controls
183 lines (154 loc) · 4.34 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
//go:build wasm
package sse
import (
"syscall/js"
"webtyp.com/backoff"
"webtyp.com/time"
"webtyp.com/fmt"
)
type eventListener struct {
name string
handler func(msg *SSEMessage)
fn js.Func
attached bool
}
// SSEClient is the SSE client for WASM.
type SSEClient struct {
tinySSE *tinySSE
config *ClientConfig
handler func(msg *SSEMessage)
errorHandler func(err error)
es js.Value
reconnectAttempts int
lastEventID string
listeners []*eventListener
}
// Client creates a new SSEClient instance.
func (t *tinySSE) Client(c *ClientConfig) *SSEClient {
return &SSEClient{
tinySSE: t,
config: c,
}
}
func (c *SSEClient) parseSSEEvent(event js.Value) *SSEMessage {
c.reconnectAttempts = 0 // Reset on successful message
dataStr := event.Get("data").String()
eventID := event.Get("lastEventId").String()
eventType := event.Get("type").String()
if eventID != "" {
c.lastEventID = eventID
}
return &SSEMessage{
Id: eventID,
Event: eventType,
Data: []byte(dataStr),
}
}
// OnEvent registers a handler for SSE frames whose event name is name
// (frames published with PublishEvent or through sse.Publisher).
// OnMessage keeps receiving only unnamed frames. Handlers registered before
// or after Connect both work, and survive reconnects.
func (c *SSEClient) OnEvent(name string, handler func(msg *SSEMessage)) {
el := &eventListener{
name: name,
handler: handler,
}
c.listeners = append(c.listeners, el)
if !c.es.IsUndefined() && !c.es.IsNull() {
c.attachListener(el)
}
}
func (c *SSEClient) attachListener(el *eventListener) {
if el.attached {
return
}
el.fn = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
msg := c.parseSSEEvent(args[0])
if el.handler != nil {
el.handler(msg)
}
return nil
})
c.es.Call("addEventListener", el.name, el.fn)
el.attached = true
}
// Connect establishes a connection to the SSE endpoint.
func (c *SSEClient) Connect() {
url := c.config.Endpoint
c.es = js.Global().Get("EventSource").New(url)
c.es.Set("onmessage", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
msg := c.parseSSEEvent(args[0])
if c.handler != nil {
c.handler(msg)
}
return nil
}))
c.es.Set("onerror", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
readyState := c.es.Get("readyState").Int()
if c.errorHandler != nil {
c.errorHandler(fmt.Err("SSE connection error", "connection state", readyState))
}
if readyState == 2 {
c.reconnect()
}
return nil
}))
c.es.Set("onopen", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
c.reconnectAttempts = 0
return nil
}))
// Re-attach all listeners to the new EventSource instance
for _, el := range c.listeners {
el.attached = false
c.attachListener(el)
}
}
// Close closes the SSE connection.
func (c *SSEClient) Close() {
if !c.es.IsUndefined() && !c.es.IsNull() {
c.es.Call("close")
}
}
// OnMessage sets the handler for incoming messages.
func (c *SSEClient) OnMessage(handler func(msg *SSEMessage)) {
c.handler = handler
}
// OnError sets the handler for errors.
func (c *SSEClient) OnError(handler func(err error)) {
c.errorHandler = handler
}
func (c *SSEClient) reconnect() {
c.Close()
if c.config.MaxReconnectAttempts > 0 && c.reconnectAttempts >= c.config.MaxReconnectAttempts {
if c.errorHandler != nil {
c.errorHandler(fmt.Err("max reconnect attempts reached"))
}
return
}
delay, err := c.reconnectDelay()
if err != nil {
if c.errorHandler != nil {
c.errorHandler(err)
}
return
}
js.Global().Call("setTimeout", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
c.Connect()
return nil
}), delay)
c.reconnectAttempts++
}
// reconnectDelay answers, in milliseconds, how long to wait before the next reconnection: the delay doubles after each
// failed attempt, from RetryInterval up to MaxRetryDelay (the policy is webtyp.com/backoff). An invalid pair of values
// is an error: it is never replaced by a default.
func (c *SSEClient) reconnectDelay() (int, error) {
policy, err := backoff.New(time.Duration(c.config.RetryInterval)*time.Millisecond, time.Duration(c.config.MaxRetryDelay)*time.Millisecond)
if err != nil {
return 0, err
}
wait, err := policy.DelayAfter(int64(c.reconnectAttempts) + 1)
if err != nil {
return 0, err
}
return int(wait.Milliseconds()), nil
}