-
Notifications
You must be signed in to change notification settings - Fork 16
/
recording-mode.js
230 lines (200 loc) · 7.85 KB
/
recording-mode.js
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
226
227
228
229
230
import { swMsgs } from '../lib/constants'
import { openSectionsDB, SECTIONS_STORE } from '../lib/sections-db'
// Triggered on 'START_RECORDING' message
export function startRecording(event) {
console.debug('[SW] Starting recording')
if (!event.data.payload?.sectionId) {
throw new Error('[SW] No section ID specified to record')
}
const clientId = event.source.id // clientId from MessageEvent
// Throw error if another recording is in process
if (isClientRecording(clientId)) {
throw new Error(
"[SW] Can't start a new recording; a recording is already in process"
)
}
const newClientRecordingState = {
sectionId: event.data.payload?.sectionId,
pendingRequests: new Set(),
// `fulfilledRequests` can later hold useful data for normalization.
// Until then, it's just a count
fulfilledRequests: 0,
recordingTimeout: undefined,
recordingTimeoutDelay:
event.data.payload?.recordingTimeoutDelay || 1000,
confirmationTimeout: undefined,
}
self.clientRecordingStates[clientId] = newClientRecordingState
// Send confirmation message to client
self.clients.get(clientId).then(client => {
client.postMessage({ type: swMsgs.recordingStarted })
})
}
/** Used to check if a new recording can begin */
function isClientRecording(clientId) {
return clientId in self.clientRecordingStates
}
/** Used to check if requests should be handled by recording handler */
export function isClientRecordingRequests(clientId) {
// Don't record requests when waiting for completion confirmation
return (
isClientRecording(clientId) &&
self.clientRecordingStates[clientId].confirmationTimeout === undefined
)
}
/** Request handler during recording mode */
export function handleRecordedRequest({ request, event }) {
const recordingState = self.clientRecordingStates[event.clientId]
clearTimeout(recordingState.recordingTimeout)
recordingState.pendingRequests.add(request)
fetch(request)
.then(response => {
return handleRecordedResponse(request, response, event.clientId)
})
.catch(error => {
stopRecording(error, event.clientId)
})
}
/** Response handler during recording mode */
function handleRecordedResponse(request, response, clientId) {
const recordingState = self.clientRecordingStates[clientId]
if (!recordingState) {
// It's likely that the recording was stopped due to an error.
// There will be plenty of error messages logged; no need for another
// one here
return response
}
// add response to temp cache - when recording is successful, move to permanent cache
const tempCacheKey = getCacheKey('temp', clientId)
addToCache(tempCacheKey, request, response)
// normalizing data could happen here; until then, increment counter
recordingState.fulfilledRequests += 1
// remove request from pending requests
recordingState.pendingRequests.delete(request)
// start timer if pending requests are all complete
if (recordingState.pendingRequests.size === 0) {
startRecordingTimeout(clientId)
}
return response
}
/**
* Starts a timer that stops recording when finished. The timer will
* be cleared if a new request is handled and start again when there are
* no more pending requests.
*/
function startRecordingTimeout(clientId) {
const recordingState = self.clientRecordingStates[clientId]
recordingState.recordingTimeout = setTimeout(
() => stopRecording(null, clientId),
recordingState.recordingTimeoutDelay
)
}
/** Called on recording success or failure */
function stopRecording(error, clientId) {
const recordingState = self.clientRecordingStates[clientId]
if (recordingState) {
console.debug('[SW] Stopping recording', { clientId, recordingState })
clearTimeout(recordingState.recordingTimeout)
}
// In case of error, notify client and remove recording.
// Post message even if !recordingState to ensure client stops.
if (error) {
self.clients.get(clientId).then(client => {
// use plain object instead of Error for firefox compatibility
client.postMessage({
type: swMsgs.recordingError,
payload: {
msg: error.message,
},
})
})
removeRecording(clientId)
return
}
// On success, prompt client to confirm saving recording
requestCompletionConfirmation(clientId)
}
function getCacheKey(...args) {
return args.join('-')
}
function addToCache(cacheKey, request, response) {
if (response.ok) {
const responseClone = response.clone()
caches.open(cacheKey).then(cache => cache.put(request, responseClone))
}
}
function removeRecording(clientId) {
// Remove recording state
delete self.clientRecordingStates[clientId]
// Delete temp cache
const cacheKey = getCacheKey('temp', clientId)
return caches.delete(cacheKey)
}
/**
* To validate a completed recording, request an acknowledgement from
* the client before finishing and saving the recording. This prevents
* saving faulty recordings due to navigation or other problems and
* avoids overwriting a good recording
*/
async function requestCompletionConfirmation(clientId) {
const client = await self.clients.get(clientId)
if (!client) {
console.debug('[SW] Client not found for ID', clientId)
removeRecording(clientId)
return
}
client.postMessage({ type: swMsgs.confirmRecordingCompletion })
startConfirmationTimeout(clientId)
}
/**
* Wait 10 seconds for client acknowledgement to save recording. If timer
* runs out, the recording is scrapped.
*/
function startConfirmationTimeout(clientId) {
const recordingState = self.clientRecordingStates[clientId]
recordingState.confirmationTimeout = setTimeout(() => {
console.warn(
'[SW] Completion confirmation timed out. Clearing recording for client',
clientId
)
removeRecording(clientId)
}, 10000)
}
/** Triggered by 'COMPLETE_RECORDING' message; saves recording */
export async function completeRecording(clientId) {
try {
const recordingState = self.clientRecordingStates[clientId]
console.debug('[SW] Completing recording', { clientId, recordingState })
clearTimeout(recordingState.confirmationTimeout)
// If global state has reset, reopen IndexedDB
if (self.dbPromise === undefined) {
self.dbPromise = openSectionsDB()
}
// Add content to DB
const db = await self.dbPromise
db.put(SECTIONS_STORE, {
// Note that request objects can't be stored in the IDB
// https://stackoverflow.com/questions/32880073/whats-the-best-option-for-structured-cloning-of-a-fetch-api-request-object
sectionId: recordingState.sectionId, // the key path
lastUpdated: new Date(),
// 'requests' can later hold data for normalization
requests: recordingState.fulfilledRequests,
}).catch(console.error)
// Move requests from temp cache to section-<ID> cache
const sectionCache = await caches.open(recordingState.sectionId)
const tempCache = await caches.open(getCacheKey('temp', clientId))
const tempCacheItemKeys = await tempCache.keys()
tempCacheItemKeys.forEach(async request => {
const response = await tempCache.match(request)
sectionCache.put(request, response)
})
// Clean up
removeRecording(clientId)
// Send confirmation message to client
self.clients.get(clientId).then(client => {
client.postMessage({ type: swMsgs.recordingCompleted })
})
} catch (err) {
stopRecording(err, clientId)
}
}