@yiffy/ratelimiter 0.0.0-stage → 0.1.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) undefined Donovan_DMC
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 all
13
+ 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 THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @yiffy/ratelimiter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A client for a shared rate limit service. It asks the service whether a request to a host can go out yet, and doesn't send anything itself. The limits live in the service's config, so every app sharing one doesn't need to know what they are, and each says who it is so the service can show who's using a limit.
4
+
5
+ The service is in [DonovanDMC/ServerConfig](https://github.com/DonovanDMC/ServerConfig) under `stacks/ratelimit`. Its API is one call:
6
+
7
+ ```
8
+ POST /check {"host": "e621.net", "source": "my-app"}
9
+ 200 {"allowed": true, "retryAfter": 0, "limit": {"rate": 2, "burst": 1}}
10
+ 429 {"allowed": false, "retryAfter": 420, "limit": {"rate": 2, "burst": 1}}
11
+ ```
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pnpm add @yiffy/ratelimiter
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```ts
22
+ import RateLimiter from "@yiffy/ratelimiter";
23
+
24
+ const limiter = new RateLimiter({ url: "http://ratelimit.local", source: "my-app" });
25
+
26
+ // waits until it's allowed, then runs it
27
+ const res = await limiter.run("https://e621.net/posts.json", () => fetch("https://e621.net/posts.json"));
28
+
29
+ // or on its own
30
+ await limiter.wait("e621.net");
31
+
32
+ // or just ask, an allowed check counts as the request
33
+ const { allowed, retryAfter, limit } = await limiter.check("e621.net");
34
+ ```
35
+
36
+ A url is checked as its hostname. Hosts the service has no limit for are always allowed, with `limit: null`.
37
+
38
+ `wait` and `run` take an `AbortSignal` as their last argument.
39
+
40
+ ### Options
41
+
42
+ | Option | Default | |
43
+ |---|---|---|
44
+ | `url` | | The service's url |
45
+ | `source` | *(none)* | Who's asking, shown on the service's status. Shows as `unknown` without it |
46
+ | `timeout` | `5000` | How long to wait for the service, in ms |
47
+ | `failOpen` | `false` | Let requests go when the service can't be reached, instead of throwing a `RateLimiterError` |
48
+
49
+ ## License
50
+
51
+ MIT
@@ -0,0 +1,41 @@
1
+ /** A url is checked as its hostname */
2
+ export type Target = string | URL;
3
+ export interface RateLimiterOptions {
4
+ /** Let requests go when the service can't be reached, instead of throwing */
5
+ failOpen?: boolean;
6
+ /** Who's asking, shown on the service's status so it's clear who's using a limit */
7
+ source?: string;
8
+ /** How long to wait for the service, in ms */
9
+ timeout?: number;
10
+ /** The service's url, like http://ratelimit.local */
11
+ url: string;
12
+ }
13
+ export interface Limit {
14
+ /** How many can go at once after a quiet spell */
15
+ burst: number;
16
+ /** Requests a second */
17
+ rate: number;
18
+ }
19
+ export interface Check {
20
+ allowed: boolean;
21
+ /** The host's limit, null when it isn't limited */
22
+ limit: Limit | null;
23
+ /** How long until it can go in ms, 0 when allowed */
24
+ retryAfter: number;
25
+ }
26
+ export declare class RateLimiterError extends Error {
27
+ name: string;
28
+ }
29
+ export default class RateLimiter {
30
+ failOpen: boolean;
31
+ source: string | undefined;
32
+ timeout: number;
33
+ url: string;
34
+ constructor({ failOpen, source, timeout, url }: RateLimiterOptions);
35
+ /** Whether a request can go now. An allowed check counts as the request */
36
+ check(target: Target): Promise<Check>;
37
+ /** Check and wait until it's allowed, then run fn */
38
+ run<T>(target: Target, fn: () => T | Promise<T>, signal?: AbortSignal): Promise<T>;
39
+ /** Check until it's allowed. That last check counts as the request, so make it straight after */
40
+ wait(target: Target, signal?: AbortSignal): Promise<void>;
41
+ }
package/dist/index.js ADDED
@@ -0,0 +1,63 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ export class RateLimiterError extends Error {
3
+ name = "RateLimiterError";
4
+ }
5
+ const hostOf = (target) => target instanceof URL ? target.hostname : URL.canParse(target) ? new URL(target).hostname : target;
6
+ export default class RateLimiter {
7
+ failOpen;
8
+ source;
9
+ timeout;
10
+ url;
11
+ constructor({ failOpen = false, source, timeout = 5000, url }) {
12
+ this.failOpen = failOpen;
13
+ this.source = source;
14
+ this.timeout = timeout;
15
+ this.url = new URL("/check", url).href;
16
+ }
17
+ /** Whether a request can go now. An allowed check counts as the request */
18
+ async check(target) {
19
+ let res;
20
+ try {
21
+ res = await fetch(this.url, {
22
+ method: "POST",
23
+ headers: { "Content-Type": "application/json" },
24
+ body: JSON.stringify({ host: hostOf(target), source: this.source }),
25
+ signal: AbortSignal.timeout(this.timeout),
26
+ });
27
+ }
28
+ catch (err) {
29
+ if (this.failOpen)
30
+ return { allowed: true, limit: null, retryAfter: 0 };
31
+ throw new RateLimiterError(`couldn't reach ${this.url}: ${String(err)}`, { cause: err });
32
+ }
33
+ if (res.status !== 200 && res.status !== 429) {
34
+ if (this.failOpen)
35
+ return { allowed: true, limit: null, retryAfter: 0 };
36
+ throw new RateLimiterError(`${this.url} returned ${res.status}: ${await res.text()}`);
37
+ }
38
+ const { limit = null, retryAfter } = await res.json().catch(() => ({}));
39
+ if (res.status === 200)
40
+ return { allowed: true, limit, retryAfter: 0 };
41
+ // a second if it didn't say, so a bad reply can't make wait() spin
42
+ return { allowed: false, limit, retryAfter: typeof retryAfter === "number" && retryAfter > 0 ? retryAfter : 1000 };
43
+ }
44
+ /** Check and wait until it's allowed, then run fn */
45
+ async run(target, fn, signal) {
46
+ await this.wait(target, signal);
47
+ return fn();
48
+ }
49
+ /** Check until it's allowed. That last check counts as the request, so make it straight after */
50
+ async wait(target, signal) {
51
+ for (;;) {
52
+ signal?.throwIfAborted();
53
+ const { allowed, retryAfter } = await this.check(target);
54
+ if (allowed)
55
+ return;
56
+ // node's own AbortError otherwise, rather than what the signal was aborted with
57
+ await sleep(retryAfter, undefined, { signal }).catch((err) => {
58
+ throw signal?.aborted ? signal.reason : err;
59
+ });
60
+ }
61
+ }
62
+ }
63
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9saWIvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLFVBQVUsSUFBSSxLQUFLLEVBQUUsTUFBTSxzQkFBc0IsQ0FBQztBQStCM0QsTUFBTSxPQUFPLGdCQUFpQixTQUFRLEtBQUs7SUFDOUIsSUFBSSxHQUFHLGtCQUFrQixDQUFDO0NBQ3RDO0FBRUQsTUFBTSxNQUFNLEdBQUcsQ0FBQyxNQUFjLEVBQVUsRUFBRSxDQUFDLE1BQU0sWUFBWSxHQUFHLENBQUMsQ0FBQyxDQUFDLE1BQU0sQ0FBQyxRQUFRLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FB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DQUFDLENBQUMsR0FBRyxDQUFDO1lBQ2hELENBQUMsQ0FBQyxDQUFDO1FBQ1AsQ0FBQztJQUNMLENBQUM7Q0FDSiJ9
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@yiffy/ratelimiter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "A client for envoyproxy/ratelimit, to check whether a request can go out yet",
5
+ "license": "MIT",
6
+ "author": "Donovan_DMC <hewwo@yiff.rocks>",
7
+ "type": "module",
8
+ "main": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/DonovanDMC/RateLimiter"
13
+ },
14
+ "homepage": "https://github.com/DonovanDMC/RateLimiter#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/DonovanDMC/RateLimiter/issues"
17
+ },
18
+ "devDependencies": {
19
+ "@eslint/js": "^9.39.5",
20
+ "@stylistic/eslint-plugin": "^5.10.0",
21
+ "@types/node": "^24.19.2",
22
+ "@uwu-codes/eslint-config": "^2.0.11",
23
+ "eslint": "^9.39.4",
24
+ "eslint-plugin-import": "^2.32.0",
25
+ "eslint-plugin-unicorn": "^59.0.1",
26
+ "eslint-plugin-unused-imports": "^4.4.1",
27
+ "globals": "^16.5.0",
28
+ "jiti": "^2.6.1",
29
+ "typescript": "^6.0.3",
30
+ "typescript-eslint": "^8.73.0"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE",
36
+ "package.json",
37
+ "tsconfig.json"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public",
41
+ "provenance": true
42
+ },
43
+ "keywords": [
44
+ "ratelimit",
45
+ "envoy"
46
+ ],
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.build.json",
49
+ "lint": "eslint .",
50
+ "lint:fix": "eslint . --fix",
51
+ "test": "node --test test/**/*.test.ts"
52
+ }
6
53
  }
package/tsconfig.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "compilerOptions": {
3
+ "lib": ["ESNext"],
4
+ "module": "NodeNext",
5
+ "target": "ESNext",
6
+ "types": ["node"],
7
+ "moduleDetection": "force",
8
+ "inlineSourceMap": true,
9
+ "importHelpers": false,
10
+ "newLine": "LF",
11
+ "noFallthroughCasesInSwitch": true,
12
+ "noImplicitOverride": true,
13
+ "strict": true,
14
+ "esModuleInterop": true,
15
+ "skipLibCheck": false,
16
+ "forceConsistentCasingInFileNames": true,
17
+ "moduleResolution": "NodeNext",
18
+ "allowUnusedLabels": false,
19
+ "allowUnreachableCode": false,
20
+ "checkJs": true,
21
+ "strictPropertyInitialization": true,
22
+ "strictBindCallApply": true,
23
+ "verbatimModuleSyntax": true,
24
+ "declaration": true,
25
+ "noEmit": true,
26
+ "allowSyntheticDefaultImports": true,
27
+ "noUncheckedIndexedAccess": true,
28
+ "allowImportingTsExtensions": true
29
+ },
30
+ "include": ["eslint.config.mts", "test/**/*", "lib/**/*"],
31
+ "exclude": ["node_modules"]
32
+ }