@unikvs/rate-limit 0.0.0-stage → 0.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2 -2
- package/dist/index.d.ts +178 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +219 -0
- package/dist/index.js.map +1 -0
- package/package.json +44 -3
- package/src/errors.ts +133 -0
- package/src/index.ts +10 -0
- package/src/rate-limit.ts +285 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026-present, tai-kun
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @unikvs/rate-limit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Document](https://tai-kun.github.io/unikvs/)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { ErrorBase, ErrorOptions, IMiddleware, InvalidUsageErrorBase } from "@unikvs/core";
|
|
2
|
+
import { PassThrough } from "@unikvs/passthrough";
|
|
3
|
+
//#region ../src/errors.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
6
|
+
*/
|
|
7
|
+
type RateLimitExceededErrorMeta = {
|
|
8
|
+
/**
|
|
9
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-exceeded-retry-after-ms)
|
|
10
|
+
*/
|
|
11
|
+
readonly retryAfterMs: number;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
15
|
+
*/
|
|
16
|
+
type RateLimitExceededErrorArgs = ErrorOptions & RateLimitExceededErrorMeta;
|
|
17
|
+
/**
|
|
18
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
19
|
+
*/
|
|
20
|
+
export declare class RateLimitExceededError extends ErrorBase<RateLimitExceededErrorMeta> {
|
|
21
|
+
/**
|
|
22
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
23
|
+
*/
|
|
24
|
+
constructor(args: RateLimitExceededErrorArgs);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
28
|
+
*/
|
|
29
|
+
type RateLimitInvalidOptionErrorMeta = {
|
|
30
|
+
/**
|
|
31
|
+
* 不正だったオプション名です。
|
|
32
|
+
*
|
|
33
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-name)
|
|
34
|
+
*/
|
|
35
|
+
readonly name: string;
|
|
36
|
+
/**
|
|
37
|
+
* 指定された値です。
|
|
38
|
+
*
|
|
39
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-actual)
|
|
40
|
+
*/
|
|
41
|
+
readonly actual: unknown;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
45
|
+
*/
|
|
46
|
+
type RateLimitInvalidOptionErrorArgs = ErrorOptions & RateLimitInvalidOptionErrorMeta;
|
|
47
|
+
/**
|
|
48
|
+
* コンストラクターに不正なオプションが渡されたときのエラーです。
|
|
49
|
+
*
|
|
50
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
51
|
+
*/
|
|
52
|
+
export declare class RateLimitInvalidOptionError extends InvalidUsageErrorBase<RateLimitInvalidOptionErrorMeta> {
|
|
53
|
+
/**
|
|
54
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
55
|
+
*/
|
|
56
|
+
constructor(args: RateLimitInvalidOptionErrorArgs);
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region ../src/rate-limit.d.ts
|
|
60
|
+
/**
|
|
61
|
+
* レート制限を超えたときの挙動です。
|
|
62
|
+
*
|
|
63
|
+
* - `"wait"` はトークンが補充されるまで待機します。
|
|
64
|
+
* - `"throw"` は直ちにエラーを投げます。
|
|
65
|
+
*
|
|
66
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-strategy)
|
|
67
|
+
*/
|
|
68
|
+
type RateLimitStrategy = "wait" | "throw";
|
|
69
|
+
/**
|
|
70
|
+
* 待機処理の実装です。テストで時刻を制御するときに差し替えます。
|
|
71
|
+
*
|
|
72
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#irate-limit-sleep)
|
|
73
|
+
*/
|
|
74
|
+
interface IRateLimitSleep {
|
|
75
|
+
(ms: number, signal: AbortSignal): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* RateLimit ミドルウェアのオプションです。
|
|
79
|
+
*
|
|
80
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options)
|
|
81
|
+
*/
|
|
82
|
+
type RateLimitOptions = {
|
|
83
|
+
/**
|
|
84
|
+
* 1 インターバルあたりに補充されるトークン数です。既定値は `1` です。
|
|
85
|
+
*
|
|
86
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-tokens-per-interval)
|
|
87
|
+
*/
|
|
88
|
+
readonly tokensPerInterval?: number | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* トークンを補充する間隔 (ミリ秒) です。既定値は `1000` です。
|
|
91
|
+
*
|
|
92
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-interval-ms)
|
|
93
|
+
*/
|
|
94
|
+
readonly intervalMs?: number | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* 保持できるトークンの上限です。既定値は `tokensPerInterval` です。
|
|
97
|
+
*
|
|
98
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-max-tokens)
|
|
99
|
+
*/
|
|
100
|
+
readonly maxTokens?: number | undefined;
|
|
101
|
+
/**
|
|
102
|
+
* `maxTokens` の別名です。両方を指定した場合は `maxTokens` が優先されます。
|
|
103
|
+
*
|
|
104
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-burst)
|
|
105
|
+
*/
|
|
106
|
+
readonly burst?: number | undefined;
|
|
107
|
+
/**
|
|
108
|
+
* レート制限を超えたときの挙動です。既定値は `"wait"` です。
|
|
109
|
+
*
|
|
110
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-strategy)
|
|
111
|
+
*/
|
|
112
|
+
readonly strategy?: RateLimitStrategy | undefined;
|
|
113
|
+
/**
|
|
114
|
+
* 現在時刻 (epoch ミリ秒) を返す関数です。既定値は `Date.now` です。
|
|
115
|
+
*
|
|
116
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-now)
|
|
117
|
+
*/
|
|
118
|
+
readonly now?: (() => number) | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* 待機処理です。既定では `setTimeout` を使用します。
|
|
121
|
+
*
|
|
122
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-sleep)
|
|
123
|
+
*/
|
|
124
|
+
readonly sleep?: IRateLimitSleep | undefined;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* トークンバケットで操作頻度を制限するミドルウェアです。
|
|
128
|
+
*
|
|
129
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
130
|
+
*/
|
|
131
|
+
declare class RateLimit extends PassThrough implements IMiddleware {
|
|
132
|
+
#private;
|
|
133
|
+
/**
|
|
134
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
135
|
+
*/
|
|
136
|
+
override readonly name: string;
|
|
137
|
+
/**
|
|
138
|
+
* 1 インターバルあたりに補充されるトークン数です。
|
|
139
|
+
*
|
|
140
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
141
|
+
*/
|
|
142
|
+
readonly tokensPerInterval: number;
|
|
143
|
+
/**
|
|
144
|
+
* トークンを補充する間隔 (ミリ秒) です。
|
|
145
|
+
*
|
|
146
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
147
|
+
*/
|
|
148
|
+
readonly intervalMs: number;
|
|
149
|
+
/**
|
|
150
|
+
* 保持できるトークンの上限です。
|
|
151
|
+
*
|
|
152
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
153
|
+
*/
|
|
154
|
+
readonly maxTokens: number;
|
|
155
|
+
/**
|
|
156
|
+
* レート制限を超えたときの挙動です。
|
|
157
|
+
*
|
|
158
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
159
|
+
*/
|
|
160
|
+
readonly strategy: RateLimitStrategy;
|
|
161
|
+
/**
|
|
162
|
+
* RateLimit ミドルウェアを作成します。
|
|
163
|
+
*
|
|
164
|
+
* @param options トークン数と補充間隔などの設定です。
|
|
165
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
166
|
+
*/
|
|
167
|
+
constructor(options?: RateLimitOptions);
|
|
168
|
+
/**
|
|
169
|
+
* 現在保持しているトークン数です。
|
|
170
|
+
*
|
|
171
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
172
|
+
*/
|
|
173
|
+
get availableTokens(): number;
|
|
174
|
+
use(c: IMiddleware.UseContext, next: IMiddleware.INext): Promise<void>;
|
|
175
|
+
}
|
|
176
|
+
//#endregion
|
|
177
|
+
export { type IRateLimitSleep, RateLimit, type RateLimitExceededErrorArgs, type RateLimitExceededErrorMeta, type RateLimitInvalidOptionErrorArgs, type RateLimitInvalidOptionErrorMeta, type RateLimitOptions, type RateLimitStrategy };
|
|
178
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/errors.ts","../src/rate-limit.ts"],"mappings":";;;;;;KAKY;;;;WAID;;;;;KAMC,6BAA6B,eAAe;;;;qBAK3C,+BAA+B,UAAU;;;;EAQpD,YAAmB,MAAM;;;;;KAsBf;;;;;;WAMD;;;;;;WAOA;;;;;KAMC,kCAAkC,eAAe;;;;;;qBAOhD,oCAAoC,sBAAsB;;;;EAQrE,YAAmB,MAAM;;;;;;;;;;;;KCtEf;;;;;;UAOK;GACd,YAAY,QAAQ,cAAc;;;;;;;KAQzB;;;;;;WAMD;;;;;;WAOA;;;;;;WAOA;;;;;;WAOA;;;;;;WAOA,WAAW;;;;;;WAOX;;;;;;WAOA,QAAQ;;;;;;;cAqCE,kBAAkB,uBAAuB;;;;;oBAInC;;;;;;WAOT;;;;;;WAOA;;;;;;WAOA;;;;;;WAOA,UAAU;;;;;;;EAkB1B,YAAmB,UAAS;;;;;;MAuDjB;EAMX,IAAiB,GAAG,YAAY,YAAY,MAAM,YAAY,QAAQ"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { ErrorBase, InvalidUsageErrorBase, setErrorMessage } from "@unikvs/core";
|
|
2
|
+
import { PassThrough } from "@unikvs/passthrough";
|
|
3
|
+
import { getAbortReason, throwIfAborted } from "abort-signal-utils";
|
|
4
|
+
//#region ../src/errors.ts
|
|
5
|
+
var _RateLimitExceededError;
|
|
6
|
+
var _RateLimitInvalidOptionError;
|
|
7
|
+
/**
|
|
8
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
9
|
+
*/
|
|
10
|
+
var RateLimitExceededError = class extends ErrorBase {
|
|
11
|
+
/**
|
|
12
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
13
|
+
*/
|
|
14
|
+
constructor(args) {
|
|
15
|
+
const { retryAfterMs, ...options } = args;
|
|
16
|
+
super({ retryAfterMs }, ({ retryAfterMs: messageRetryAfterMs }) => `Rate limit exceeded. Retry after ${String(messageRetryAfterMs)}ms.`, options);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
_RateLimitExceededError = RateLimitExceededError;
|
|
20
|
+
_RateLimitExceededError.prototype.name = "RateLimitExceededError";
|
|
21
|
+
setErrorMessage(RateLimitExceededError, ({ retryAfterMs }) => `レート制限を超えました。${String(retryAfterMs)}ms 後に再試行してください。`, "ja");
|
|
22
|
+
/**
|
|
23
|
+
* コンストラクターに不正なオプションが渡されたときのエラーです。
|
|
24
|
+
*
|
|
25
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
26
|
+
*/
|
|
27
|
+
var RateLimitInvalidOptionError = class extends InvalidUsageErrorBase {
|
|
28
|
+
/**
|
|
29
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
30
|
+
*/
|
|
31
|
+
constructor(args) {
|
|
32
|
+
const { name, actual, ...options } = args;
|
|
33
|
+
super({
|
|
34
|
+
name,
|
|
35
|
+
actual
|
|
36
|
+
}, ({ name: messageName, actual: messageActual }) => `Invalid RateLimit option ${JSON.stringify(messageName)}: ${formatActual(messageActual)}`, options);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
_RateLimitInvalidOptionError = RateLimitInvalidOptionError;
|
|
40
|
+
_RateLimitInvalidOptionError.prototype.name = "RateLimitInvalidOptionError";
|
|
41
|
+
setErrorMessage(RateLimitInvalidOptionError, ({ name, actual }) => `無効な RateLimit オプション ${JSON.stringify(name)}: ${formatActual(actual)}`, "ja");
|
|
42
|
+
/**
|
|
43
|
+
* エラーメッセージに埋め込む実際の値を整形します。
|
|
44
|
+
*
|
|
45
|
+
* @param actual 整形する値です。
|
|
46
|
+
*
|
|
47
|
+
* @returns 整形した文字列を返します。
|
|
48
|
+
*/
|
|
49
|
+
function formatActual(actual) {
|
|
50
|
+
if (typeof actual === "string") return JSON.stringify(actual);
|
|
51
|
+
if (typeof actual === "number" || typeof actual === "boolean" || actual === null || actual === void 0) return String(actual);
|
|
52
|
+
try {
|
|
53
|
+
return JSON.stringify(actual) ?? "[object Object]";
|
|
54
|
+
} catch {
|
|
55
|
+
return "[object Object]";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region \0@oxc-project+runtime@0.154.0/helpers/esm/checkPrivateRedeclaration.js
|
|
60
|
+
function _checkPrivateRedeclaration(e, t) {
|
|
61
|
+
if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region \0@oxc-project+runtime@0.154.0/helpers/esm/classPrivateMethodInitSpec.js
|
|
65
|
+
function _classPrivateMethodInitSpec(e, a) {
|
|
66
|
+
_checkPrivateRedeclaration(e, a), a.add(e);
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region \0@oxc-project+runtime@0.154.0/helpers/esm/classPrivateFieldInitSpec.js
|
|
70
|
+
function _classPrivateFieldInitSpec(e, t, a) {
|
|
71
|
+
_checkPrivateRedeclaration(e, t), t.set(e, a);
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region \0@oxc-project+runtime@0.154.0/helpers/esm/assertClassBrand.js
|
|
75
|
+
function _assertClassBrand(e, t, n) {
|
|
76
|
+
if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
|
|
77
|
+
throw new TypeError("Private element is not present on this object");
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region \0@oxc-project+runtime@0.154.0/helpers/esm/classPrivateFieldSet2.js
|
|
81
|
+
function _classPrivateFieldSet2(s, a, r) {
|
|
82
|
+
return s.set(_assertClassBrand(s, a), r), r;
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region \0@oxc-project+runtime@0.154.0/helpers/esm/classPrivateFieldGet2.js
|
|
86
|
+
function _classPrivateFieldGet2(s, a) {
|
|
87
|
+
return s.get(_assertClassBrand(s, a));
|
|
88
|
+
}
|
|
89
|
+
//#endregion
|
|
90
|
+
//#region ../src/rate-limit.ts
|
|
91
|
+
function defaultSleep(ms, signal) {
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
if (signal.aborted) {
|
|
94
|
+
reject(getAbortReason(signal));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const timer = setTimeout(() => {
|
|
98
|
+
signal.removeEventListener("abort", onAbort);
|
|
99
|
+
resolve();
|
|
100
|
+
}, ms);
|
|
101
|
+
const onAbort = () => {
|
|
102
|
+
clearTimeout(timer);
|
|
103
|
+
reject(getAbortReason(signal));
|
|
104
|
+
};
|
|
105
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
function assertPositiveNumber(name, value) {
|
|
109
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) throw new RateLimitInvalidOptionError({
|
|
110
|
+
name,
|
|
111
|
+
actual: value
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
var _now = /* @__PURE__ */ new WeakMap();
|
|
115
|
+
var _sleep = /* @__PURE__ */ new WeakMap();
|
|
116
|
+
var _tokens = /* @__PURE__ */ new WeakMap();
|
|
117
|
+
var _lastRefill = /* @__PURE__ */ new WeakMap();
|
|
118
|
+
var _tail = /* @__PURE__ */ new WeakMap();
|
|
119
|
+
var _RateLimit_brand = /* @__PURE__ */ new WeakSet();
|
|
120
|
+
/**
|
|
121
|
+
* トークンバケットで操作頻度を制限するミドルウェアです。
|
|
122
|
+
*
|
|
123
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
124
|
+
*/
|
|
125
|
+
var RateLimit = class extends PassThrough {
|
|
126
|
+
/**
|
|
127
|
+
* RateLimit ミドルウェアを作成します。
|
|
128
|
+
*
|
|
129
|
+
* @param options トークン数と補充間隔などの設定です。
|
|
130
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
131
|
+
*/
|
|
132
|
+
constructor(options = {}) {
|
|
133
|
+
super();
|
|
134
|
+
_classPrivateMethodInitSpec(this, _RateLimit_brand);
|
|
135
|
+
this.name = "RateLimit";
|
|
136
|
+
_classPrivateFieldInitSpec(this, _now, void 0);
|
|
137
|
+
_classPrivateFieldInitSpec(this, _sleep, void 0);
|
|
138
|
+
_classPrivateFieldInitSpec(this, _tokens, void 0);
|
|
139
|
+
_classPrivateFieldInitSpec(this, _lastRefill, void 0);
|
|
140
|
+
_classPrivateFieldInitSpec(this, _tail, void 0);
|
|
141
|
+
const { now = Date.now, burst, sleep = defaultSleep, strategy = "wait", maxTokens, intervalMs = 1e3, tokensPerInterval = 1 } = options;
|
|
142
|
+
assertPositiveNumber("tokensPerInterval", tokensPerInterval);
|
|
143
|
+
assertPositiveNumber("intervalMs", intervalMs);
|
|
144
|
+
const capacity = maxTokens ?? burst ?? tokensPerInterval;
|
|
145
|
+
assertPositiveNumber("maxTokens", capacity);
|
|
146
|
+
if (strategy !== "wait" && strategy !== "throw") throw new RateLimitInvalidOptionError({
|
|
147
|
+
name: "strategy",
|
|
148
|
+
actual: strategy
|
|
149
|
+
});
|
|
150
|
+
if (typeof now !== "function") throw new RateLimitInvalidOptionError({
|
|
151
|
+
name: "now",
|
|
152
|
+
actual: now
|
|
153
|
+
});
|
|
154
|
+
if (typeof sleep !== "function") throw new RateLimitInvalidOptionError({
|
|
155
|
+
name: "sleep",
|
|
156
|
+
actual: sleep
|
|
157
|
+
});
|
|
158
|
+
this.tokensPerInterval = tokensPerInterval;
|
|
159
|
+
this.intervalMs = intervalMs;
|
|
160
|
+
this.maxTokens = capacity;
|
|
161
|
+
this.strategy = strategy;
|
|
162
|
+
_classPrivateFieldSet2(_now, this, now);
|
|
163
|
+
_classPrivateFieldSet2(_sleep, this, sleep);
|
|
164
|
+
_classPrivateFieldSet2(_tokens, this, capacity);
|
|
165
|
+
_classPrivateFieldSet2(_lastRefill, this, now());
|
|
166
|
+
_classPrivateFieldSet2(_tail, this, Promise.resolve());
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* 現在保持しているトークン数です。
|
|
170
|
+
*
|
|
171
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
172
|
+
*/
|
|
173
|
+
get availableTokens() {
|
|
174
|
+
_assertClassBrand(_RateLimit_brand, this, _refill).call(this);
|
|
175
|
+
return _classPrivateFieldGet2(_tokens, this);
|
|
176
|
+
}
|
|
177
|
+
async use(c, next) {
|
|
178
|
+
await _assertClassBrand(_RateLimit_brand, this, _acquire).call(this, c.signal);
|
|
179
|
+
await next();
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
async function _acquire(signal) {
|
|
183
|
+
throwIfAborted(signal);
|
|
184
|
+
let release;
|
|
185
|
+
const previous = _classPrivateFieldGet2(_tail, this);
|
|
186
|
+
_classPrivateFieldSet2(_tail, this, new Promise((resolve) => {
|
|
187
|
+
release = resolve;
|
|
188
|
+
}));
|
|
189
|
+
await previous;
|
|
190
|
+
try {
|
|
191
|
+
for (;;) {
|
|
192
|
+
throwIfAborted(signal);
|
|
193
|
+
_assertClassBrand(_RateLimit_brand, this, _refill).call(this);
|
|
194
|
+
if (_classPrivateFieldGet2(_tokens, this) >= 1) {
|
|
195
|
+
_classPrivateFieldSet2(_tokens, this, _classPrivateFieldGet2(_tokens, this) - 1);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (this.strategy === "throw") throw new RateLimitExceededError({ retryAfterMs: _assertClassBrand(_RateLimit_brand, this, _retryAfterMs).call(this) });
|
|
199
|
+
await _classPrivateFieldGet2(_sleep, this).call(this, _assertClassBrand(_RateLimit_brand, this, _retryAfterMs).call(this), signal);
|
|
200
|
+
}
|
|
201
|
+
} finally {
|
|
202
|
+
release();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
function _refill() {
|
|
206
|
+
const now = _classPrivateFieldGet2(_now, this).call(this);
|
|
207
|
+
const elapsed = now - _classPrivateFieldGet2(_lastRefill, this);
|
|
208
|
+
if (elapsed <= 0) return;
|
|
209
|
+
_classPrivateFieldSet2(_tokens, this, Math.min(this.maxTokens, _classPrivateFieldGet2(_tokens, this) + elapsed * this.tokensPerInterval / this.intervalMs));
|
|
210
|
+
_classPrivateFieldSet2(_lastRefill, this, now);
|
|
211
|
+
}
|
|
212
|
+
function _retryAfterMs() {
|
|
213
|
+
const deficit = 1 - _classPrivateFieldGet2(_tokens, this);
|
|
214
|
+
return Math.max(0, Math.ceil(deficit * this.intervalMs / this.tokensPerInterval));
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
export { RateLimit, RateLimitExceededError, RateLimitInvalidOptionError };
|
|
218
|
+
|
|
219
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/errors.ts","../src/rate-limit.ts"],"sourcesContent":["import { type ErrorOptions, ErrorBase, setErrorMessage, InvalidUsageErrorBase } from \"@unikvs/core\";\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)\n */\nexport type RateLimitExceededErrorMeta = {\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-exceeded-retry-after-ms)\n */\n readonly retryAfterMs: number;\n};\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)\n */\nexport type RateLimitExceededErrorArgs = ErrorOptions & RateLimitExceededErrorMeta;\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)\n */\nexport class RateLimitExceededError extends ErrorBase<RateLimitExceededErrorMeta> {\n static {\n this.prototype.name = \"RateLimitExceededError\";\n }\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)\n */\n public constructor(args: RateLimitExceededErrorArgs) {\n const { retryAfterMs, ...options } = args;\n const meta: RateLimitExceededErrorMeta = { retryAfterMs };\n super(\n meta,\n ({ retryAfterMs: messageRetryAfterMs }) =>\n `Rate limit exceeded. Retry after ${String(messageRetryAfterMs)}ms.`,\n options,\n );\n }\n}\n\nsetErrorMessage(\n RateLimitExceededError,\n ({ retryAfterMs }) =>\n `レート制限を超えました。${String(retryAfterMs)}ms 後に再試行してください。`,\n \"ja\",\n);\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)\n */\nexport type RateLimitInvalidOptionErrorMeta = {\n /**\n * 不正だったオプション名です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-name)\n */\n readonly name: string;\n\n /**\n * 指定された値です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-actual)\n */\n readonly actual: unknown;\n};\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)\n */\nexport type RateLimitInvalidOptionErrorArgs = ErrorOptions & RateLimitInvalidOptionErrorMeta;\n\n/**\n * コンストラクターに不正なオプションが渡されたときのエラーです。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)\n */\nexport class RateLimitInvalidOptionError extends InvalidUsageErrorBase<RateLimitInvalidOptionErrorMeta> {\n static {\n this.prototype.name = \"RateLimitInvalidOptionError\";\n }\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)\n */\n public constructor(args: RateLimitInvalidOptionErrorArgs) {\n const { name, actual, ...options } = args;\n const meta: RateLimitInvalidOptionErrorMeta = {\n name,\n actual,\n };\n super(\n meta,\n ({ name: messageName, actual: messageActual }) =>\n `Invalid RateLimit option ${JSON.stringify(messageName)}: ${formatActual(messageActual)}`,\n options,\n );\n }\n}\n\nsetErrorMessage(\n RateLimitInvalidOptionError,\n ({ name, actual }) =>\n `無効な RateLimit オプション ${JSON.stringify(name)}: ${formatActual(actual)}`,\n \"ja\",\n);\n\n/**\n * エラーメッセージに埋め込む実際の値を整形します。\n *\n * @param actual 整形する値です。\n *\n * @returns 整形した文字列を返します。\n */\nfunction formatActual(actual: unknown): string {\n if (typeof actual === \"string\") {\n return JSON.stringify(actual);\n }\n\n if (\n typeof actual === \"number\" ||\n typeof actual === \"boolean\" ||\n actual === null ||\n actual === undefined\n ) {\n return String(actual);\n }\n\n try {\n return JSON.stringify(actual) ?? \"[object Object]\";\n } catch {\n return \"[object Object]\";\n }\n}\n","import type { IMiddleware } from \"@unikvs/core\";\nimport { PassThrough } from \"@unikvs/passthrough\";\nimport { getAbortReason, throwIfAborted } from \"abort-signal-utils\";\n\nimport { RateLimitExceededError, RateLimitInvalidOptionError } from \"./errors.js\";\n\n/**\n * レート制限を超えたときの挙動です。\n *\n * - `\"wait\"` はトークンが補充されるまで待機します。\n * - `\"throw\"` は直ちにエラーを投げます。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-strategy)\n */\nexport type RateLimitStrategy = \"wait\" | \"throw\";\n\n/**\n * 待機処理の実装です。テストで時刻を制御するときに差し替えます。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#irate-limit-sleep)\n */\nexport interface IRateLimitSleep {\n (ms: number, signal: AbortSignal): Promise<void>;\n}\n\n/**\n * RateLimit ミドルウェアのオプションです。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options)\n */\nexport type RateLimitOptions = {\n /**\n * 1 インターバルあたりに補充されるトークン数です。既定値は `1` です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-tokens-per-interval)\n */\n readonly tokensPerInterval?: number | undefined;\n\n /**\n * トークンを補充する間隔 (ミリ秒) です。既定値は `1000` です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-interval-ms)\n */\n readonly intervalMs?: number | undefined;\n\n /**\n * 保持できるトークンの上限です。既定値は `tokensPerInterval` です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-max-tokens)\n */\n readonly maxTokens?: number | undefined;\n\n /**\n * `maxTokens` の別名です。両方を指定した場合は `maxTokens` が優先されます。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-burst)\n */\n readonly burst?: number | undefined;\n\n /**\n * レート制限を超えたときの挙動です。既定値は `\"wait\"` です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-strategy)\n */\n readonly strategy?: RateLimitStrategy | undefined;\n\n /**\n * 現在時刻 (epoch ミリ秒) を返す関数です。既定値は `Date.now` です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-now)\n */\n readonly now?: (() => number) | undefined;\n\n /**\n * 待機処理です。既定では `setTimeout` を使用します。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-sleep)\n */\n readonly sleep?: IRateLimitSleep | undefined;\n};\n\nfunction defaultSleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(getAbortReason(signal));\n\n return;\n }\n\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(getAbortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nfunction assertPositiveNumber(name: string, value: number): void {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n throw new RateLimitInvalidOptionError({\n name,\n actual: value,\n });\n }\n}\n\n/**\n * トークンバケットで操作頻度を制限するミドルウェアです。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\nexport default class RateLimit extends PassThrough implements IMiddleware {\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public override readonly name: string = \"RateLimit\";\n\n /**\n * 1 インターバルあたりに補充されるトークン数です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public readonly tokensPerInterval: number;\n\n /**\n * トークンを補充する間隔 (ミリ秒) です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public readonly intervalMs: number;\n\n /**\n * 保持できるトークンの上限です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public readonly maxTokens: number;\n\n /**\n * レート制限を超えたときの挙動です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public readonly strategy: RateLimitStrategy;\n\n readonly #now: () => number;\n\n readonly #sleep: IRateLimitSleep;\n\n #tokens: number;\n\n #lastRefill: number;\n\n #tail: Promise<void>;\n\n /**\n * RateLimit ミドルウェアを作成します。\n *\n * @param options トークン数と補充間隔などの設定です。\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public constructor(options: RateLimitOptions = {}) {\n super();\n\n const {\n now = Date.now,\n burst,\n sleep = defaultSleep,\n strategy = \"wait\",\n maxTokens,\n intervalMs = 1000,\n tokensPerInterval = 1,\n } = options;\n assertPositiveNumber(\"tokensPerInterval\", tokensPerInterval);\n assertPositiveNumber(\"intervalMs\", intervalMs);\n\n const capacity = maxTokens ?? burst ?? tokensPerInterval;\n assertPositiveNumber(\"maxTokens\", capacity);\n\n if (strategy !== \"wait\" && strategy !== \"throw\") {\n throw new RateLimitInvalidOptionError({\n name: \"strategy\",\n actual: strategy,\n });\n }\n\n if (typeof now !== \"function\") {\n throw new RateLimitInvalidOptionError({\n name: \"now\",\n actual: now,\n });\n }\n\n if (typeof sleep !== \"function\") {\n throw new RateLimitInvalidOptionError({\n name: \"sleep\",\n actual: sleep,\n });\n }\n\n this.tokensPerInterval = tokensPerInterval;\n this.intervalMs = intervalMs;\n this.maxTokens = capacity;\n this.strategy = strategy;\n this.#now = now;\n this.#sleep = sleep;\n this.#tokens = capacity;\n this.#lastRefill = now();\n this.#tail = Promise.resolve();\n }\n\n /**\n * 現在保持しているトークン数です。\n *\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public get availableTokens(): number {\n this.#refill();\n\n return this.#tokens;\n }\n\n public async use(c: IMiddleware.UseContext, next: IMiddleware.INext): Promise<void> {\n await this.#acquire(c.signal);\n\n await next();\n }\n\n async #acquire(signal: AbortSignal): Promise<void> {\n throwIfAborted(signal);\n\n let release!: () => void;\n const previous = this.#tail;\n this.#tail = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previous;\n\n try {\n for (;;) {\n throwIfAborted(signal);\n this.#refill();\n\n if (this.#tokens >= 1) {\n this.#tokens -= 1;\n\n return;\n }\n\n if (this.strategy === \"throw\") {\n throw new RateLimitExceededError({ retryAfterMs: this.#retryAfterMs() });\n }\n\n await this.#sleep(this.#retryAfterMs(), signal);\n }\n } finally {\n release();\n }\n }\n\n #refill(): void {\n const now = this.#now();\n const elapsed = now - this.#lastRefill;\n\n if (elapsed <= 0) {\n return;\n }\n\n this.#tokens = Math.min(\n this.maxTokens,\n this.#tokens + (elapsed * this.tokensPerInterval) / this.intervalMs,\n );\n this.#lastRefill = now;\n }\n\n #retryAfterMs(): number {\n const deficit = 1 - this.#tokens;\n\n return Math.max(0, Math.ceil((deficit * this.intervalMs) / this.tokensPerInterval));\n }\n}\n"],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unikvs/rate-limit",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.13",
|
|
4
|
+
"description": "Transformer plugin that limits operations per time window with a token bucket.",
|
|
5
|
+
"homepage": "https://tai-kun.github.io/unikvs/",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"url": "https://github.com/tai-kun/unikvs",
|
|
9
|
+
"directory": "packages/rate-limit"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src",
|
|
14
|
+
"package.json",
|
|
15
|
+
"LICENSE",
|
|
16
|
+
"README.md"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"default": "./dist/index.js"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@unikvs/core": "0.0.13",
|
|
28
|
+
"@unikvs/passthrough": "0.0.13",
|
|
29
|
+
"abort-signal-utils": "^0.0.6"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@unikvs/testing": "0.0.0",
|
|
33
|
+
"@vitest/browser-playwright": "5.0.5",
|
|
34
|
+
"@vitest/coverage-istanbul": "5.0.5",
|
|
35
|
+
"@vitest/coverage-v8": "5.0.5",
|
|
36
|
+
"playwright": "1.64.1",
|
|
37
|
+
"valibot": "1.5.0",
|
|
38
|
+
"vite-plus": "1.3.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@logtape/logtape": "^2.0.0"
|
|
42
|
+
},
|
|
43
|
+
"readme": "README.md",
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "vp -C .config pack"
|
|
46
|
+
}
|
|
6
47
|
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { type ErrorOptions, ErrorBase, setErrorMessage, InvalidUsageErrorBase } from "@unikvs/core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
5
|
+
*/
|
|
6
|
+
export type RateLimitExceededErrorMeta = {
|
|
7
|
+
/**
|
|
8
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-exceeded-retry-after-ms)
|
|
9
|
+
*/
|
|
10
|
+
readonly retryAfterMs: number;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
15
|
+
*/
|
|
16
|
+
export type RateLimitExceededErrorArgs = ErrorOptions & RateLimitExceededErrorMeta;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
20
|
+
*/
|
|
21
|
+
export class RateLimitExceededError extends ErrorBase<RateLimitExceededErrorMeta> {
|
|
22
|
+
static {
|
|
23
|
+
this.prototype.name = "RateLimitExceededError";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
|
|
28
|
+
*/
|
|
29
|
+
public constructor(args: RateLimitExceededErrorArgs) {
|
|
30
|
+
const { retryAfterMs, ...options } = args;
|
|
31
|
+
const meta: RateLimitExceededErrorMeta = { retryAfterMs };
|
|
32
|
+
super(
|
|
33
|
+
meta,
|
|
34
|
+
({ retryAfterMs: messageRetryAfterMs }) =>
|
|
35
|
+
`Rate limit exceeded. Retry after ${String(messageRetryAfterMs)}ms.`,
|
|
36
|
+
options,
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
setErrorMessage(
|
|
42
|
+
RateLimitExceededError,
|
|
43
|
+
({ retryAfterMs }) =>
|
|
44
|
+
`レート制限を超えました。${String(retryAfterMs)}ms 後に再試行してください。`,
|
|
45
|
+
"ja",
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
50
|
+
*/
|
|
51
|
+
export type RateLimitInvalidOptionErrorMeta = {
|
|
52
|
+
/**
|
|
53
|
+
* 不正だったオプション名です。
|
|
54
|
+
*
|
|
55
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-name)
|
|
56
|
+
*/
|
|
57
|
+
readonly name: string;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 指定された値です。
|
|
61
|
+
*
|
|
62
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-actual)
|
|
63
|
+
*/
|
|
64
|
+
readonly actual: unknown;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
69
|
+
*/
|
|
70
|
+
export type RateLimitInvalidOptionErrorArgs = ErrorOptions & RateLimitInvalidOptionErrorMeta;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* コンストラクターに不正なオプションが渡されたときのエラーです。
|
|
74
|
+
*
|
|
75
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
76
|
+
*/
|
|
77
|
+
export class RateLimitInvalidOptionError extends InvalidUsageErrorBase<RateLimitInvalidOptionErrorMeta> {
|
|
78
|
+
static {
|
|
79
|
+
this.prototype.name = "RateLimitInvalidOptionError";
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
|
|
84
|
+
*/
|
|
85
|
+
public constructor(args: RateLimitInvalidOptionErrorArgs) {
|
|
86
|
+
const { name, actual, ...options } = args;
|
|
87
|
+
const meta: RateLimitInvalidOptionErrorMeta = {
|
|
88
|
+
name,
|
|
89
|
+
actual,
|
|
90
|
+
};
|
|
91
|
+
super(
|
|
92
|
+
meta,
|
|
93
|
+
({ name: messageName, actual: messageActual }) =>
|
|
94
|
+
`Invalid RateLimit option ${JSON.stringify(messageName)}: ${formatActual(messageActual)}`,
|
|
95
|
+
options,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
setErrorMessage(
|
|
101
|
+
RateLimitInvalidOptionError,
|
|
102
|
+
({ name, actual }) =>
|
|
103
|
+
`無効な RateLimit オプション ${JSON.stringify(name)}: ${formatActual(actual)}`,
|
|
104
|
+
"ja",
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* エラーメッセージに埋め込む実際の値を整形します。
|
|
109
|
+
*
|
|
110
|
+
* @param actual 整形する値です。
|
|
111
|
+
*
|
|
112
|
+
* @returns 整形した文字列を返します。
|
|
113
|
+
*/
|
|
114
|
+
function formatActual(actual: unknown): string {
|
|
115
|
+
if (typeof actual === "string") {
|
|
116
|
+
return JSON.stringify(actual);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (
|
|
120
|
+
typeof actual === "number" ||
|
|
121
|
+
typeof actual === "boolean" ||
|
|
122
|
+
actual === null ||
|
|
123
|
+
actual === undefined
|
|
124
|
+
) {
|
|
125
|
+
return String(actual);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
try {
|
|
129
|
+
return JSON.stringify(actual) ?? "[object Object]";
|
|
130
|
+
} catch {
|
|
131
|
+
return "[object Object]";
|
|
132
|
+
}
|
|
133
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type {
|
|
2
|
+
RateLimitExceededErrorArgs,
|
|
3
|
+
RateLimitExceededErrorMeta,
|
|
4
|
+
RateLimitInvalidOptionErrorArgs,
|
|
5
|
+
RateLimitInvalidOptionErrorMeta,
|
|
6
|
+
} from "./errors.js";
|
|
7
|
+
export { RateLimitExceededError, RateLimitInvalidOptionError } from "./errors.js";
|
|
8
|
+
|
|
9
|
+
export type * from "./rate-limit.js";
|
|
10
|
+
export { default as RateLimit } from "./rate-limit.js";
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import type { IMiddleware } from "@unikvs/core";
|
|
2
|
+
import { PassThrough } from "@unikvs/passthrough";
|
|
3
|
+
import { getAbortReason, throwIfAborted } from "abort-signal-utils";
|
|
4
|
+
|
|
5
|
+
import { RateLimitExceededError, RateLimitInvalidOptionError } from "./errors.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* レート制限を超えたときの挙動です。
|
|
9
|
+
*
|
|
10
|
+
* - `"wait"` はトークンが補充されるまで待機します。
|
|
11
|
+
* - `"throw"` は直ちにエラーを投げます。
|
|
12
|
+
*
|
|
13
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-strategy)
|
|
14
|
+
*/
|
|
15
|
+
export type RateLimitStrategy = "wait" | "throw";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 待機処理の実装です。テストで時刻を制御するときに差し替えます。
|
|
19
|
+
*
|
|
20
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#irate-limit-sleep)
|
|
21
|
+
*/
|
|
22
|
+
export interface IRateLimitSleep {
|
|
23
|
+
(ms: number, signal: AbortSignal): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* RateLimit ミドルウェアのオプションです。
|
|
28
|
+
*
|
|
29
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options)
|
|
30
|
+
*/
|
|
31
|
+
export type RateLimitOptions = {
|
|
32
|
+
/**
|
|
33
|
+
* 1 インターバルあたりに補充されるトークン数です。既定値は `1` です。
|
|
34
|
+
*
|
|
35
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-tokens-per-interval)
|
|
36
|
+
*/
|
|
37
|
+
readonly tokensPerInterval?: number | undefined;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* トークンを補充する間隔 (ミリ秒) です。既定値は `1000` です。
|
|
41
|
+
*
|
|
42
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-interval-ms)
|
|
43
|
+
*/
|
|
44
|
+
readonly intervalMs?: number | undefined;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 保持できるトークンの上限です。既定値は `tokensPerInterval` です。
|
|
48
|
+
*
|
|
49
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-max-tokens)
|
|
50
|
+
*/
|
|
51
|
+
readonly maxTokens?: number | undefined;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* `maxTokens` の別名です。両方を指定した場合は `maxTokens` が優先されます。
|
|
55
|
+
*
|
|
56
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-burst)
|
|
57
|
+
*/
|
|
58
|
+
readonly burst?: number | undefined;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* レート制限を超えたときの挙動です。既定値は `"wait"` です。
|
|
62
|
+
*
|
|
63
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-strategy)
|
|
64
|
+
*/
|
|
65
|
+
readonly strategy?: RateLimitStrategy | undefined;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 現在時刻 (epoch ミリ秒) を返す関数です。既定値は `Date.now` です。
|
|
69
|
+
*
|
|
70
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-now)
|
|
71
|
+
*/
|
|
72
|
+
readonly now?: (() => number) | undefined;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 待機処理です。既定では `setTimeout` を使用します。
|
|
76
|
+
*
|
|
77
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-sleep)
|
|
78
|
+
*/
|
|
79
|
+
readonly sleep?: IRateLimitSleep | undefined;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
function defaultSleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
83
|
+
return new Promise<void>((resolve, reject) => {
|
|
84
|
+
if (signal.aborted) {
|
|
85
|
+
reject(getAbortReason(signal));
|
|
86
|
+
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const timer = setTimeout(() => {
|
|
91
|
+
signal.removeEventListener("abort", onAbort);
|
|
92
|
+
resolve();
|
|
93
|
+
}, ms);
|
|
94
|
+
const onAbort = (): void => {
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
reject(getAbortReason(signal));
|
|
97
|
+
};
|
|
98
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function assertPositiveNumber(name: string, value: number): void {
|
|
103
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
104
|
+
throw new RateLimitInvalidOptionError({
|
|
105
|
+
name,
|
|
106
|
+
actual: value,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* トークンバケットで操作頻度を制限するミドルウェアです。
|
|
113
|
+
*
|
|
114
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
115
|
+
*/
|
|
116
|
+
export default class RateLimit extends PassThrough implements IMiddleware {
|
|
117
|
+
/**
|
|
118
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
119
|
+
*/
|
|
120
|
+
public override readonly name: string = "RateLimit";
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 1 インターバルあたりに補充されるトークン数です。
|
|
124
|
+
*
|
|
125
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
126
|
+
*/
|
|
127
|
+
public readonly tokensPerInterval: number;
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* トークンを補充する間隔 (ミリ秒) です。
|
|
131
|
+
*
|
|
132
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
133
|
+
*/
|
|
134
|
+
public readonly intervalMs: number;
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* 保持できるトークンの上限です。
|
|
138
|
+
*
|
|
139
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
140
|
+
*/
|
|
141
|
+
public readonly maxTokens: number;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* レート制限を超えたときの挙動です。
|
|
145
|
+
*
|
|
146
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
147
|
+
*/
|
|
148
|
+
public readonly strategy: RateLimitStrategy;
|
|
149
|
+
|
|
150
|
+
readonly #now: () => number;
|
|
151
|
+
|
|
152
|
+
readonly #sleep: IRateLimitSleep;
|
|
153
|
+
|
|
154
|
+
#tokens: number;
|
|
155
|
+
|
|
156
|
+
#lastRefill: number;
|
|
157
|
+
|
|
158
|
+
#tail: Promise<void>;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* RateLimit ミドルウェアを作成します。
|
|
162
|
+
*
|
|
163
|
+
* @param options トークン数と補充間隔などの設定です。
|
|
164
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
165
|
+
*/
|
|
166
|
+
public constructor(options: RateLimitOptions = {}) {
|
|
167
|
+
super();
|
|
168
|
+
|
|
169
|
+
const {
|
|
170
|
+
now = Date.now,
|
|
171
|
+
burst,
|
|
172
|
+
sleep = defaultSleep,
|
|
173
|
+
strategy = "wait",
|
|
174
|
+
maxTokens,
|
|
175
|
+
intervalMs = 1000,
|
|
176
|
+
tokensPerInterval = 1,
|
|
177
|
+
} = options;
|
|
178
|
+
assertPositiveNumber("tokensPerInterval", tokensPerInterval);
|
|
179
|
+
assertPositiveNumber("intervalMs", intervalMs);
|
|
180
|
+
|
|
181
|
+
const capacity = maxTokens ?? burst ?? tokensPerInterval;
|
|
182
|
+
assertPositiveNumber("maxTokens", capacity);
|
|
183
|
+
|
|
184
|
+
if (strategy !== "wait" && strategy !== "throw") {
|
|
185
|
+
throw new RateLimitInvalidOptionError({
|
|
186
|
+
name: "strategy",
|
|
187
|
+
actual: strategy,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (typeof now !== "function") {
|
|
192
|
+
throw new RateLimitInvalidOptionError({
|
|
193
|
+
name: "now",
|
|
194
|
+
actual: now,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (typeof sleep !== "function") {
|
|
199
|
+
throw new RateLimitInvalidOptionError({
|
|
200
|
+
name: "sleep",
|
|
201
|
+
actual: sleep,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
this.tokensPerInterval = tokensPerInterval;
|
|
206
|
+
this.intervalMs = intervalMs;
|
|
207
|
+
this.maxTokens = capacity;
|
|
208
|
+
this.strategy = strategy;
|
|
209
|
+
this.#now = now;
|
|
210
|
+
this.#sleep = sleep;
|
|
211
|
+
this.#tokens = capacity;
|
|
212
|
+
this.#lastRefill = now();
|
|
213
|
+
this.#tail = Promise.resolve();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 現在保持しているトークン数です。
|
|
218
|
+
*
|
|
219
|
+
* [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
|
|
220
|
+
*/
|
|
221
|
+
public get availableTokens(): number {
|
|
222
|
+
this.#refill();
|
|
223
|
+
|
|
224
|
+
return this.#tokens;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
public async use(c: IMiddleware.UseContext, next: IMiddleware.INext): Promise<void> {
|
|
228
|
+
await this.#acquire(c.signal);
|
|
229
|
+
|
|
230
|
+
await next();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async #acquire(signal: AbortSignal): Promise<void> {
|
|
234
|
+
throwIfAborted(signal);
|
|
235
|
+
|
|
236
|
+
let release!: () => void;
|
|
237
|
+
const previous = this.#tail;
|
|
238
|
+
this.#tail = new Promise<void>((resolve) => {
|
|
239
|
+
release = resolve;
|
|
240
|
+
});
|
|
241
|
+
await previous;
|
|
242
|
+
|
|
243
|
+
try {
|
|
244
|
+
for (;;) {
|
|
245
|
+
throwIfAborted(signal);
|
|
246
|
+
this.#refill();
|
|
247
|
+
|
|
248
|
+
if (this.#tokens >= 1) {
|
|
249
|
+
this.#tokens -= 1;
|
|
250
|
+
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (this.strategy === "throw") {
|
|
255
|
+
throw new RateLimitExceededError({ retryAfterMs: this.#retryAfterMs() });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
await this.#sleep(this.#retryAfterMs(), signal);
|
|
259
|
+
}
|
|
260
|
+
} finally {
|
|
261
|
+
release();
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
#refill(): void {
|
|
266
|
+
const now = this.#now();
|
|
267
|
+
const elapsed = now - this.#lastRefill;
|
|
268
|
+
|
|
269
|
+
if (elapsed <= 0) {
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
this.#tokens = Math.min(
|
|
274
|
+
this.maxTokens,
|
|
275
|
+
this.#tokens + (elapsed * this.tokensPerInterval) / this.intervalMs,
|
|
276
|
+
);
|
|
277
|
+
this.#lastRefill = now;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
#retryAfterMs(): number {
|
|
281
|
+
const deficit = 1 - this.#tokens;
|
|
282
|
+
|
|
283
|
+
return Math.max(0, Math.ceil((deficit * this.intervalMs) / this.tokensPerInterval));
|
|
284
|
+
}
|
|
285
|
+
}
|