@aomex/rate-limit 0.0.28 → 1.0.1

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/CHANGELOG.md CHANGED
@@ -1,64 +1,15 @@
1
1
  # @aomex/rate-limit
2
2
 
3
- ## 0.0.28
3
+ ## 1.0.1
4
4
 
5
- ### Patch Changes
6
-
7
- - Updated dependencies [[`59cd3f9`](https://github.com/aomex/aomex/commit/59cd3f98a0b5648a972d6118ba21501130a9ee7e), [`90ca7d5`](https://github.com/aomex/aomex/commit/90ca7d5fc736b523c4fbf7949f64653428dc413c)]:
8
- - @aomex/web@0.0.29
9
- - @aomex/core@0.0.28
10
- - @aomex/memory-cache@0.0.28
11
-
12
- ## 0.0.27
13
-
14
- ### Patch Changes
15
-
16
- - [`00bafbb`](https://github.com/aomex/aomex/commit/00bafbbac2d32205b63a6bf561fb0a69c38a54bb) Thanks [@geekact](https://github.com/geekact)! - refactor(core): 缓存迁移到新的包@aomex/internal-cache
17
-
18
- - [`8becf8e`](https://github.com/aomex/aomex/commit/8becf8ee5ef86a5909783d0654e536db7be9bf5b) Thanks [@geekact](https://github.com/geekact)! - refactor(core): 工具移动到新的包@aomex/internal-tools
19
-
20
- - Updated dependencies [[`00bafbb`](https://github.com/aomex/aomex/commit/00bafbbac2d32205b63a6bf561fb0a69c38a54bb), [`8becf8e`](https://github.com/aomex/aomex/commit/8becf8ee5ef86a5909783d0654e536db7be9bf5b), [`0776719`](https://github.com/aomex/aomex/commit/077671963401f1dafb5b03722899452d45df13fc), [`f996bf7`](https://github.com/aomex/aomex/commit/f996bf7e529e7751a5e858c579feed33f5f02d65)]:
21
- - @aomex/memory-cache@0.0.27
22
- - @aomex/core@0.0.27
23
- - @aomex/web@0.0.28
24
- - @aomex/internal-tools@0.0.27
25
-
26
- ## 0.0.26
27
-
28
- ### Patch Changes
29
-
30
- - Updated dependencies [[`33c3c61`](https://github.com/aomex/aomex/commit/33c3c614be9f66077f7487350b88d2db854f5fc8), [`fbcea3d`](https://github.com/aomex/aomex/commit/fbcea3d68ff033e6861130c645c8e5ad7336193f)]:
31
- - @aomex/web@0.0.27
32
- - @aomex/core@0.0.26
33
-
34
- ## 0.0.25
35
-
36
- ### Patch Changes
37
-
38
- - Updated dependencies [[`5ef2022`](https://github.com/aomex/aomex/commit/5ef202248b4320ff9076fbecb54379055cffb7db), [`8d9e9d8`](https://github.com/aomex/aomex/commit/8d9e9d8ece0bbcc7e1ac685702eacbfdfa145aa9), [`0e6ed2c`](https://github.com/aomex/aomex/commit/0e6ed2c611100dcfaafb6fb41357624ad9f5c67a)]:
39
- - @aomex/web@0.0.26
40
- - @aomex/core@0.0.25
41
-
42
- ## 0.0.24
43
-
44
- ### Patch Changes
45
-
46
- - Updated dependencies [[`2ac62fd`](https://github.com/aomex/aomex/commit/2ac62fd28166a1d9dd60b3c6d5a6508a6f9ee82b), [`4258410`](https://github.com/aomex/aomex/commit/42584107ad9f7e34492ae1053fef83aa2d9d747a), [`4177cba`](https://github.com/aomex/aomex/commit/4177cba7877e38120842bd8d287eaed54e4926ca)]:
47
- - @aomex/core@0.0.24
48
- - @aomex/web@0.0.25
49
-
50
- ## 0.0.23
51
-
52
- ### Patch Changes
5
+ ## 1.0.0
53
6
 
54
- - Updated dependencies [[`6621e4f`](https://github.com/aomex/aomex/commit/6621e4ff0f3509beeb332a0571a7db9c7d6ca99a), [`7b09277`](https://github.com/aomex/aomex/commit/7b09277136910966f500c8132303c7ddee84340c), [`46c5b72`](https://github.com/aomex/aomex/commit/46c5b72785011fa181767f4c8ea0d0f5008b21ae), [`9c78999`](https://github.com/aomex/aomex/commit/9c78999ebcb2962f30344acfbf6de0733d6fdd41), [`f4b012d`](https://github.com/aomex/aomex/commit/f4b012d98cddb2918479ea05df6c266dd914e53a)]:
55
- - @aomex/web@0.0.24
56
- - @aomex/core@0.0.23
7
+ ### Minor Changes
57
8
 
58
- ## 0.0.22
9
+ - [`11103a2`](https://github.com/aomex/aomex/commit/11103a2aff4e081754c56b0ff18fa5130ca252e8) Thanks [@geekact](https://github.com/geekact)! - 重新制作
59
10
 
60
11
  ### Patch Changes
61
12
 
62
- - Updated dependencies [[`6f7d706`](https://github.com/aomex/aomex/commit/6f7d7066c23711abdd149eb1c9a293ab8c4284a4), [`e21007a`](https://github.com/aomex/aomex/commit/e21007a82cb8eac73e1f696340bbe986d57dc159), [`e7bf93c`](https://github.com/aomex/aomex/commit/e7bf93cee6896c61d0bf3eb0921151dc6c1bc107), [`e21007a`](https://github.com/aomex/aomex/commit/e21007a82cb8eac73e1f696340bbe986d57dc159), [`818e840`](https://github.com/aomex/aomex/commit/818e840d36c7456a863fc071968b246c123c17f5), [`fb6c72d`](https://github.com/aomex/aomex/commit/fb6c72dbb266be4db92a542afe93dfa5d8c7cd41)]:
63
- - @aomex/core@0.0.22
64
- - @aomex/web@0.0.23
13
+ - Updated dependencies [[`11103a2`](https://github.com/aomex/aomex/commit/11103a2aff4e081754c56b0ff18fa5130ca252e8)]:
14
+ - @aomex/core@1.0.0
15
+ - @aomex/web@1.0.0
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2023 geekact
3
+ Copyright (c) 2023-2024 geekact
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/dist/index.d.ts CHANGED
@@ -1,19 +1,41 @@
1
- import { Caching } from '@aomex/core';
2
1
  import { WebContext, WebMiddleware } from '@aomex/web';
3
2
 
3
+ declare abstract class RateLimitStore {
4
+ abstract getAndSet(data: {
5
+ key: string;
6
+ maxRequest: number;
7
+ duration: number;
8
+ }): Promise<RateLimitState>;
9
+ protected getMicroTime(): number;
10
+ }
11
+ interface RateLimitState {
12
+ /**
13
+ * 标识
14
+ */
15
+ key: string;
16
+ /**
17
+ * 重置的具体时间戳,单位:`us`
18
+ */
19
+ resetAt: number;
20
+ /**
21
+ * 剩余可用请求次数
22
+ */
23
+ remaining: number;
24
+ }
25
+
4
26
  interface RateLimitOptions {
5
27
  /**
6
- * 存储和共享请求记录。默认值:`MemoryCache`
28
+ * 存储和共享请求记录。默认值:`RateLimitMemoryStore`
7
29
  */
8
- driver?: Caching;
30
+ store?: RateLimitStore;
9
31
  /**
10
- * 限速时间周期。默认值:`3600 * 1000`(1小时)
32
+ * 限速时间周期。单位:`ms`。默认值:`3600 * 1000`(1小时)
11
33
  */
12
34
  duration?: number;
13
35
  /**
14
36
  * 一个客户端(根据id字段)在一个时间周期内的最大可请求数量
15
37
  */
16
- max?: number;
38
+ maxRequest?: number;
17
39
  /**
18
40
  * 请求客户端的身份识别信息,默认使用客户端的IP地址。如果返回`false`,则代表该请求不需要限速
19
41
  */
@@ -50,4 +72,4 @@ interface RateLimitOptions {
50
72
  }
51
73
  declare const rateLimit: (options?: RateLimitOptions) => WebMiddleware;
52
74
 
53
- export { RateLimitOptions, rateLimit };
75
+ export { type RateLimitOptions, type RateLimitState, RateLimitStore, rateLimit };
package/dist/index.js CHANGED
@@ -1,71 +1,82 @@
1
- // src/index.ts
1
+ // src/rate-limit.ts
2
2
  import { middleware } from "@aomex/core";
3
- import { MemoryCache } from "@aomex/memory-cache";
4
- import microtime from "microtime";
5
- import ms from "ms";
6
- var getState = async (cache, id, max, duration) => {
7
- const key = `ratelimit:${id}`;
8
- let state = await cache.get(key);
9
- const now = microtime.now();
10
- const expired = state && state.reset * 1e6 < now;
11
- if (!state || expired) {
12
- state = {
13
- id,
14
- reset: (now + duration * 1e3) / 1e6,
15
- current: max,
16
- total: max
17
- };
18
- } else {
19
- state.current = state.current > 0 ? state.current - 1 : 0;
3
+ import { statuses } from "@aomex/web";
4
+
5
+ // src/store.ts
6
+ var time = Date.now() * 1e3;
7
+ var start = process.hrtime.bigint();
8
+ var RateLimitStore = class {
9
+ getMicroTime() {
10
+ return time + Number(process.hrtime.bigint() - start) * 1e-3;
20
11
  }
21
- await cache.set(key, state);
22
- return state;
23
12
  };
13
+
14
+ // src/memory-store.ts
15
+ var RateLimitMemoryStore = class extends RateLimitStore {
16
+ store = /* @__PURE__ */ new Map();
17
+ async getAndSet(data) {
18
+ const { key, maxRequest, duration } = data;
19
+ const now = this.getMicroTime();
20
+ const durationMicro = duration * 1e3;
21
+ const startTime = now - durationMicro;
22
+ let result = this.store.get(key);
23
+ if (!result || result.expires < now) {
24
+ this.store.set(key, result = { expires: now + durationMicro, records: [] });
25
+ }
26
+ result.records = result.records.filter((record) => record >= startTime);
27
+ const usedCount = result.records.length;
28
+ result.records.push(now);
29
+ result.records = result.records.slice(-maxRequest);
30
+ result.expires = now + durationMicro;
31
+ const remaining = Math.max(maxRequest - usedCount, 0);
32
+ const resetAt = Math.floor(result.records[0] + durationMicro);
33
+ return { key, remaining, resetAt };
34
+ }
35
+ };
36
+
37
+ // src/rate-limit.ts
24
38
  var rateLimit = (options = {}) => {
25
39
  const {
26
- driver: cache = new MemoryCache(),
40
+ store = new RateLimitMemoryStore(),
27
41
  duration = 3600 * 1e3,
28
- // 1 hour
29
- max = 2500,
42
+ // 1小时
43
+ maxRequest = 2500,
30
44
  id: getId = (ctx) => ctx.request.ip,
31
45
  headers: headerNames = {},
32
- denyList,
33
- allowList
46
+ denyList = () => false,
47
+ allowList = () => false
34
48
  } = options;
35
49
  return middleware.web(async (ctx, next) => {
36
- if (denyList && await denyList(ctx)) {
37
- ctx.throw(403);
38
- }
50
+ if (await denyList(ctx))
51
+ ctx.throw(403, "denied");
39
52
  const id = getId(ctx);
40
- if (id === false || allowList && await allowList(ctx)) {
53
+ if (id === false || await allowList(ctx))
41
54
  return next();
42
- }
43
- const { response } = ctx;
44
- const state = await getState(cache, id, max, duration);
45
- let headers = {};
55
+ const state = await store.getAndSet({
56
+ key: `aomex-rate-limit:${id}`,
57
+ maxRequest,
58
+ duration
59
+ });
60
+ const headers = {};
46
61
  if (headerNames !== false) {
47
- const {
48
- remaining = "X-RateLimit-Remaining",
49
- reset = "X-RateLimit-Reset",
50
- total = "X-RateLimit-Limit"
51
- } = headerNames;
52
- headers = {
53
- [remaining]: state.current > 0 ? state.current - 1 : 0,
54
- [reset]: state.reset,
55
- [total]: state.total
56
- };
57
- response.setHeaders(headers);
62
+ headers[headerNames.remaining || "X-RateLimit-Remaining"] = Math.max(
63
+ 0,
64
+ state.remaining - 1
65
+ );
66
+ headers[headerNames.reset || "X-RateLimit-Reset"] = Math.floor(
67
+ state.resetAt / 1e6
68
+ );
69
+ headers[headerNames.total || "X-RateLimit-Limit"] = maxRequest;
70
+ ctx.response.setHeaders(headers);
58
71
  }
59
- if (state.current)
72
+ if (state.remaining)
60
73
  return next();
61
- const now = Date.now();
62
- const delta = Math.round(state.reset * 1e3 - now);
63
- const body = options.errorMessage || `Rate limit exceeded, retry in ${ms(delta, { long: true })}.`;
64
- headers["Retry-After"] = Math.round(state.reset - now / 1e3);
65
- ctx.throw(429, body, { headers });
74
+ headers["Retry-After"] = Math.round((state.resetAt / 1e3 - Date.now()) / 1e3);
75
+ ctx.throw(429, options.errorMessage || statuses.message[429], { headers });
66
76
  });
67
77
  };
68
78
  export {
79
+ RateLimitStore,
69
80
  rateLimit
70
81
  };
71
82
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { middleware, Caching } from '@aomex/core';\nimport type { WebContext, WebMiddleware } from '@aomex/web';\nimport { MemoryCache } from '@aomex/memory-cache';\nimport microtime from 'microtime';\nimport ms from 'ms';\n\nexport interface RateLimitOptions {\n /**\n * 存储和共享请求记录。默认值:`MemoryCache`\n */\n driver?: Caching;\n\n /**\n * 限速时间周期。默认值:`3600 * 1000`(1小时)\n */\n duration?: number;\n\n /**\n * 一个客户端(根据id字段)在一个时间周期内的最大可请求数量\n */\n max?: number;\n\n /**\n * 请求客户端的身份识别信息,默认使用客户端的IP地址。如果返回`false`,则代表该请求不需要限速\n */\n id?: (ctx: WebContext) => string | false;\n\n /**\n * 被限速(状态码:429)时响应的报错信息\n */\n errorMessage?: string;\n\n /**\n * 相关的响应头部名称。如果传入`false`,则代表不设置\n */\n headers?:\n | false\n | {\n /**\n * 指定时间段内剩下的请求次数。默认名称:`X-RateLimit-Remaining`\n */\n remaining?: string;\n /**\n * 以UTC秒为单位,限流重置之前的剩余时间。默认名称:`X-RateLimit-Reset`\n */\n reset?: string;\n /**\n * 指定时间内允许的最大请求次数。默认名称:`X-RateLimit-Limit`\n */\n total?: string;\n };\n\n /**\n * 白名单,不做请求频率限制\n */\n allowList?: (ctx: WebContext) => boolean | Promise<boolean>;\n\n /**\n * 黑名单,直接抛出`403`状态码\n */\n denyList?: (ctx: WebContext) => boolean | Promise<boolean>;\n}\n\ninterface LimitState {\n id: string;\n reset: number;\n current: number;\n total: number;\n}\n\nconst getState = async (\n cache: Caching,\n id: string,\n max: number,\n duration: number,\n) => {\n const key = `ratelimit:${id}`;\n let state = await cache.get<LimitState>(key);\n const now = microtime.now();\n const expired = state && state.reset * 1e6 < now;\n\n if (!state || expired) {\n state = {\n id,\n reset: (now + duration * 1e3) / 1e6,\n current: max,\n total: max,\n };\n } else {\n state.current = state.current > 0 ? state.current - 1 : 0;\n }\n\n await cache.set(key, state);\n return state!;\n};\n\nexport const rateLimit = (options: RateLimitOptions = {}): WebMiddleware => {\n const {\n driver: cache = new MemoryCache(),\n duration = 3600 * 1000, // 1 hour\n max = 2500,\n id: getId = (ctx) => ctx.request.ip,\n headers: headerNames = {},\n denyList,\n allowList,\n } = options;\n\n return middleware.web(async (ctx, next) => {\n if (denyList && (await denyList(ctx))) {\n ctx.throw(403);\n }\n\n const id = getId(ctx);\n if (id === false || (allowList && (await allowList(ctx)))) {\n return next();\n }\n\n const { response } = ctx;\n const state = await getState(cache, id, max, duration);\n let headers: Record<string, number> = {};\n if (headerNames !== false) {\n const {\n remaining = 'X-RateLimit-Remaining',\n reset = 'X-RateLimit-Reset',\n total = 'X-RateLimit-Limit',\n } = headerNames;\n\n headers = {\n [remaining]: state.current > 0 ? state.current - 1 : 0,\n [reset]: state.reset,\n [total]: state.total,\n };\n response.setHeaders(headers);\n }\n\n if (state.current) return next();\n\n const now = Date.now();\n const delta = Math.round(state.reset * 1e3 - now);\n const body =\n options.errorMessage ||\n `Rate limit exceeded, retry in ${ms(delta, { long: true })}.`;\n\n headers['Retry-After'] = Math.round(state.reset - now / 1e3);\n ctx.throw(429, body, { headers });\n });\n};\n"],"mappings":";AAAA,SAAS,kBAA2B;AAEpC,SAAS,mBAAmB;AAC5B,OAAO,eAAe;AACtB,OAAO,QAAQ;AAkEf,IAAM,WAAW,OACf,OACA,IACA,KACA,aACG;AACH,QAAM,MAAM,aAAa,EAAE;AAC3B,MAAI,QAAQ,MAAM,MAAM,IAAgB,GAAG;AAC3C,QAAM,MAAM,UAAU,IAAI;AAC1B,QAAM,UAAU,SAAS,MAAM,QAAQ,MAAM;AAE7C,MAAI,CAAC,SAAS,SAAS;AACrB,YAAQ;AAAA,MACN;AAAA,MACA,QAAQ,MAAM,WAAW,OAAO;AAAA,MAChC,SAAS;AAAA,MACT,OAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,UAAM,UAAU,MAAM,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,EAC1D;AAEA,QAAM,MAAM,IAAI,KAAK,KAAK;AAC1B,SAAO;AACT;AAEO,IAAM,YAAY,CAAC,UAA4B,CAAC,MAAqB;AAC1E,QAAM;AAAA,IACJ,QAAQ,QAAQ,IAAI,YAAY;AAAA,IAChC,WAAW,OAAO;AAAA;AAAA,IAClB,MAAM;AAAA,IACN,IAAI,QAAQ,CAAC,QAAQ,IAAI,QAAQ;AAAA,IACjC,SAAS,cAAc,CAAC;AAAA,IACxB;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,SAAO,WAAW,IAAI,OAAO,KAAK,SAAS;AACzC,QAAI,YAAa,MAAM,SAAS,GAAG,GAAI;AACrC,UAAI,MAAM,GAAG;AAAA,IACf;AAEA,UAAM,KAAK,MAAM,GAAG;AACpB,QAAI,OAAO,SAAU,aAAc,MAAM,UAAU,GAAG,GAAK;AACzD,aAAO,KAAK;AAAA,IACd;AAEA,UAAM,EAAE,SAAS,IAAI;AACrB,UAAM,QAAQ,MAAM,SAAS,OAAO,IAAI,KAAK,QAAQ;AACrD,QAAI,UAAkC,CAAC;AACvC,QAAI,gBAAgB,OAAO;AACzB,YAAM;AAAA,QACJ,YAAY;AAAA,QACZ,QAAQ;AAAA,QACR,QAAQ;AAAA,MACV,IAAI;AAEJ,gBAAU;AAAA,QACR,CAAC,SAAS,GAAG,MAAM,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,QACrD,CAAC,KAAK,GAAG,MAAM;AAAA,QACf,CAAC,KAAK,GAAG,MAAM;AAAA,MACjB;AACA,eAAS,WAAW,OAAO;AAAA,IAC7B;AAEA,QAAI,MAAM;AAAS,aAAO,KAAK;AAE/B,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,QAAQ,KAAK,MAAM,MAAM,QAAQ,MAAM,GAAG;AAChD,UAAM,OACJ,QAAQ,gBACR,iCAAiC,GAAG,OAAO,EAAE,MAAM,KAAK,CAAC,CAAC;AAE5D,YAAQ,aAAa,IAAI,KAAK,MAAM,MAAM,QAAQ,MAAM,GAAG;AAC3D,QAAI,MAAM,KAAK,MAAM,EAAE,QAAQ,CAAC;AAAA,EAClC,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/rate-limit.ts","../src/store.ts","../src/memory-store.ts"],"sourcesContent":["import { middleware } from '@aomex/core';\nimport { statuses, type WebContext, type WebMiddleware } from '@aomex/web';\nimport type { RateLimitStore } from './store';\nimport { RateLimitMemoryStore } from './memory-store';\n\nexport interface RateLimitOptions {\n /**\n * 存储和共享请求记录。默认值:`RateLimitMemoryStore`\n */\n store?: RateLimitStore;\n\n /**\n * 限速时间周期。单位:`ms`。默认值:`3600 * 1000`(1小时)\n */\n duration?: number;\n\n /**\n * 一个客户端(根据id字段)在一个时间周期内的最大可请求数量\n */\n maxRequest?: number;\n\n /**\n * 请求客户端的身份识别信息,默认使用客户端的IP地址。如果返回`false`,则代表该请求不需要限速\n */\n id?: (ctx: WebContext) => string | false;\n\n /**\n * 被限速(状态码:429)时响应的报错信息\n */\n errorMessage?: string;\n\n /**\n * 相关的响应头部名称。如果传入`false`,则代表不设置\n */\n headers?:\n | false\n | {\n /**\n * 指定时间段内剩下的请求次数。默认名称:`X-RateLimit-Remaining`\n */\n remaining?: string;\n /**\n * 以UTC秒为单位,限流重置之前的剩余时间。默认名称:`X-RateLimit-Reset`\n */\n reset?: string;\n /**\n * 指定时间内允许的最大请求次数。默认名称:`X-RateLimit-Limit`\n */\n total?: string;\n };\n\n /**\n * 白名单,不做请求频率限制\n */\n allowList?: (ctx: WebContext) => boolean | Promise<boolean>;\n\n /**\n * 黑名单,直接抛出`403`状态码\n */\n denyList?: (ctx: WebContext) => boolean | Promise<boolean>;\n}\n\nexport const rateLimit = (options: RateLimitOptions = {}): WebMiddleware => {\n const {\n store = new RateLimitMemoryStore(),\n duration = 3600 * 1_000, // 1小时\n maxRequest = 2500,\n id: getId = (ctx) => ctx.request.ip,\n headers: headerNames = {},\n denyList = () => false,\n allowList = () => false,\n } = options;\n\n return middleware.web(async (ctx, next) => {\n if (await denyList(ctx)) ctx.throw(403, 'denied');\n\n const id = getId(ctx);\n if (id === false || (await allowList(ctx))) return next();\n\n const state = await store.getAndSet({\n key: `aomex-rate-limit:${id}`,\n maxRequest,\n duration,\n });\n\n const headers: Record<string, number> = {};\n if (headerNames !== false) {\n headers[headerNames.remaining || 'X-RateLimit-Remaining'] = Math.max(\n 0,\n state.remaining - 1,\n );\n headers[headerNames.reset || 'X-RateLimit-Reset'] = Math.floor(\n state.resetAt / 1_000_000,\n );\n headers[headerNames.total || 'X-RateLimit-Limit'] = maxRequest;\n ctx.response.setHeaders(headers);\n }\n\n if (state.remaining) return next();\n\n headers['Retry-After'] = Math.round((state.resetAt / 1000 - Date.now()) / 1000);\n ctx.throw(429, options.errorMessage || statuses.message[429], { headers });\n });\n};\n","const time = Date.now() * 1e3;\nconst start = process.hrtime.bigint();\n\nexport abstract class RateLimitStore {\n abstract getAndSet(data: {\n key: string;\n maxRequest: number;\n duration: number;\n }): Promise<RateLimitState>;\n\n protected getMicroTime() {\n return time + Number(process.hrtime.bigint() - start) * 1e-3;\n }\n}\n\nexport interface RateLimitState {\n /**\n * 标识\n */\n key: string;\n /**\n * 重置的具体时间戳,单位:`us`\n */\n resetAt: number;\n /**\n * 剩余可用请求次数\n */\n remaining: number;\n}\n","import { RateLimitStore, type RateLimitState } from './store';\n\nexport class RateLimitMemoryStore extends RateLimitStore {\n private store = new Map<string, { expires: number; records: number[] }>();\n\n override async getAndSet(data: {\n key: string;\n maxRequest: number;\n duration: number;\n }): Promise<RateLimitState> {\n const { key, maxRequest, duration } = data;\n const now = this.getMicroTime();\n const durationMicro = duration * 1_000;\n const startTime = now - durationMicro;\n\n let result = this.store.get(key);\n if (!result || result.expires < now) {\n this.store.set(key, (result = { expires: now + durationMicro, records: [] }));\n }\n\n result.records = result.records.filter((record) => record >= startTime);\n const usedCount = result.records.length;\n result.records.push(now);\n result.records = result.records.slice(-maxRequest);\n result.expires = now + durationMicro;\n\n const remaining = Math.max(maxRequest - usedCount, 0);\n const resetAt = Math.floor(result.records[0]! + durationMicro);\n\n return { key, remaining, resetAt };\n }\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAqD;;;ACD9D,IAAM,OAAO,KAAK,IAAI,IAAI;AAC1B,IAAM,QAAQ,QAAQ,OAAO,OAAO;AAE7B,IAAe,iBAAf,MAA8B;AAAA,EAOzB,eAAe;AACvB,WAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,IAAI,KAAK,IAAI;AAAA,EAC1D;AACF;;;ACXO,IAAM,uBAAN,cAAmC,eAAe;AAAA,EAC/C,QAAQ,oBAAI,IAAoD;AAAA,EAExE,MAAe,UAAU,MAIG;AAC1B,UAAM,EAAE,KAAK,YAAY,SAAS,IAAI;AACtC,UAAM,MAAM,KAAK,aAAa;AAC9B,UAAM,gBAAgB,WAAW;AACjC,UAAM,YAAY,MAAM;AAExB,QAAI,SAAS,KAAK,MAAM,IAAI,GAAG;AAC/B,QAAI,CAAC,UAAU,OAAO,UAAU,KAAK;AACnC,WAAK,MAAM,IAAI,KAAM,SAAS,EAAE,SAAS,MAAM,eAAe,SAAS,CAAC,EAAE,CAAE;AAAA,IAC9E;AAEA,WAAO,UAAU,OAAO,QAAQ,OAAO,CAAC,WAAW,UAAU,SAAS;AACtE,UAAM,YAAY,OAAO,QAAQ;AACjC,WAAO,QAAQ,KAAK,GAAG;AACvB,WAAO,UAAU,OAAO,QAAQ,MAAM,CAAC,UAAU;AACjD,WAAO,UAAU,MAAM;AAEvB,UAAM,YAAY,KAAK,IAAI,aAAa,WAAW,CAAC;AACpD,UAAM,UAAU,KAAK,MAAM,OAAO,QAAQ,CAAC,IAAK,aAAa;AAE7D,WAAO,EAAE,KAAK,WAAW,QAAQ;AAAA,EACnC;AACF;;;AF+BO,IAAM,YAAY,CAAC,UAA4B,CAAC,MAAqB;AAC1E,QAAM;AAAA,IACJ,QAAQ,IAAI,qBAAqB;AAAA,IACjC,WAAW,OAAO;AAAA;AAAA,IAClB,aAAa;AAAA,IACb,IAAI,QAAQ,CAAC,QAAQ,IAAI,QAAQ;AAAA,IACjC,SAAS,cAAc,CAAC;AAAA,IACxB,WAAW,MAAM;AAAA,IACjB,YAAY,MAAM;AAAA,EACpB,IAAI;AAEJ,SAAO,WAAW,IAAI,OAAO,KAAK,SAAS;AACzC,QAAI,MAAM,SAAS,GAAG;AAAG,UAAI,MAAM,KAAK,QAAQ;AAEhD,UAAM,KAAK,MAAM,GAAG;AACpB,QAAI,OAAO,SAAU,MAAM,UAAU,GAAG;AAAI,aAAO,KAAK;AAExD,UAAM,QAAQ,MAAM,MAAM,UAAU;AAAA,MAClC,KAAK,oBAAoB,EAAE;AAAA,MAC3B;AAAA,MACA;AAAA,IACF,CAAC;AAED,UAAM,UAAkC,CAAC;AACzC,QAAI,gBAAgB,OAAO;AACzB,cAAQ,YAAY,aAAa,uBAAuB,IAAI,KAAK;AAAA,QAC/D;AAAA,QACA,MAAM,YAAY;AAAA,MACpB;AACA,cAAQ,YAAY,SAAS,mBAAmB,IAAI,KAAK;AAAA,QACvD,MAAM,UAAU;AAAA,MAClB;AACA,cAAQ,YAAY,SAAS,mBAAmB,IAAI;AACpD,UAAI,SAAS,WAAW,OAAO;AAAA,IACjC;AAEA,QAAI,MAAM;AAAW,aAAO,KAAK;AAEjC,YAAQ,aAAa,IAAI,KAAK,OAAO,MAAM,UAAU,MAAO,KAAK,IAAI,KAAK,GAAI;AAC9E,QAAI,MAAM,KAAK,QAAQ,gBAAgB,SAAS,QAAQ,GAAG,GAAG,EAAE,QAAQ,CAAC;AAAA,EAC3E,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aomex/rate-limit",
3
- "version": "0.0.28",
4
- "description": "Web request rate limit",
3
+ "version": "1.0.1",
4
+ "description": "请求限速",
5
5
  "repository": "git@github.com:aomex/aomex.git",
6
6
  "homepage": "https://aomex.js.org",
7
7
  "license": "MIT",
@@ -26,22 +26,13 @@
26
26
  "access": "public"
27
27
  },
28
28
  "peerDependencies": {
29
- "@aomex/core": "^0.0.28",
30
- "@aomex/web": "^0.0.29"
31
- },
32
- "dependencies": {
33
- "microtime": "^3.1.1",
34
- "ms": "^2.1.3",
35
- "@aomex/internal-tools": "^0.0.27",
36
- "@aomex/memory-cache": "^0.0.28"
29
+ "@aomex/core": "^1.0.0",
30
+ "@aomex/web": "^1.0.0"
37
31
  },
38
32
  "devDependencies": {
39
- "@aomex/core": "^0.0.28",
40
- "@aomex/web": "^0.0.29",
41
- "@types/microtime": "^2.1.0",
42
- "@types/ms": "^0.7.31"
33
+ "@aomex/core": "^1.0.1",
34
+ "@aomex/internal-tools": "^1.0.1",
35
+ "@aomex/web": "^1.0.1"
43
36
  },
44
- "scripts": {
45
- "test": "vitest"
46
- }
37
+ "scripts": {}
47
38
  }