-
Notifications
You must be signed in to change notification settings - Fork 2
/
emitter.ts
379 lines (359 loc) · 12.9 KB
/
emitter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import { ConsoleHandler } from "std/log/handlers.ts";
import { getLogger, setup as setupLog } from "std/log/mod.ts";
import type { AmqpConnection } from "amqp/mod.ts";
import { stringify as losslessJsonStringify } from "npm:lossless-json";
import { type Chain, getAddress, toHex } from "viem";
import type { PrismaClient } from "./prisma/shim.ts";
import {
ControlEmitterRoutingKey,
ControlExchangeName,
EvmEventsQueueName,
} from "./constants/constants.ts";
import { deserializeControlMessage } from "./messages/ControlMessage.ts";
import {
deserializeEventMessage,
EventMessage,
} from "./messages/EventMessage.ts";
import { serializeEventResponse } from "./messages/EventResponse.ts";
import { createMutex } from "./utils/concurrencyUtils.ts";
import {
defaultLogFormatter,
EmitterLoggerName,
getInternalLoggers,
getLoggingLevel,
} from "./utils/logUtils.ts";
import {
runWithAmqp,
runWithChainDefinition,
runWithPrisma,
} from "./utils/runUtils.ts";
import { uint8ArrayEquals } from "./utils/uint8ArrayUtils.ts";
export async function emitter(
chain: Chain,
prisma: PrismaClient,
amqpConnection: AmqpConnection,
) {
const logger = getLogger(EmitterLoggerName);
logger.info(
`Emitter starting, chain name: ${chain.name} id: ${chain.id} url: ${
chain.rpcUrls.default.http[0]
}.`,
);
logger.debug(`Opening AMQP channel.`);
const amqpChannel = await amqpConnection.openChannel();
logger.debug(`Declaring AMQP control exchange: ${ControlExchangeName}.`);
await amqpChannel.declareExchange({ exchange: ControlExchangeName });
const controlQueue = await amqpChannel.declareQueue({});
logger.debug(`Declared AMQP control queue: ${controlQueue.queue}.`);
logger.debug(
`Binding AMQP control queue with exchange: ${ControlExchangeName} routing key: ${ControlEmitterRoutingKey}.`,
);
await amqpChannel.bindQueue({
queue: controlQueue.queue,
exchange: ControlExchangeName,
routingKey: ControlEmitterRoutingKey,
});
const eventsQueue = await amqpChannel.declareQueue({
queue: EvmEventsQueueName,
durable: true,
});
logger.debug(
`Declared AMQP events queue: ${eventsQueue.queue} consumers: ${eventsQueue.consumerCount} message count: ${eventsQueue.messageCount}.`,
);
async function getEmitDestinations() {
const emitDestinations = await prisma.emitDestination.findMany();
logger.info(() =>
emitDestinations.length > 0
? `Loaded emit destinations, ${
emitDestinations.map((dest) =>
`address: ${toHex(dest.sourceAddress)} event signature hash: ${
toHex(dest.abiHash)
} topic filters: ${
[dest.topic1, dest.topic2, dest.topic3]
.map((topic, i) => [topic, i + 1])
.filter(([topic, _]) => topic != null)
.map(([topic, i]) =>
`[${i}] ${toHex(topic as Uint8Array)}`
).join(" ")
} destination: ${dest.webhookUrl}`
).join(", ")
}.`
: "No emit destinations to push events."
);
return emitDestinations;
}
// TODO: rework hierarchical mapping
let emitDestinations = await getEmitDestinations();
await amqpChannel.consume(
{ queue: controlQueue.queue },
async (_args, _props, data) => {
const message = deserializeControlMessage(data);
logger.debug(
`Received message from control queue, action: ${message.action}.`,
);
if (
message.action === "reload"
) {
logger.info(
"Received reload control message, reloading configuration.",
);
emitDestinations = await getEmitDestinations();
}
},
);
const doEmitQueueMutex = createMutex();
let emitQueue:
(EventMessage & { retry?: true; lockedTimestamp: Date; url: string[] })[] =
[];
let abortWaitController = new AbortController();
await amqpChannel.consume(
{ queue: EvmEventsQueueName },
async (args, _, data) => {
const message = deserializeEventMessage(data);
const {
address,
sigHash,
topics,
logIndex,
blockNumber,
blockHash,
} = message;
if (blockNumber !== -1n) {
// not webhook test request
logger.debug(
`Received event message, blockNumber: ${blockNumber} logIndex: ${logIndex} delivery tag: ${args.deliveryTag}.`,
);
}
const failedUrls = (await prisma.failedUrl.findMany({
where: { blockNumber: Number(blockNumber), logIndex: Number(logIndex) },
})).map((x) => x.url);
const destinationUrls = failedUrls.length > 0
? failedUrls
: emitDestinations.filter((x) =>
uint8ArrayEquals(x.sourceAddress as unknown as Uint8Array, address) &&
uint8ArrayEquals(x.abiHash as unknown as Uint8Array, sigHash) &&
(x.topic1 == null ||
(uint8ArrayEquals(x.topic1 as unknown as Uint8Array, topics[1]) &&
(x.topic2 == null ||
(uint8ArrayEquals(
x.topic2 as unknown as Uint8Array,
topics[2],
) &&
(x.topic3 == null ||
uint8ArrayEquals(
x.topic3 as unknown as Uint8Array,
topics[3],
))))))
).map((x) => x.webhookUrl);
if (blockNumber === -1n) {
// Webhook Test Request
const sourceAddress = getAddress(toHex(address));
const abiHash = toHex(sigHash);
logger.info(
`Received webhook test request, address: ${sourceAddress} event signature hash: ${abiHash} destinations: ${
destinationUrls.join(", ")
}.`,
);
await Promise.all(destinationUrls.map(async (url) => {
try {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: losslessJsonStringify(serializeEventResponse(message)),
});
if (!response.ok) {
logger.error(
`Webhook test POST request failed with an HTTP error, status: ${response.status} blockNumber: url: ${url} response body: ${await response
.text()}`,
);
}
} catch (e) {
logger.error(
`Webhook test POST request failed with an exception, url: ${url}: ${
e.stack ?? e.message
}`,
);
}
}));
} else {
const lockedTimestamp = new Date();
if (
(await prisma.event.updateMany({
where: {
blockNumber: Number(blockNumber),
logIndex: Number(logIndex),
lockedTimestamp: null,
},
data: { lockedTimestamp },
})).count <= 0
) {
logger.error(() =>
`Message shouldn't be locked, but it is, blockNumber: ${blockNumber} logIndex: ${logIndex}.`
);
} else {
await doEmitQueueMutex(async () => {
const doMutex = createMutex();
logger.info(
`Queueing event for emit, blockNumber: ${blockNumber} logIndex: ${logIndex}.`,
);
await Promise.all(
destinationUrls.map(async (url) =>
await doMutex(() => {
let newEvt = true;
emitQueue = emitQueue.map((queuedItem) => {
if (
uint8ArrayEquals(queuedItem.blockHash, blockHash) &&
queuedItem.logIndex === logIndex
) {
newEvt = false;
if (!queuedItem.url.includes(url)) {
return {
...queuedItem,
url: [...queuedItem.url, url],
};
}
}
return queuedItem;
});
if (newEvt) {
emitQueue.push({ ...message, lockedTimestamp, url: [url] });
}
})
),
);
if (emitQueue.length > 0) abortWaitController.abort();
});
}
}
logger.debug(
`Acknowledging AMQP message for event, blockNumber: ${blockNumber} logIndex: ${logIndex} delivery tag: ${args.deliveryTag}.`,
);
await amqpChannel.ack({ deliveryTag: args.deliveryTag });
},
);
const abortController = new AbortController();
const runningPromise = emitEvents();
async function cleanup() {
logger.warning("Stopping emitter.");
abortController.abort();
abortWaitController.abort();
await runningPromise;
}
async function emitEvents() {
while (true) {
if (abortController.signal.aborted) return;
await doEmitQueueMutex(async () => {
abortWaitController = new AbortController();
emitQueue = (await Promise.all(
emitQueue.map(async (x) => {
const where = {
blockNumber: Number(x.blockNumber),
logIndex: Number(x.logIndex),
};
const newLockedTimestamp = new Date();
if (
(await prisma.event.updateMany({
where: { ...where, lockedTimestamp: x.lockedTimestamp },
data: { lockedTimestamp: newLockedTimestamp },
})).count <= 0
) {
logger.warning(
`Lock was modified by another party, aborting emit, blockNumber: ${x.blockNumber} logIndex: ${x.logIndex}.`,
);
return undefined;
}
const nextRetryUrls = (await Promise.all(x.url.map(async (url) => {
logger.info(
`${
x.retry ? "Retry p" : "P"
}osting event destination: ${url} blockNumber: ${x.blockNumber} logIndex: ${x.logIndex}.`,
);
try {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: losslessJsonStringify(serializeEventResponse(x)),
});
if (response.ok) return undefined;
logger.error(
`Event emit POST request failed with an HTTP error, status: ${response.status} blockNumber: ${x.blockNumber} logIndex: ${x.logIndex} url: ${url} response body: ${await response
.text()}`,
);
return url;
} catch (e) {
logger.error(
`Event emit POST request failed with an exception, blockNumber: ${x.blockNumber} logIndex: ${x.logIndex} url: ${url}: ${
e.stack ?? e.message
}`,
);
return url;
}
}))).filter((x) => x != undefined) as string[];
await prisma.failedUrl.deleteMany({ where });
await Promise.all(
nextRetryUrls.map((url) =>
prisma.failedUrl.create({ data: { ...where, url } })
),
);
if (nextRetryUrls.length <= 0) {
logger.info(
`Event post success for all webhook URLs, blockNumber: ${x.blockNumber} logIndex: ${x.logIndex}.`,
);
await prisma.event.updateMany({
where,
data: {
lockedTimestamp: null,
emittedTimestamp: new Date(),
},
});
return undefined;
} else {
logger.info(
`Event post failed for some webhook URLs, will retry on next event observed or after 60s, blockNumber: ${x.blockNumber} logIndex: ${x.logIndex} destinations: ${nextRetryUrls}.`,
);
return {
...x,
lockedTimestamp: newLockedTimestamp,
retry: true,
url: nextRetryUrls,
};
}
}),
)).filter((x) => x != undefined) as typeof emitQueue;
});
// TODO: interval config
await new Promise<void>((resolve) => {
abortWaitController.signal.onabort = () => resolve();
if (abortWaitController.signal.aborted) resolve();
setTimeout(resolve, 60000);
});
}
}
return { runningPromise, cleanup };
}
if (import.meta.main) {
setupLog({
handlers: {
console: new ConsoleHandler(getLoggingLevel(), {
formatter: defaultLogFormatter,
}),
},
loggers: {
...getInternalLoggers({
level: getLoggingLevel(),
handlers: ["console"],
}),
[EmitterLoggerName]: {
level: getLoggingLevel(),
handlers: ["console"],
},
},
});
await runWithChainDefinition((chain) => ({
runningPromise: runWithPrisma((prisma) => ({
runningPromise: runWithAmqp((amqpConnection) =>
emitter(chain, prisma, amqpConnection)
),
})),
}));
}