UNPKG

2.14 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const IlpPacket = require("ilp-packet");
4const log_1 = require("../common/log");
5const log = log_1.create('rate-limit-middleware');
6const token_bucket_1 = require("../lib/token-bucket");
7const { RateLimitedError } = IlpPacket.Errors;
8const DEFAULT_REFILL_PERIOD = 60 * 1000;
9const DEFAULT_REFILL_COUNT = 10000;
10class RateLimitMiddleware {
11 constructor(opts, { getInfo, stats }) {
12 this.getInfo = getInfo;
13 this.stats = stats;
14 }
15 async applyToPipelines(pipelines, accountId) {
16 const accountInfo = this.getInfo(accountId);
17 if (!accountInfo) {
18 throw new Error('could not load info for account. accountId=' + accountId);
19 }
20 const rateLimit = accountInfo.rateLimit || {};
21 const { refillPeriod = DEFAULT_REFILL_PERIOD, refillCount = DEFAULT_REFILL_COUNT } = rateLimit;
22 const capacity = rateLimit.capacity || refillCount;
23 log.trace('created token bucket for account. accountId=%s refillPeriod=%s refillCount=%s capacity=%s', accountId, refillPeriod, refillCount, capacity);
24 const bucket = new token_bucket_1.default({ refillPeriod, refillCount, capacity });
25 pipelines.incomingData.insertLast({
26 name: 'rateLimit',
27 method: async (data, next) => {
28 if (!bucket.take()) {
29 this.stats.rateLimitedPackets.increment({ accountId, accountInfo }, {});
30 throw new RateLimitedError('too many requests, throttling.');
31 }
32 return next(data);
33 }
34 });
35 pipelines.incomingMoney.insertLast({
36 name: 'rateLimit',
37 method: async (amount, next) => {
38 if (!bucket.take()) {
39 this.stats.rateLimitedMoney.increment({ accountId, accountInfo }, {});
40 throw new RateLimitedError('too many requests, throttling.');
41 }
42 return next(amount);
43 }
44 });
45 }
46}
47exports.default = RateLimitMiddleware;
48//# sourceMappingURL=rate-limit.js.map
\No newline at end of file