UNPKG

2.29 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const log_1 = require("../common/log");
4const log = log_1.create('alert-middleware');
5const IlpPacket = require("ilp-packet");
6const { T04_INSUFFICIENT_LIQUIDITY } = IlpPacket.Errors.codes;
7class AlertMiddleware {
8 constructor() {
9 this.alerts = {};
10 this.nextAlertId = Date.now();
11 }
12 async applyToPipelines(pipelines, accountId) {
13 pipelines.outgoingData.insertLast({
14 name: 'alert',
15 method: async (data, next) => {
16 const result = await next(data);
17 if (result[0] !== IlpPacket.Type.TYPE_ILP_REJECT)
18 return result;
19 const rejectPacket = IlpPacket.deserializeIlpReject(result);
20 if (rejectPacket.code !== T04_INSUFFICIENT_LIQUIDITY)
21 return result;
22 if (rejectPacket.message !== 'exceeded maximum balance.')
23 return result;
24 const { triggeredBy } = rejectPacket;
25 log.warn('generating alert for account=%s triggeredBy=%s message="%s"', accountId, triggeredBy, rejectPacket.message);
26 this.addAlert(accountId, triggeredBy, rejectPacket.message);
27 return result;
28 }
29 });
30 }
31 getAlerts() {
32 return Object.keys(this.alerts)
33 .map((id) => this.alerts[id])
34 .sort((a, b) => a.id - b.id);
35 }
36 dismissAlert(id) {
37 delete this.alerts[id];
38 }
39 addAlert(accountId, triggeredBy, message) {
40 const alert = Object.keys(this.alerts)
41 .map((alertId) => this.alerts[alertId])
42 .find((alert) => alert.accountId === accountId &&
43 alert.triggeredBy === triggeredBy &&
44 alert.message === message);
45 if (alert) {
46 alert.count++;
47 alert.updatedAt = new Date();
48 return;
49 }
50 const id = this.nextAlertId++;
51 const now = new Date();
52 this.alerts[id] = {
53 id,
54 accountId,
55 triggeredBy,
56 message,
57 count: 1,
58 createdAt: now,
59 updatedAt: now
60 };
61 }
62}
63exports.default = AlertMiddleware;
64//# sourceMappingURL=alert.js.map
\No newline at end of file