|
| 1 | +import { anyPass, map, path } from 'ramda' |
| 2 | +import { RawData, WebSocket } from 'ws' |
| 3 | +import cluster from 'cluster' |
| 4 | +import { randomUUID } from 'crypto' |
| 5 | + |
| 6 | +import { createRelayedEventMessage, createSubscriptionMessage } from '../utils/messages' |
| 7 | +import { isEventIdValid, isEventMatchingFilter, isEventSignatureValid } from '../utils/event' |
| 8 | +import { Mirror, Settings } from '../@types/settings' |
| 9 | +import { createLogger } from '../factories/logger-factory' |
| 10 | +import { IRunnable } from '../@types/base' |
| 11 | +import { OutgoingEventMessage } from '../@types/messages' |
| 12 | +import { WebSocketServerAdapterEvent } from '../constants/adapter' |
| 13 | + |
| 14 | +const debug = createLogger('static-mirror-worker') |
| 15 | + |
| 16 | +export class StaticMirroringWorker implements IRunnable { |
| 17 | + private client: WebSocket | undefined |
| 18 | + private config: Mirror |
| 19 | + |
| 20 | + public constructor( |
| 21 | + private readonly process: NodeJS.Process, |
| 22 | + private readonly settings: () => Settings, |
| 23 | + ) { |
| 24 | + this.process |
| 25 | + .on('message', this.onMessage.bind(this)) |
| 26 | + .on('SIGINT', this.onExit.bind(this)) |
| 27 | + .on('SIGHUP', this.onExit.bind(this)) |
| 28 | + .on('SIGTERM', this.onExit.bind(this)) |
| 29 | + .on('uncaughtException', this.onError.bind(this)) |
| 30 | + .on('unhandledRejection', this.onError.bind(this)) |
| 31 | + } |
| 32 | + |
| 33 | + public run(): void { |
| 34 | + const currentSettings = this.settings() |
| 35 | + |
| 36 | + console.log('mirroring', currentSettings.mirroring) |
| 37 | + |
| 38 | + this.config = path(['mirroring', 'static', process.env.MIRROR_INDEX], currentSettings) as Mirror |
| 39 | + |
| 40 | + let since = Math.floor(Date.now() / 1000) - 60*10 |
| 41 | + |
| 42 | + const createMirror = (config: Mirror) => { |
| 43 | + const subscriptionId = `mirror-${randomUUID()}` |
| 44 | + |
| 45 | + debug('connecting to %s', config.address) |
| 46 | + |
| 47 | + return new WebSocket(config.address, { timeout: 5000 }) |
| 48 | + .on('open', function () { |
| 49 | + debug('connected to %s', config.address) |
| 50 | + |
| 51 | + if (Array.isArray(config.filters) && config.filters?.length) { |
| 52 | + const filters = config.filters.map((filter) => ({ ...filter, since })) |
| 53 | + |
| 54 | + debug('subscribing with %s: %o', subscriptionId, filters) |
| 55 | + |
| 56 | + this.send(JSON.stringify(createSubscriptionMessage(subscriptionId, filters))) |
| 57 | + } |
| 58 | + }) |
| 59 | + .on('message', async function (raw: RawData) { |
| 60 | + try { |
| 61 | + const message = JSON.parse(raw.toString('utf8')) as OutgoingEventMessage |
| 62 | + debug('received: %o', message) |
| 63 | + |
| 64 | + if (!Array.isArray(message)) { |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + if (message[0] !== 'EVENT' || message[1] !== subscriptionId) { |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + const event = message[2] |
| 73 | + |
| 74 | + if (!anyPass(map(isEventMatchingFilter, config.filters))(event)) { |
| 75 | + return |
| 76 | + } |
| 77 | + |
| 78 | + if (!await isEventIdValid(event) || !await isEventSignatureValid(event)) { |
| 79 | + return |
| 80 | + } |
| 81 | + |
| 82 | + since = Math.floor(Date.now()) - 30 |
| 83 | + |
| 84 | + if (cluster.isWorker && typeof process.send === 'function') { |
| 85 | + process.send({ |
| 86 | + eventName: WebSocketServerAdapterEvent.Broadcast, |
| 87 | + event, |
| 88 | + source: config.address, |
| 89 | + }) |
| 90 | + } |
| 91 | + } catch (error) { |
| 92 | + debug('unable to process message: %o', error) |
| 93 | + } |
| 94 | + }) |
| 95 | + .on('close', (code, reason) => { |
| 96 | + debug(`disconnected (${code}): ${reason.toString()}`) |
| 97 | + |
| 98 | + setTimeout(() => { |
| 99 | + this.client.removeAllListeners() |
| 100 | + this.client = createMirror(config) |
| 101 | + }, 5000) |
| 102 | + }) |
| 103 | + .on('error', function (error) { |
| 104 | + debug('connection error: %o', error) |
| 105 | + }) |
| 106 | + } |
| 107 | + |
| 108 | + this.client = createMirror(this.config) |
| 109 | + } |
| 110 | + |
| 111 | + private onMessage(message: { eventName: string, event: unknown, source: string }): void { |
| 112 | + if ( |
| 113 | + message.eventName !== WebSocketServerAdapterEvent.Broadcast |
| 114 | + || message.source === this.config.address |
| 115 | + || !this.client |
| 116 | + || this.client.readyState !== WebSocket.OPEN |
| 117 | + ) { |
| 118 | + return |
| 119 | + } |
| 120 | + |
| 121 | + debug('received broadcast: %o', message.event) |
| 122 | + |
| 123 | + const eventToRelay = createRelayedEventMessage(message.event as any, this.config.secret) |
| 124 | + debug('relaying: %o', eventToRelay) |
| 125 | + this.client.send(JSON.stringify(eventToRelay)) |
| 126 | + } |
| 127 | + |
| 128 | + private onError(error: Error) { |
| 129 | + debug('error: %o', error) |
| 130 | + throw error |
| 131 | + } |
| 132 | + |
| 133 | + private onExit() { |
| 134 | + debug('exiting') |
| 135 | + this.close(() => { |
| 136 | + this.process.exit(0) |
| 137 | + }) |
| 138 | + } |
| 139 | + |
| 140 | + public close(callback?: () => void) { |
| 141 | + debug('closing') |
| 142 | + if (this.client) { |
| 143 | + this.client.terminate() |
| 144 | + } |
| 145 | + if (typeof callback === 'function') { |
| 146 | + callback() |
| 147 | + } |
| 148 | + } |
| 149 | +} |
0 commit comments