Skip to content

Commit

Permalink
✨ [RUM-249] add streamId to error responses
Browse files Browse the repository at this point in the history
  • Loading branch information
BenoitZugmeyer committed Jul 20, 2023
1 parent 4930e01 commit 8598c9e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,21 @@ describe('createDeflateWorker', () => {
deflateWorker.postMessage({ id: 2, streamId: 1, action: 'write', data: 'baz' })
})

it('reports an error when an unexpected exception occurs', (done) => {
const deflateWorker = createDeflateWorker()
listen(deflateWorker, 1, (events) => {
expect(events).toEqual([
{
type: 'errored',
error: new TypeError("Cannot read properties of null (reading 'action')"),
streamId: undefined,
},
])
done()
})
deflateWorker.postMessage(null as any)
})

function listen(
deflateWorker: DeflateWorker,
expectedResponseCount: number,
Expand Down
49 changes: 24 additions & 25 deletions packages/worker/src/boot/startWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,37 @@ import { Deflate, constants, string2buf } from '../domain/deflate'
import type { DeflateWorkerAction, DeflateWorkerResponse } from '../types'

export function startWorker() {
monitor(() => {
try {
const streams = new Map<number, Deflate>()
self.addEventListener(
'message',
monitor((event: MessageEvent<DeflateWorkerAction>) => {
self.addEventListener('message', (event: MessageEvent<DeflateWorkerAction>) => {
try {
const response = handleAction(streams, event.data)
if (response) {
self.postMessage(response)
}
})
)
})()
} catch (error) {
sendError(error, event.data && 'streamId' in event.data ? event.data.streamId : undefined)
}
})
} catch (error) {
sendError(error)
}
}

function monitor<Args extends any[], Result>(fn: (...args: Args) => Result): (...args: Args) => Result | undefined {
return (...args) => {
try {
return fn(...args)
} catch (e) {
try {
self.postMessage({
type: 'errored',
error: e,
})
} catch (_) {
// DATA_CLONE_ERR, cf https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
self.postMessage({
type: 'errored',
error: String(e),
})
}
}
function sendError(error: unknown, streamId?: number) {
try {
self.postMessage({
type: 'errored',
error,
streamId,
})
} catch (_) {
// DATA_CLONE_ERR, cf https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
self.postMessage({
type: 'errored',
error: String(error),
streamId,
})
}
}

Expand Down

0 comments on commit 8598c9e

Please sign in to comment.