| 1 | import { BroadcastChannel } from 'node:worker_threads'; |
| 2 | |
| 3 | import type { |
| 4 | BroadcastChannelRequest, |
| 5 | BroadcastChannelResponse, |
| 6 | JsonType, |
| 7 | MessageEvent, |
| 8 | } from '../../types'; |
| 9 | import { logPrefix, logger, validateUUID } from '../../utils'; |
| 10 | |
| 11 | const moduleName = 'WorkerBroadcastChannel'; |
| 12 | |
| 13 | export abstract class WorkerBroadcastChannel extends BroadcastChannel { |
| 14 | protected constructor() { |
| 15 | super('worker'); |
| 16 | } |
| 17 | |
| 18 | public sendRequest(request: BroadcastChannelRequest): void { |
| 19 | this.postMessage(request); |
| 20 | } |
| 21 | |
| 22 | protected sendResponse(response: BroadcastChannelResponse): void { |
| 23 | this.postMessage(response); |
| 24 | } |
| 25 | |
| 26 | protected isRequest(message: JsonType[]): boolean { |
| 27 | return Array.isArray(message) === true && message.length === 3; |
| 28 | } |
| 29 | |
| 30 | protected isResponse(message: JsonType[]): boolean { |
| 31 | return Array.isArray(message) === true && message.length === 2; |
| 32 | } |
| 33 | |
| 34 | protected validateMessageEvent(messageEvent: MessageEvent): MessageEvent | false { |
| 35 | if (Array.isArray(messageEvent.data) === false) { |
| 36 | logger.error( |
| 37 | `${this.logPrefix( |
| 38 | moduleName, |
| 39 | 'validateMessageEvent', |
| 40 | )} Worker broadcast channel protocol message event data is not an array`, |
| 41 | ); |
| 42 | return false; |
| 43 | } |
| 44 | if (validateUUID(messageEvent.data[0]) === false) { |
| 45 | logger.error( |
| 46 | `${this.logPrefix( |
| 47 | moduleName, |
| 48 | 'validateMessageEvent', |
| 49 | )} Worker broadcast channel protocol message event data UUID field is invalid`, |
| 50 | ); |
| 51 | return false; |
| 52 | } |
| 53 | return messageEvent; |
| 54 | } |
| 55 | |
| 56 | private logPrefix = (modName: string, methodName: string): string => { |
| 57 | return logPrefix(` Worker Broadcast Channel | ${modName}.${methodName}:`); |
| 58 | }; |
| 59 | } |