Skip to content

Commit

Permalink
Wait for Chelonia, more error logs
Browse files Browse the repository at this point in the history
  • Loading branch information
corrideat committed Dec 18, 2024
1 parent df255f8 commit 78f539f
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
28 changes: 28 additions & 0 deletions frontend/controller/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,34 @@ sbp('sbp/selectors/register', {
await swRegistration.update()
setInterval(() => sbp('service-worker/update'), HOURS_MILLIS)

// Send a 'ready' message to the SW and wait back for a response
// This way we ensure that Chelonia has been set up
await new Promise((resolve, reject) => {
const messageChannel = new MessageChannel()
messageChannel.port1.onmessage = (event) => {
if (event.data.type === 'ready') {
resolve()
} else {
reject(event.data.error)
}
messageChannel.port1.close()
}
messageChannel.port1.onmessageerror = () => {
reject(new Error('Message error'))
messageChannel.port1.close()
}

navigator.serviceWorker.ready.then(() => {
navigator.serviceWorker.controller.postMessage({
type: 'ready',
port: messageChannel.port2
}, [messageChannel.port2])
}).catch((e) => {
reject(e)
messageChannel.port1.close()
})
})

// Keep the service worker alive while the window is open
// The default idle timeout on Chrome and Firefox is 30 seconds. We send
// a ping message every 5 seconds to ensure that the worker remains
Expand Down
20 changes: 20 additions & 0 deletions frontend/controller/serviceworkers/sw-primary.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,26 @@ self.addEventListener('message', function (event) {
case 'event':
sbp('okTurtles.events/emit', event.data.subtype, ...deserializer(event.data.data))
break
case 'ready': {
// The 'ready' message is sent by a client (i.e., a tab or window) to
// ensure that Chelonia has been setup
const port = event.data.port
Promise.race([
setupChelonia(),
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Timed out setting up Chelonia'))
}, 30e3)
})
]).then(() => {
port.postMessage({ type: 'ready' })
}, (e) => {
port.postMessage({ type: 'error', error: e })
}).finally(() => {
port.close()
})
break
}
default:
console.error('[sw] unknown message type:', event.data)
break
Expand Down
1 change: 1 addition & 0 deletions frontend/setupChelonia.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ export default ((() => {
return () => {
if (!promise) {
promise = setupChelonia().catch((e) => {
console.error('[setupChelonia] Error during chelonia setup', e)
promise = undefined // Reset on error
throw e // Re-throw the error
})
Expand Down

0 comments on commit 78f539f

Please sign in to comment.