-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathlisten.ts
225 lines (193 loc) · 6.68 KB
/
listen.ts
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
import {Observable} from 'rxjs'
import type {ObservableSanityClient, SanityClient} from '../SanityClient'
import type {Any, ListenEvent, ListenOptions, ListenParams, MutationEvent} from '../types'
import defaults from '../util/defaults'
import {pick} from '../util/pick'
import {_getDataUrl} from './dataMethods'
import {encodeQueryString} from './encodeQueryString'
// Limit is 16K for a _request_, eg including headers. Have to account for an
// unknown range of headers, but an average EventSource request from Chrome seems
// to have around 700 bytes of cruft, so let us account for 1.2K to be "safe"
const MAX_URL_LENGTH = 16000 - 1200
const possibleOptions = [
'includePreviousRevision',
'includeResult',
'includeMutations',
'visibility',
'effectFormat',
'tag',
]
const defaultOptions = {
includeResult: true,
}
/**
* Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.
*
* @param query - GROQ-filter to listen to changes for
* @param params - Optional query parameters
* @param options - Optional listener options
* @public
*/
export function _listen<R extends Record<string, Any> = Record<string, Any>>(
this: SanityClient | ObservableSanityClient,
query: string,
params?: ListenParams,
): Observable<MutationEvent<R>>
/**
* Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.
*
* @param query - GROQ-filter to listen to changes for
* @param params - Optional query parameters
* @param options - Optional listener options
* @public
*/
export function _listen<R extends Record<string, Any> = Record<string, Any>>(
this: SanityClient | ObservableSanityClient,
query: string,
params?: ListenParams,
options?: ListenOptions,
): Observable<ListenEvent<R>>
/** @public */
export function _listen<R extends Record<string, Any> = Record<string, Any>>(
this: SanityClient | ObservableSanityClient,
query: string,
params?: ListenParams,
opts: ListenOptions = {},
): Observable<MutationEvent<R> | ListenEvent<R>> {
const {url, token, withCredentials, requestTagPrefix} = this.config()
const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join('.') : opts.tag
const options = {...defaults(opts, defaultOptions), tag}
const listenOpts = pick(options, possibleOptions)
const qs = encodeQueryString({query, params, options: {tag, ...listenOpts}})
const uri = `${url}${_getDataUrl(this, 'listen', qs)}`
if (uri.length > MAX_URL_LENGTH) {
return new Observable((observer) => observer.error(new Error('Query too large for listener')))
}
const listenFor = options.events ? options.events : ['mutation']
const shouldEmitReconnect = listenFor.indexOf('reconnect') !== -1
const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}
if (token || withCredentials) {
esOptions.withCredentials = true
}
if (token) {
esOptions.headers = {
Authorization: `Bearer ${token}`,
}
}
return new Observable((observer) => {
let es: InstanceType<typeof import('@sanity/eventsource')>
let reconnectTimer: NodeJS.Timeout
let stopped = false
// Unsubscribe differs from stopped in that we will never reopen.
// Once it is`true`, it will never be `false` again.
let unsubscribed = false
open()
function onError() {
if (stopped) {
return
}
emitReconnect()
// Allow event handlers of `emitReconnect` to cancel/close the reconnect attempt
if (stopped) {
return
}
// Unless we've explicitly stopped the ES (in which case `stopped` should be true),
// we should never be in a disconnected state. By default, EventSource will reconnect
// automatically, in which case it sets readyState to `CONNECTING`, but in some cases
// (like when a laptop lid is closed), it closes the connection. In these cases we need
// to explicitly reconnect.
if (es.readyState === es.CLOSED) {
unsubscribe()
clearTimeout(reconnectTimer)
reconnectTimer = setTimeout(open, 100)
}
}
function onChannelError(err: Any) {
observer.error(cooerceError(err))
}
function onMessage(evt: Any) {
const event = parseEvent(evt)
return event instanceof Error ? observer.error(event) : observer.next(event)
}
function onDisconnect() {
stopped = true
unsubscribe()
observer.complete()
}
function unsubscribe() {
if (!es) return
es.removeEventListener('error', onError)
es.removeEventListener('channelError', onChannelError)
es.removeEventListener('disconnect', onDisconnect)
listenFor.forEach((type: string) => es.removeEventListener(type, onMessage))
es.close()
}
function emitReconnect() {
if (shouldEmitReconnect) {
observer.next({type: 'reconnect'})
}
}
async function getEventSource(): Promise<InstanceType<
typeof import('@sanity/eventsource')
> | void> {
const {default: EventSource} = await import('@sanity/eventsource')
// If the listener has been unsubscribed from before we managed to load the module,
// do not set up the EventSource.
if (unsubscribed) {
return
}
const evs = new EventSource(uri, esOptions)
evs.addEventListener('error', onError)
evs.addEventListener('channelError', onChannelError)
evs.addEventListener('disconnect', onDisconnect)
listenFor.forEach((type: string) => evs.addEventListener(type, onMessage))
return evs
}
function open() {
getEventSource()
.then((eventSource) => {
if (eventSource) {
es = eventSource
// Handle race condition where the observer is unsubscribed before the EventSource is set up
if (unsubscribed) {
unsubscribe()
}
}
})
.catch((reason) => {
observer.error(reason)
stop()
})
}
function stop() {
stopped = true
unsubscribe()
unsubscribed = true
}
return stop
})
}
function parseEvent(event: Any) {
try {
const data = (event.data && JSON.parse(event.data)) || {}
return Object.assign({type: event.type}, data)
} catch (err) {
return err
}
}
function cooerceError(err: Any) {
if (err instanceof Error) {
return err
}
const evt = parseEvent(err)
return evt instanceof Error ? evt : new Error(extractErrorMessage(evt))
}
function extractErrorMessage(err: Any) {
if (!err.error) {
return err.message || 'Unknown listener error'
}
if (err.error.description) {
return err.error.description
}
return typeof err.error === 'string' ? err.error : JSON.stringify(err.error, null, 2)
}