@shivaedev/rate-limit 0.0.0 → 0.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 - 2026-11-02
4
+
5
+ ### Added
6
+
7
+ - `@shivaedev/errors`' shared `TooManyRequests` accepts optional `key` and `retryAt` fields, preserving rate-limit details across RPC while still accepting message-only failures.
8
+
9
+ ### Breaking
10
+
11
+ - `@shivaedev/rate-limit` now fails with the shared `TooManyRequests`. Replace imports from `@shivaedev/rate-limit/TooManyRequests.ts` with `@shivaedev/errors/taxonomy.ts` and add `@shivaedev/errors` as a dependency. Use that shared schema in contract rejections and custom stores. Its `key` and `retryAt` fields are optional because other callers can create message-only failures; check for their presence before using them. The limiter continues to supply both fields. The old module is removed without an alias.
12
+
13
+ ## 0.1.0 - 2026-11-01
14
+
15
+ ### Added
16
+
17
+ - Admit per-key budgets through `@shivaedev/rate-limit`, with an Effect-clock memory store, a PostgreSQL adapter, and typed `TooManyRequests` carrying a retry time.
18
+ - Include rate limiting in Platform and demonstrate a per-user note creation budget in generated applications.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ShivaeDev
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,53 @@
1
1
  # @shivaedev/rate-limit
2
2
 
3
- Placeholder. The package is published from https://github.com/ShivaeDev/platform.
3
+ Give each user or operation a budget without writing another counter. One Effect admits a call or returns a typed `TooManyRequests` with the time it can be tried again, using a memory store or PostgreSQL.
4
+
5
+ ## One budget at the write boundary
6
+
7
+ Keep the policy next to the action it protects:
8
+
9
+ ```ts
10
+ import { rateLimit } from "@shivaedev/rate-limit/rateLimit.ts";
11
+
12
+ const admitNote = rateLimit({ key: "notes:alice", per: 10, window: "1 minute" });
13
+ ```
14
+
15
+ The caller chooses a key and budget. The store handles admission, including competing PostgreSQL callers on separate pools.
16
+
17
+ ## Using it
18
+
19
+ ### Choose a store once
20
+
21
+ A window starts on the first admitted call for a key. Up to `per` calls are admitted before its expiry; subsequent calls fail without increasing the count or extending the window. At expiry the next call starts a fresh window. Use one stable policy per key and include the operation and user in the key to keep their budgets separate.
22
+
23
+ Provide the memory layer for a single process:
24
+
25
+ ```ts
26
+ import { Effect } from "effect";
27
+ import { memoryStore } from "@shivaedev/rate-limit/memoryStore.ts";
28
+ import { rateLimit } from "@shivaedev/rate-limit/rateLimit.ts";
29
+
30
+ const admitted = rateLimit({ key: "notes:alice", per: 10, window: "1 minute" }).pipe(Effect.provide(memoryStore));
31
+ ```
32
+
33
+ Share the layer across requests. Each layer build owns its counters; rebuilding it for every request resets the budget. Memory uses Effect's clock and removes expired entries on subsequent calls. It counts attempts admitted by the limiter, even if the following application write fails.
34
+
35
+ For a shared PostgreSQL budget, install the optional `@shivaedev/sql` peer, include `postgresMigration` from `@shivaedev/rate-limit/adapters/postgresMigration.ts` in the application's numbered migration loader, and provide `postgresStore` from `@shivaedev/rate-limit/adapters/postgresStore.ts`. The layer requires native `SqlClient` and `Reactivity`, supplied by the SQL package's PostgreSQL layer. It uses database time after taking a per-key transaction advisory lock, so independent processes share the same window. It runs through `transact`; call it before the application's write transaction, since admission commits independently. SQL failures become typed `StoreError` values with their original cause.
36
+
37
+ The migration creates `rate_limit_windows`. PostgreSQL retains one row per key; an application with unbounded key churn should delete expired rows as part of its own retention policy. The adapter disables SQL name transforms for its owned table.
38
+
39
+ ### Handle a refusal
40
+
41
+ `rateLimit({ key, per, window })` reads `Store` from the environment and returns `void`. `per` must be a positive safe integer and `window` a finite positive Effect duration; invalid policies die with `RangeError`.
42
+
43
+ `TooManyRequests`, from `@shivaedev/errors/taxonomy.ts`, is an Effect Schema tagged error with `message` and optional `key` and `retryAt` fields. Both built-in stores supply `key` and `retryAt` on every refusal. The retry time is Unix epoch milliseconds. Declare this schema in a contract's rejections to preserve it across RPC. Applications choose the message shown to the user and whether to retry. Refusals are immediate; the limiter does not sleep or queue callers.
44
+
45
+ A custom store implements `Store.consume` from `@shivaedev/rate-limit/Store.ts`, atomically consuming a `WindowRequest` or failing with `TooManyRequests` or `StoreError`. A store owns its clock and consistency boundary.
46
+
47
+ ### Install
48
+
49
+ ```sh
50
+ pnpm add @shivaedev/rate-limit @shivaedev/errors effect
51
+ ```
52
+
53
+ For PostgreSQL, also install `@shivaedev/sql` and its PostgreSQL driver peer. Applications depending on `@shivaedev/platform` reach the limiter through the framework hoist.
@@ -0,0 +1,21 @@
1
+ import { Context, type Effect } from "effect";
2
+ import type { TooManyRequests } from "@shivaedev/errors/taxonomy.ts";
3
+ declare const StoreError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
4
+ readonly _tag: "RateLimitStoreError";
5
+ } & Readonly<A>;
6
+ export declare class StoreError extends StoreError_base<{
7
+ readonly cause: unknown;
8
+ }> {
9
+ }
10
+ export interface WindowRequest {
11
+ readonly key: string;
12
+ readonly per: number;
13
+ readonly windowMillis: number;
14
+ }
15
+ declare const Store_base: Context.ServiceClass<Store, "@shivaedev/rate-limit/Store", {
16
+ readonly consume: (request: WindowRequest) => Effect.Effect<void, TooManyRequests | StoreError>;
17
+ }>;
18
+ export declare class Store extends Store_base {
19
+ }
20
+ export {};
21
+ //# sourceMappingURL=Store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Store.d.ts","sourceRoot":"","sources":["../src/Store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAQ,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AACpD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;;;;AAErE,qBAAa,UAAW,SAAQ,gBAAwC;IAAE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;CAAG;AAEvG,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC9B;;sBAKmB,CAAC,OAAO,EAAE,aAAa,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,eAAe,GAAG,UAAU,CAAC;;AAHjG,qBAAa,KAAM,SAAQ,UAKO;CAAG"}
package/dist/Store.js ADDED
@@ -0,0 +1,6 @@
1
+ import { Context, Data } from "effect";
2
+ export class StoreError extends Data.TaggedError("RateLimitStoreError") {
3
+ }
4
+ export class Store extends Context.Service()("@shivaedev/rate-limit/Store") {
5
+ }
6
+ //# sourceMappingURL=Store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Store.js","sourceRoot":"","sources":["../src/Store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAe,MAAM,QAAQ,CAAC;AAGpD,MAAM,OAAO,UAAW,SAAQ,IAAI,CAAC,WAAW,CAAC,qBAAqB,CAA8B;CAAG;AAQvG,MAAM,OAAO,KAAM,SAAQ,OAAO,CAAC,OAAO,EAKvC,CAAC,6BAA6B,CAAC;CAAG"}
@@ -0,0 +1,4 @@
1
+ import { Effect } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ export declare const postgresMigration: Effect.Effect<void, import("effect/sql/SqlError").SqlError, SqlClient.SqlClient>;
4
+ //# sourceMappingURL=postgresMigration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgresMigration.d.ts","sourceRoot":"","sources":["../../src/adapters/postgresMigration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,eAAO,MAAM,iBAAiB,kFAO5B,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { Effect } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ export const postgresMigration = Effect.gen(function* () {
4
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
5
+ yield* sql `create table rate_limit_windows (
6
+ key text primary key,
7
+ count bigint not null,
8
+ expires_at double precision not null
9
+ )`;
10
+ });
11
+ //# sourceMappingURL=postgresMigration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgresMigration.js","sourceRoot":"","sources":["../../src/adapters/postgresMigration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;IACpD,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,iBAAiB,EAAE,CAAC;IAC7D,KAAK,CAAC,CAAC,GAAG,CAAA;;;;GAIR,CAAC;AACJ,CAAC,CAAC,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { Layer } from "effect";
2
+ import * as Reactivity from "effect/reactivity/Reactivity";
3
+ import { SqlClient } from "effect/sql";
4
+ import { Store } from "#Store.ts";
5
+ export declare const postgresStore: Layer.Layer<Store, never, Reactivity.Reactivity | SqlClient.SqlClient>;
6
+ //# sourceMappingURL=postgresStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgresStore.d.ts","sourceRoot":"","sources":["../../src/adapters/postgresStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,KAAK,UAAU,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAIvC,OAAO,EAAE,KAAK,EAAkC,MAAM,WAAW,CAAC;AAElE,eAAO,MAAM,aAAa,wEAmCzB,CAAC"}
@@ -0,0 +1,37 @@
1
+ import { Effect, Layer } from "effect";
2
+ import * as Reactivity from "effect/reactivity/Reactivity";
3
+ import { SqlClient } from "effect/sql";
4
+ import { TooManyRequests } from "@shivaedev/errors/taxonomy.ts";
5
+ import { advisoryXactLock } from "@shivaedev/sql/advisoryXactLock.ts";
6
+ import { transact } from "@shivaedev/sql/transact.ts";
7
+ import { Store, StoreError } from "#Store.ts";
8
+ export const postgresStore = Layer.effect(Store)(Effect.gen(function* () {
9
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
10
+ const reactivity = yield* Reactivity.Reactivity;
11
+ return {
12
+ consume: ({ key, per, windowMillis }) => Effect.gen(function* () {
13
+ yield* advisoryXactLock(`@shivaedev/rate-limit:${key}`).pipe(Effect.catchTag("AdvisoryLockOutsideTransaction", Effect.die));
14
+ const [clock] = yield* sql `select extract(epoch from clock_timestamp())::double precision * 1000 as now`;
15
+ if (clock === undefined) {
16
+ return yield* Effect.die(new Error("PostgreSQL returned no clock"));
17
+ }
18
+ const now = clock.now;
19
+ const rows = yield* sql `insert into rate_limit_windows (key, count, expires_at)
20
+ values (${key}, 1, ${now + windowMillis})
21
+ on conflict (key) do update set
22
+ count = case when rate_limit_windows.expires_at <= ${now} then 1 else rate_limit_windows.count + 1 end,
23
+ expires_at = case when rate_limit_windows.expires_at <= ${now} then ${now + windowMillis} else rate_limit_windows.expires_at end
24
+ where rate_limit_windows.expires_at <= ${now} or rate_limit_windows.count < ${per}
25
+ returning expires_at as "expiresAt"`;
26
+ if (rows.length > 0) {
27
+ return;
28
+ }
29
+ const [entry] = yield* sql `select expires_at as "expiresAt" from rate_limit_windows where key = ${key}`;
30
+ if (entry === undefined) {
31
+ return yield* Effect.die(new Error("Rate limit window disappeared while locked"));
32
+ }
33
+ return yield* new TooManyRequests({ key, message: "Rate limit exceeded", retryAt: entry.expiresAt });
34
+ }).pipe(transact({ onSqlError: (cause) => new StoreError({ cause }) }), Effect.provideService(SqlClient.SqlClient, sql), Effect.provideService(Reactivity.Reactivity, reactivity)),
35
+ };
36
+ }));
37
+ //# sourceMappingURL=postgresStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgresStore.js","sourceRoot":"","sources":["../../src/adapters/postgresStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,KAAK,UAAU,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,UAAU,EAAsB,MAAM,WAAW,CAAC;AAElE,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAC/C,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;IACnB,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,iBAAiB,EAAE,CAAC;IAC7D,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC;IAChD,OAAO;QACN,OAAO,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,YAAY,EAAiB,EAAE,EAAE,CACtD,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;YACnB,KAAK,CAAC,CAAC,gBAAgB,CAAC,yBAAyB,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,gCAAgC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;YAC5H,MAAM,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAiB,8EAA8E,CAAC;YAC1H,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACzB,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC,CAAC;YACrE,CAAC;YACD,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;YACtB,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,GAAG,CAAuB;cACrC,GAAG,QAAQ,GAAG,GAAG,YAAY;;0DAEe,GAAG;+DACE,GAAG,SAAS,GAAG,GAAG,YAAY;6CAChD,GAAG,kCAAkC,GAAG;wCAC7C,CAAC;YACpC,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACrB,OAAO;YACR,CAAC;YACD,MAAM,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAuB,wEAAwE,GAAG,EAAE,CAAC;YAC/H,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACzB,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC,CAAC;YACnF,CAAC;YACD,OAAO,KAAK,CAAC,CAAC,IAAI,eAAe,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,qBAAqB,EAAE,OAAO,EAAE,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC;QACtG,CAAC,CAAC,CAAC,IAAI,CACN,QAAQ,CAAC,EAAE,UAAU,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAC9D,MAAM,CAAC,cAAc,CAAC,SAAS,CAAC,SAAS,EAAE,GAAG,CAAC,EAC/C,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,UAAU,EAAE,UAAU,CAAC,CACxD;KACF,CAAC;AACH,CAAC,CAAC,CACF,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { Layer } from "effect";
2
+ import { Store } from "#Store.ts";
3
+ export declare const memoryStore: Layer.Layer<Store, never, never>;
4
+ //# sourceMappingURL=memoryStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memoryStore.d.ts","sourceRoot":"","sources":["../src/memoryStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,EAAE,KAAK,EAAsB,MAAM,WAAW,CAAC;AAOtD,eAAO,MAAM,WAAW,kCAuBvB,CAAC"}
@@ -0,0 +1,26 @@
1
+ import { Clock, Effect, Layer } from "effect";
2
+ import { TooManyRequests } from "@shivaedev/errors/taxonomy.ts";
3
+ import { Store } from "#Store.ts";
4
+ export const memoryStore = Layer.effect(Store)(Effect.sync(() => {
5
+ const windows = new Map();
6
+ return {
7
+ consume: Effect.fn("MemoryStore.consume")(function* ({ key, per, windowMillis }) {
8
+ const now = yield* Clock.currentTimeMillis;
9
+ return yield* Effect.suspend(() => {
10
+ for (const [name, entry] of windows) {
11
+ if (entry.expiresAt <= now) {
12
+ windows.delete(name);
13
+ }
14
+ }
15
+ const entry = windows.get(key) ?? { count: 0, expiresAt: now + windowMillis };
16
+ if (entry.count >= per) {
17
+ return Effect.fail(new TooManyRequests({ key, message: "Rate limit exceeded", retryAt: entry.expiresAt }));
18
+ }
19
+ entry.count += 1;
20
+ windows.set(key, entry);
21
+ return Effect.void;
22
+ });
23
+ }),
24
+ };
25
+ }));
26
+ //# sourceMappingURL=memoryStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memoryStore.js","sourceRoot":"","sources":["../src/memoryStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,KAAK,EAAsB,MAAM,WAAW,CAAC;AAOtD,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAC7C,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE;IAChB,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC1C,OAAO;QACN,OAAO,EAAE,MAAM,CAAC,EAAE,CAAC,qBAAqB,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,YAAY,EAAiB;YAC7F,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,iBAAiB,CAAC;YAC3C,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE;gBACjC,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,OAAO,EAAE,CAAC;oBACrC,IAAI,KAAK,CAAC,SAAS,IAAI,GAAG,EAAE,CAAC;wBAC5B,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;oBACtB,CAAC;gBACF,CAAC;gBACD,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,SAAS,EAAE,GAAG,GAAG,YAAY,EAAE,CAAC;gBAC9E,IAAI,KAAK,CAAC,KAAK,IAAI,GAAG,EAAE,CAAC;oBACxB,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,eAAe,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,qBAAqB,EAAE,OAAO,EAAE,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;gBAC5G,CAAC;gBACD,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC;gBACjB,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;gBACxB,OAAO,MAAM,CAAC,IAAI,CAAC;YACpB,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC;KACF,CAAC;AACH,CAAC,CAAC,CACF,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { Duration, Effect } from "effect";
2
+ import { Store } from "#Store.ts";
3
+ export interface RateLimitOptions {
4
+ readonly key: string;
5
+ readonly per: number;
6
+ readonly window: Duration.Input;
7
+ }
8
+ export declare const rateLimit: (args_0: RateLimitOptions) => Effect.Effect<undefined, import("#Store.ts").StoreError | import("@shivaedev/errors/taxonomy.ts").TooManyRequests, Store>;
9
+ //# sourceMappingURL=rateLimit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rateLimit.d.ts","sourceRoot":"","sources":["../src/rateLimit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAElC,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC;CAChC;AAED,eAAO,MAAM,SAAS,yJAOpB,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { Duration, Effect } from "effect";
2
+ import { Store } from "#Store.ts";
3
+ export const rateLimit = Effect.fn("RateLimit.rateLimit")(function* ({ key, per, window }) {
4
+ const windowMillis = Duration.toMillis(Duration.fromInputUnsafe(window));
5
+ if (!Number.isSafeInteger(per) || per < 1 || !Number.isFinite(windowMillis) || windowMillis <= 0) {
6
+ return yield* Effect.die(new RangeError("Rate limits require a positive integer per and a finite positive window"));
7
+ }
8
+ const store = yield* Store;
9
+ yield* store.consume({ key, per, windowMillis });
10
+ });
11
+ //# sourceMappingURL=rateLimit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rateLimit.js","sourceRoot":"","sources":["../src/rateLimit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAQlC,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,EAAE,CAAC,qBAAqB,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,EAAoB;IAC1G,MAAM,YAAY,GAAG,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC;IACzE,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,YAAY,IAAI,CAAC,EAAE,CAAC;QAClG,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,yEAAyE,CAAC,CAAC,CAAC;IACrH,CAAC;IACD,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC;IAC3B,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,YAAY,EAAE,CAAC,CAAC;AAClD,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,11 +1,82 @@
1
1
  {
2
2
  "name": "@shivaedev/rate-limit",
3
- "version": "0.0.0",
4
- "description": "Placeholder for the ShivaeDev rate-limit package.",
5
- "license": "MIT",
3
+ "version": "0.2.0",
4
+ "description": "Per-key rate limits with memory and PostgreSQL stores for Effect applications",
5
+ "keywords": [
6
+ "effect"
7
+ ],
8
+ "homepage": "https://github.com/ShivaeDev/platform/tree/main/packages/rate-limit#readme",
9
+ "bugs": {
10
+ "url": "https://github.com/ShivaeDev/platform/issues"
11
+ },
6
12
  "repository": {
7
13
  "type": "git",
8
14
  "url": "git+https://github.com/ShivaeDev/platform.git",
9
15
  "directory": "packages/rate-limit"
16
+ },
17
+ "license": "MIT",
18
+ "sideEffects": false,
19
+ "type": "module",
20
+ "imports": {
21
+ "#test/*": "./src/test-support/*",
22
+ "#*.ts": {
23
+ "source": "./src/*.ts",
24
+ "types": "./dist/*.d.ts",
25
+ "default": "./dist/*.js"
26
+ }
27
+ },
28
+ "exports": {
29
+ "./*.ts": {
30
+ "source": "./src/*.ts",
31
+ "types": "./dist/*.d.ts",
32
+ "default": "./dist/*.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "src",
39
+ "!src/**/*.test.ts",
40
+ "!src/**/*.test.tsx",
41
+ "!src/**/*.spec.ts",
42
+ "!src/**/*.spec.tsx",
43
+ "!src/**/test-support",
44
+ "CHANGELOG.md",
45
+ "README.md"
46
+ ],
47
+ "dependencies": {
48
+ "@shivaedev/errors": "0.5.0"
49
+ },
50
+ "devDependencies": {
51
+ "@shivaedev/quality": "0.55.0",
52
+ "@shivaedev/sql": "0.32.0",
53
+ "@shivaedev/test-sql": "0.16.1",
54
+ "@shivaedev/test-story": "0.33.0",
55
+ "@types/node": "24.19.2",
56
+ "effect": "4.0.6",
57
+ "typescript": "7.0.2",
58
+ "vitest": "5.0.5"
59
+ },
60
+ "peerDependencies": {
61
+ "@shivaedev/sql": "0.32.0",
62
+ "effect": "4.0.6"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "@shivaedev/sql": {
66
+ "optional": true
67
+ }
68
+ },
69
+ "engines": {
70
+ "node": ">=24"
71
+ },
72
+ "publishConfig": {
73
+ "access": "public",
74
+ "provenance": true
75
+ },
76
+ "scripts": {
77
+ "build": "node --eval \"import('node:fs').then(({ rmSync }) => rmSync('dist', { force: true, recursive: true }))\" && tsc --project tsconfig.build.json",
78
+ "ready": "pnpm typecheck && pnpm test && pnpm build",
79
+ "test": "vitest run",
80
+ "typecheck": "tsc --noEmit"
10
81
  }
11
82
  }
package/src/Store.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { Context, Data, type Effect } from "effect";
2
+ import type { TooManyRequests } from "@shivaedev/errors/taxonomy.ts";
3
+
4
+ export class StoreError extends Data.TaggedError("RateLimitStoreError")<{ readonly cause: unknown }> {}
5
+
6
+ export interface WindowRequest {
7
+ readonly key: string;
8
+ readonly per: number;
9
+ readonly windowMillis: number;
10
+ }
11
+
12
+ export class Store extends Context.Service<
13
+ Store,
14
+ {
15
+ readonly consume: (request: WindowRequest) => Effect.Effect<void, TooManyRequests | StoreError>;
16
+ }
17
+ >()("@shivaedev/rate-limit/Store") {}
@@ -0,0 +1,11 @@
1
+ import { Effect } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+
4
+ export const postgresMigration = Effect.gen(function* () {
5
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
6
+ yield* sql`create table rate_limit_windows (
7
+ key text primary key,
8
+ count bigint not null,
9
+ expires_at double precision not null
10
+ )`;
11
+ });
@@ -0,0 +1,44 @@
1
+ import { Effect, Layer } from "effect";
2
+ import * as Reactivity from "effect/reactivity/Reactivity";
3
+ import { SqlClient } from "effect/sql";
4
+ import { TooManyRequests } from "@shivaedev/errors/taxonomy.ts";
5
+ import { advisoryXactLock } from "@shivaedev/sql/advisoryXactLock.ts";
6
+ import { transact } from "@shivaedev/sql/transact.ts";
7
+ import { Store, StoreError, type WindowRequest } from "#Store.ts";
8
+
9
+ export const postgresStore = Layer.effect(Store)(
10
+ Effect.gen(function* () {
11
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
12
+ const reactivity = yield* Reactivity.Reactivity;
13
+ return {
14
+ consume: ({ key, per, windowMillis }: WindowRequest) =>
15
+ Effect.gen(function* () {
16
+ yield* advisoryXactLock(`@shivaedev/rate-limit:${key}`).pipe(Effect.catchTag("AdvisoryLockOutsideTransaction", Effect.die));
17
+ const [clock] = yield* sql<{ now: number }>`select extract(epoch from clock_timestamp())::double precision * 1000 as now`;
18
+ if (clock === undefined) {
19
+ return yield* Effect.die(new Error("PostgreSQL returned no clock"));
20
+ }
21
+ const now = clock.now;
22
+ const rows = yield* sql<{ expiresAt: number }>`insert into rate_limit_windows (key, count, expires_at)
23
+ values (${key}, 1, ${now + windowMillis})
24
+ on conflict (key) do update set
25
+ count = case when rate_limit_windows.expires_at <= ${now} then 1 else rate_limit_windows.count + 1 end,
26
+ expires_at = case when rate_limit_windows.expires_at <= ${now} then ${now + windowMillis} else rate_limit_windows.expires_at end
27
+ where rate_limit_windows.expires_at <= ${now} or rate_limit_windows.count < ${per}
28
+ returning expires_at as "expiresAt"`;
29
+ if (rows.length > 0) {
30
+ return;
31
+ }
32
+ const [entry] = yield* sql<{ expiresAt: number }>`select expires_at as "expiresAt" from rate_limit_windows where key = ${key}`;
33
+ if (entry === undefined) {
34
+ return yield* Effect.die(new Error("Rate limit window disappeared while locked"));
35
+ }
36
+ return yield* new TooManyRequests({ key, message: "Rate limit exceeded", retryAt: entry.expiresAt });
37
+ }).pipe(
38
+ transact({ onSqlError: (cause) => new StoreError({ cause }) }),
39
+ Effect.provideService(SqlClient.SqlClient, sql),
40
+ Effect.provideService(Reactivity.Reactivity, reactivity),
41
+ ),
42
+ };
43
+ }),
44
+ );
@@ -0,0 +1,33 @@
1
+ import { Clock, Effect, Layer } from "effect";
2
+ import { TooManyRequests } from "@shivaedev/errors/taxonomy.ts";
3
+ import { Store, type WindowRequest } from "#Store.ts";
4
+
5
+ interface Window {
6
+ count: number;
7
+ readonly expiresAt: number;
8
+ }
9
+
10
+ export const memoryStore = Layer.effect(Store)(
11
+ Effect.sync(() => {
12
+ const windows = new Map<string, Window>();
13
+ return {
14
+ consume: Effect.fn("MemoryStore.consume")(function* ({ key, per, windowMillis }: WindowRequest) {
15
+ const now = yield* Clock.currentTimeMillis;
16
+ return yield* Effect.suspend(() => {
17
+ for (const [name, entry] of windows) {
18
+ if (entry.expiresAt <= now) {
19
+ windows.delete(name);
20
+ }
21
+ }
22
+ const entry = windows.get(key) ?? { count: 0, expiresAt: now + windowMillis };
23
+ if (entry.count >= per) {
24
+ return Effect.fail(new TooManyRequests({ key, message: "Rate limit exceeded", retryAt: entry.expiresAt }));
25
+ }
26
+ entry.count += 1;
27
+ windows.set(key, entry);
28
+ return Effect.void;
29
+ });
30
+ }),
31
+ };
32
+ }),
33
+ );
@@ -0,0 +1,17 @@
1
+ import { Duration, Effect } from "effect";
2
+ import { Store } from "#Store.ts";
3
+
4
+ export interface RateLimitOptions {
5
+ readonly key: string;
6
+ readonly per: number;
7
+ readonly window: Duration.Input;
8
+ }
9
+
10
+ export const rateLimit = Effect.fn("RateLimit.rateLimit")(function* ({ key, per, window }: RateLimitOptions) {
11
+ const windowMillis = Duration.toMillis(Duration.fromInputUnsafe(window));
12
+ if (!Number.isSafeInteger(per) || per < 1 || !Number.isFinite(windowMillis) || windowMillis <= 0) {
13
+ return yield* Effect.die(new RangeError("Rate limits require a positive integer per and a finite positive window"));
14
+ }
15
+ const store = yield* Store;
16
+ yield* store.consume({ key, per, windowMillis });
17
+ });