1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const log_1 = require("../common/log");
|
4 | const log = log_1.create('throughput-middleware');
|
5 | const token_bucket_1 = require("../lib/token-bucket");
|
6 | const IlpPacket = require("ilp-packet");
|
7 | const { InsufficientLiquidityError } = IlpPacket.Errors;
|
8 | const DEFAULT_REFILL_PERIOD = 1000;
|
9 | class ThroughputMiddleware {
|
10 | constructor(opts, { getInfo }) {
|
11 | this.getInfo = getInfo;
|
12 | }
|
13 | async applyToPipelines(pipelines, accountId) {
|
14 | const accountInfo = this.getInfo(accountId);
|
15 | if (!accountInfo) {
|
16 | throw new Error('could not load info for account. accountId=' + accountId);
|
17 | }
|
18 | if (accountInfo.throughput) {
|
19 | const { refillPeriod = DEFAULT_REFILL_PERIOD, incomingAmount = false, outgoingAmount = false } = accountInfo.throughput || {};
|
20 | if (incomingAmount) {
|
21 | const incomingBucket = new token_bucket_1.default({ refillPeriod, refillCount: Number(incomingAmount) });
|
22 | log.trace('created incoming amount limit token bucket for account. accountId=%s refillPeriod=%s incomingAmount=%s', accountId, refillPeriod, incomingAmount);
|
23 | pipelines.incomingData.insertLast({
|
24 | name: 'throughput',
|
25 | method: async (data, next) => {
|
26 | if (data[0] === IlpPacket.Type.TYPE_ILP_PREPARE) {
|
27 | const parsedPacket = IlpPacket.deserializeIlpPrepare(data);
|
28 | if (!incomingBucket.take(Number(parsedPacket.amount))) {
|
29 | throw new InsufficientLiquidityError('exceeded money bandwidth, throttling.');
|
30 | }
|
31 | return next(data);
|
32 | }
|
33 | else {
|
34 | return next(data);
|
35 | }
|
36 | }
|
37 | });
|
38 | }
|
39 | if (outgoingAmount) {
|
40 | const incomingBucket = new token_bucket_1.default({ refillPeriod, refillCount: Number(outgoingAmount) });
|
41 | log.trace('created outgoing amount limit token bucket for account. accountId=%s refillPeriod=%s outgoingAmount=%s', accountId, refillPeriod, outgoingAmount);
|
42 | pipelines.outgoingData.insertLast({
|
43 | name: 'throughput',
|
44 | method: async (data, next) => {
|
45 | if (data[0] === IlpPacket.Type.TYPE_ILP_PREPARE) {
|
46 | const parsedPacket = IlpPacket.deserializeIlpPrepare(data);
|
47 | if (!incomingBucket.take(Number(parsedPacket.amount))) {
|
48 | throw new InsufficientLiquidityError('exceeded money bandwidth, throttling.');
|
49 | }
|
50 | return next(data);
|
51 | }
|
52 | else {
|
53 | return next(data);
|
54 | }
|
55 | }
|
56 | });
|
57 | }
|
58 | }
|
59 | }
|
60 | }
|
61 | exports.default = ThroughputMiddleware;
|
62 |
|
\ | No newline at end of file |