Skip to content

Commit

Permalink
Fix infinite loop on NEW_CHATROOM_UNREAD_POSITION
Browse files Browse the repository at this point in the history
  • Loading branch information
corrideat committed Dec 18, 2024
1 parent 2932ea3 commit 7432b75
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
8 changes: 7 additions & 1 deletion frontend/controller/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,18 @@ sbp('sbp/selectors/register', {
})

// Events that need to be relayed to the SW
;[LOGIN_COMPLETE, NEW_CHATROOM_UNREAD_POSITION, SET_APP_LOGS_FILTER].forEach((event) =>
;[LOGIN_COMPLETE, SET_APP_LOGS_FILTER].forEach((event) =>
sbp('okTurtles.events/on', event, (...data) => {
navigator.serviceWorker.controller?.postMessage({ type: 'event', subtype: event, data })
})
)

sbp('okTurtles.events/on', NEW_CHATROOM_UNREAD_POSITION, (obj: Object) => {
// Don't send messages from the SW back to the SW to prevent infinite loops
if (obj.from === 'sw') return
navigator.serviceWorker.controller?.postMessage({ type: 'event', subtype: event, data: [obj] })
})

const swRpc = (() => {
if (!navigator.serviceWorker) {
throw new Error('Missing service worker object')
Expand Down
22 changes: 21 additions & 1 deletion frontend/controller/serviceworkers/sw-primary.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ sbp('okTurtles.events/on', CHELONIA_RESET, setupRootState)
LOGIN_ERROR, LOGOUT, ACCEPTED_GROUP, CHATROOM_USER_STOP_TYPING,
CHATROOM_USER_TYPING, DELETED_CHATROOM, LEFT_CHATROOM, LEFT_GROUP,
JOINED_CHATROOM, JOINED_GROUP, KV_EVENT, MESSAGE_RECEIVE, MESSAGE_SEND,
NAMESPACE_REGISTRATION, NEW_CHATROOM_UNREAD_POSITION, NEW_LAST_LOGGED_IN,
NAMESPACE_REGISTRATION, NEW_LAST_LOGGED_IN,
NEW_PREFERENCES, NEW_UNREAD_MESSAGES, NOTIFICATION_EMITTED,
NOTIFICATION_REMOVED, NOTIFICATION_STATUS_LOADED, OFFLINE, ONLINE,
PROPOSAL_ARCHIVED, SERIOUS_ERROR, SWITCH_GROUP
Expand All @@ -108,6 +108,26 @@ sbp('okTurtles.events/on', CHELONIA_RESET, setupRootState)
})
})

// This event (`NEW_CHATROOM_UNREAD_POSITION`) requires special handling because
// it can be sent from the SW to clients or from clients to the SW. Handling it
// the normal way (in the forwarding logic above) would result in event loops.
sbp('okTurtles.events/on', NEW_CHATROOM_UNREAD_POSITION, (args) => {
// Set a 'from' parameter to signal it comes from the SW
const argsCopy = { ...args, from: 'sw' }
const { data } = serializer(argsCopy)
const message = {
type: 'event',
subtype: NEW_CHATROOM_UNREAD_POSITION,
data
}
self.clients.matchAll()
.then((clientList) => {
clientList.forEach((client) => {
client.postMessage(message)
})
})
})

// Logs are treated especially to avoid spamming logs with event emitted
// entries
sbp('okTurtles.events/on', CAPTURED_LOGS, (...args) => {
Expand Down

0 comments on commit 7432b75

Please sign in to comment.