1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const IlpPacket = require("ilp-packet");
|
4 | const log_1 = require("../common/log");
|
5 | const log = log_1.create('rate-limit-middleware');
|
6 | const token_bucket_1 = require("../lib/token-bucket");
|
7 | const { RateLimitedError } = IlpPacket.Errors;
|
8 | const DEFAULT_REFILL_PERIOD = 60 * 1000;
|
9 | const DEFAULT_REFILL_COUNT = 10000;
|
10 | class 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 | }
|
47 | exports.default = RateLimitMiddleware;
|
48 |
|
\ | No newline at end of file |