forked from zabawaba99/firego
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwatch.go
203 lines (176 loc) · 4.73 KB
/
watch.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
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
package firego
import (
"bufio"
"encoding/json"
"log"
"strings"
"sync"
)
// EventTypeError is the type that is set on an Event struct if an
// error occurs while watching a Firebase reference
const EventTypeError = "event_error"
// Event represents a notification received when watching a
// firebase reference
type Event struct {
// Type of event that was received
Type string
// Path to the data that changed
Path string
// Data that changed
Data interface{}
}
// StopWatching stops tears down all connections that are watching
func (fb *Firebase) StopWatching() {
if fb.isWatching() {
// signal connection to terminal
fb.stopWatching <- struct{}{}
// flip the bit back to not watching
fb.setWatching(false)
}
}
func (fb *Firebase) isWatching() bool {
fb.watchMtx.Lock()
v := fb.watching
fb.watchMtx.Unlock()
return v
}
func (fb *Firebase) setWatching(v bool) {
fb.watchMtx.Lock()
fb.watching = v
fb.watchMtx.Unlock()
}
// Watch listens for changes on a firebase instance and
// passes over to the given chan.
//
// Only one connection can be established at a time. The
// second call to this function without a call to fb.StopWatching
// will close the channel given and return nil immediately
func (fb *Firebase) Watch(notifications chan Event) error {
if fb.isWatching() {
close(notifications)
return nil
}
// set watching flag
fb.setWatching(true)
// build SSE request
req, err := fb.makeRequest("GET", nil)
if err != nil {
fb.setWatching(false)
return err
}
req.Header.Add("Accept", "text/event-stream")
// do request
resp, err := fb.client.Do(req)
if err != nil {
fb.setWatching(false)
return err
}
// start parsing response body
go func() {
// build scanner for response body
scanner := bufio.NewReader(resp.Body)
var (
scanErr error
closedManually bool
mtx sync.Mutex
)
// monitor the stopWatching channel
// if we're told to stop, close the response Body
go func() {
<-fb.stopWatching
mtx.Lock()
closedManually = true
mtx.Unlock()
resp.Body.Close()
}()
scanning:
for scanErr == nil {
// split event string
// event: put
// data: {"path":"/","data":{"foo":"bar"}}
var evt []byte
var dat []byte
isPrefix := true
var result []byte
// For possible results larger than 64 * 1024 bytes (MaxTokenSize)
// we need bufio#ReadLine()
// 1. step: scan for the 'event:' part. ReadLine() oes not return the \n
// so we have to add it to our result buffer.
evt, isPrefix, scanErr = scanner.ReadLine()
if scanErr != nil {
break scanning
}
result = append(result, evt...)
result = append(result, '\n')
// 2. step: scan for the 'data:' part. Firebase returns just one 'data:'
// part, but the value can be very large. If we exceed a certain length
// isPrefix will be true until all data is read.
for {
dat, isPrefix, scanErr = scanner.ReadLine()
if scanErr != nil {
break scanning
}
result = append(result, dat...)
if !isPrefix {
break
}
}
// Again we add the \n
result = append(result, '\n')
_, _, scanErr = scanner.ReadLine()
if scanErr != nil {
break scanning
}
txt := string(result)
parts := strings.Split(txt, "\n")
// create a base event
event := Event{
Type: strings.Replace(parts[0], "event: ", "", 1),
}
// should be reacting differently based off the type of event
switch event.Type {
case "put", "patch": // we've got extra data we've got to parse
// the extra data is in json format
var data map[string]interface{}
if err := json.Unmarshal([]byte(strings.Replace(parts[1], "data: ", "", 1)), &data); err != nil {
scanErr = err
break scanning
}
// set the extra fields
event.Path = data["path"].(string)
event.Data = data["data"]
// ship it
notifications <- event
case "keep-alive":
// received ping - nothing to do here
case "cancel":
// The data for this event is null
// This event will be sent if the Security and Firebase Rules
// cause a read at the requested location to no longer be allowed
// send the cancel event
notifications <- event
break scanning
case "auth_revoked":
// The data for this event is a string indicating that a the credential has expired
// This event will be sent when the supplied auth parameter is no longer valid
// TODO: handle
case "rules_debug":
log.Printf("Rules-Debug: %s\n", txt)
}
}
// check error type
mtx.Lock()
closed := closedManually
mtx.Unlock()
if !closed && scanErr != nil {
notifications <- Event{
Type: EventTypeError,
Data: scanErr,
}
}
// call stop watching to reset state and cleanup routines
fb.StopWatching()
close(notifications)
}()
return nil
}