@lunora/ratelimit 1.0.0-alpha.19 → 1.0.0-alpha.191
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/README.md +49 -18
- package/dist/index.d.mts +156 -79
- package/dist/index.d.ts +156 -79
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/RateLimitError-9Y5OLxpl.mjs +1 -0
- package/dist/packem_shared/RateLimiter-C67wj24r.mjs +1 -0
- package/dist/packem_shared/availableAt-DCUEox4O.mjs +1 -0
- package/dist/packem_shared/createDbStore-DdoYxOaZ.mjs +1 -0
- package/dist/packem_shared/dbRateLimit-D8xJ03b-.mjs +1 -0
- package/dist/packem_shared/rateLimit-CWZur6XE.mjs +1 -0
- package/dist/packem_shared/ratelimitPlugin-CFnDs9rj.mjs +1 -0
- package/dist/packem_shared/tokenBudget-CPm8DEVi.mjs +1 -0
- package/package.json +7 -3
- package/dist/packem_shared/RateLimitError-xJ2Iv-i7.mjs +0 -1
- package/dist/packem_shared/RateLimiter-CitqoGTI.mjs +0 -1
- package/dist/packem_shared/availableAt-BMlAt2U2.mjs +0 -1
- package/dist/packem_shared/createDbStore-CwJBMxDQ.mjs +0 -1
- package/dist/packem_shared/dbRateLimit-e95-suu-.mjs +0 -1
- package/dist/packem_shared/rateLimit-DLcwK-84.mjs +0 -1
- package/dist/packem_shared/ratelimitPlugin-D1QHZF9b.mjs +0 -1
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
</a>
|
|
8
8
|
|
|
9
|
-
<h3 align="center">Rate limiting: token-bucket / fixed-window / sliding-window algorithms, deny list,
|
|
9
|
+
<h3 align="center">Rate limiting: token-bucket / fixed-window / sliding-window algorithms, deny list, pluggable stores, and procedure middleware</h3>
|
|
10
10
|
|
|
11
11
|
<!-- END_PACKAGE_OG_IMAGE_PLACEHOLDER -->
|
|
12
12
|
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
|
|
35
35
|
---
|
|
36
36
|
|
|
37
|
-
Rate limiting for Lunora: token-bucket, fixed-window, and sliding-window algorithms, a deny list,
|
|
37
|
+
Rate limiting for Lunora: token-bucket, fixed-window, and sliding-window algorithms, a deny list, pluggable stores (in-memory, SQL, or the Lunora ORM), and procedure middleware that rides the `.use()` chain.
|
|
38
38
|
|
|
39
39
|
Part of the [Lunora](https://github.com/anolilab/lunora) framework — a type-safe, real-time backend on Cloudflare Workers + Durable Objects with a Vite-first DX.
|
|
40
40
|
|
|
@@ -59,37 +59,68 @@ to a procedure's `.use(...)` chain. The procedure builders (`mutation`, …) com
|
|
|
59
59
|
from your app's generated `_generated/server` module, not from a package.
|
|
60
60
|
|
|
61
61
|
```ts
|
|
62
|
-
import {
|
|
62
|
+
import { dbRateLimit } from "@lunora/ratelimit";
|
|
63
63
|
|
|
64
64
|
import { mutation } from "./_generated/server";
|
|
65
65
|
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
66
|
+
const config = {
|
|
67
|
+
login: { kind: "fixed window", period: 60_000, rate: 5 },
|
|
68
|
+
send: { kind: "token bucket", period: 1_000, rate: 10 },
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// `dbRateLimit` builds the limiter per call, backed by a Lunora table via
|
|
72
|
+
// `ctx.db`, so the count is durable. A `RateLimiter` built with no explicit
|
|
73
|
+
// `store` falls back to `createMemoryStore` (a per-instance in-memory Map) —
|
|
74
|
+
// fine for a limit that only ever needs to hold within one Durable Object
|
|
75
|
+
// instance, but a limiter like `login` needs a durable store or it stops
|
|
76
|
+
// enforcing the configured rate the moment the DO instance is sharded,
|
|
77
|
+
// replicated, or recreated.
|
|
73
78
|
// As procedure middleware — throws a structural LunoraError (429/403) on rejection.
|
|
74
|
-
|
|
79
|
+
// `key` must resolve to a string — a resolver returning `undefined` throws
|
|
80
|
+
// rather than silently sharing one bucket across every keyless caller.
|
|
81
|
+
export const send = mutation.use(dbRateLimit(config, "send", { key: (ctx) => ctx.auth.userId ?? "anonymous" })).mutation(async ({ ctx }) => {
|
|
75
82
|
// …
|
|
76
83
|
});
|
|
77
84
|
```
|
|
78
85
|
|
|
79
|
-
Or call the limiter directly
|
|
86
|
+
Or call the limiter directly, inside a mutation/action so `ctx.db` is available.
|
|
87
|
+
A login limiter belongs in an **action**: a mutation's `ctx.db` writes ride its
|
|
88
|
+
storage transaction, so a handler that throws (a wrong password) rolls the
|
|
89
|
+
consumed unit back and every failed attempt is free. An action's writes commit
|
|
90
|
+
on their own, so the charge stays whether or not the handler throws.
|
|
80
91
|
|
|
81
92
|
```ts
|
|
82
|
-
|
|
93
|
+
import { RateLimiter, RateLimitError, createDbStore } from "@lunora/ratelimit";
|
|
94
|
+
|
|
95
|
+
import { action } from "./_generated/server";
|
|
83
96
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
97
|
+
export const login = action.action(async ({ ctx, args }) => {
|
|
98
|
+
const limiter = new RateLimiter({ config, store: createDbStore({ db: ctx.db }) });
|
|
99
|
+
const status = await limiter.limit("login", { key: args.email });
|
|
100
|
+
|
|
101
|
+
if (!status.ok) {
|
|
102
|
+
// Stop here — `limit` returns a failing status by default rather than
|
|
103
|
+
// throwing, so falling through authenticates the rejected attempt.
|
|
104
|
+
// status.retryAfter is milliseconds until the request would succeed.
|
|
105
|
+
// status.reason is "rate" or "deny".
|
|
106
|
+
throw new RateLimitError(status);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
await authenticate(args);
|
|
110
|
+
});
|
|
88
111
|
```
|
|
89
112
|
|
|
90
113
|
For durable per-DO state inside a procedure, back the limiter with a Lunora
|
|
91
114
|
table via `dbRateLimit(config, name, options)`, or supply a `store`
|
|
92
|
-
(`
|
|
115
|
+
(`createSqlStore` / `createDbStore`). `createMemoryStore` stays the default —
|
|
116
|
+
correct inside a single Durable Object — but constructing a `RateLimiter` with
|
|
117
|
+
no explicit `store` now warns once so that choice is visible instead of
|
|
118
|
+
silent.
|
|
119
|
+
|
|
120
|
+
A key that is an IPv6 address (for example `ctx.ip`) is bucketed by its /64
|
|
121
|
+
prefix, and an IPv4-mapped address by the IPv4 address it wraps. An IPv6 client
|
|
122
|
+
usually controls a whole /64, so a per-address bucket would let it pick a fresh
|
|
123
|
+
address for every request. A deny-list IPv6 entry bans its /64.
|
|
93
124
|
|
|
94
125
|
> This README covers the basics. For the full API, options, and guides, see the **[documentation](https://lunora.sh/docs)**.
|
|
95
126
|
|
package/dist/index.d.mts
CHANGED
|
@@ -19,18 +19,6 @@ interface RateLimitConfig {
|
|
|
19
19
|
period: number;
|
|
20
20
|
/** Tokens granted per `period`. */
|
|
21
21
|
rate: number;
|
|
22
|
-
/**
|
|
23
|
-
* Split a hot limit across N independent sub-buckets to avoid a single
|
|
24
|
-
* contended key/Durable Object. Each shard enforces `rate / shards` (and
|
|
25
|
-
* `capacity / shards`); a request is routed to a shard via a deterministic
|
|
26
|
-
* hash of `(name, key)`, so the same key always lands on the same shard and
|
|
27
|
-
* a single key's effective throughput is exactly `rate / shards`. Aggregate
|
|
28
|
-
* throughput across many distinct keys approaches `rate` as keys spread
|
|
29
|
-
* uniformly across shards. Reserve it for high-volume limits where
|
|
30
|
-
* contention bites; leave unset (one bucket) otherwise. Must be a positive
|
|
31
|
-
* integer — `1` is equivalent to unset.
|
|
32
|
-
*/
|
|
33
|
-
shards?: number;
|
|
34
22
|
/**
|
|
35
23
|
* Phase offset in epoch milliseconds for windowed algorithms — windows
|
|
36
24
|
* align to `start + n * period`. Ignored by token buckets. Defaults to `0`.
|
|
@@ -92,6 +80,34 @@ interface RateLimitStore {
|
|
|
92
80
|
delete: (storageKey: string) => Promise<void> | void;
|
|
93
81
|
get: (storageKey: string) => Promise<RateLimitValue | undefined> | RateLimitValue | undefined;
|
|
94
82
|
set: (storageKey: string, value: RateLimitValue) => Promise<void> | void;
|
|
83
|
+
/**
|
|
84
|
+
* Optional conditional write: persist `value` only while the stored value is
|
|
85
|
+
* still `prior` (what `get` returned for this consume, `undefined` for no
|
|
86
|
+
* row), and resolve `false` when it no longer is. When present the limiter
|
|
87
|
+
* writes through it instead of `set`, and a `false` makes it read and decide
|
|
88
|
+
* again rather than admit off a stale read.
|
|
89
|
+
*
|
|
90
|
+
* A store whose `get` and write cannot be interleaved by another consume
|
|
91
|
+
* (memory, SQL: synchronous) needs none. One whose calls can be
|
|
92
|
+
* (`createDbStore`: every call is awaited I/O) must have it.
|
|
93
|
+
*/
|
|
94
|
+
setIf?: (storageKey: string, value: RateLimitValue, prior: RateLimitValue | undefined) => Promise<boolean>;
|
|
95
|
+
/**
|
|
96
|
+
* Optional eviction hint, called by the limiter after each successful write.
|
|
97
|
+
* Remove up to `limit` entries whose `ts` is at or before `olderThanTs`, except
|
|
98
|
+
* entries with a negative `value`: a reserved debt is kept, whatever its age.
|
|
99
|
+
* The memory store examines up to `limit` entries from its oldest end; the
|
|
100
|
+
* durable stores delete at most `limit` matching rows. A returned promise is
|
|
101
|
+
* awaited, so a store whose sweep is I/O (`createDbStore`) finishes it before the
|
|
102
|
+
* consume returns. The durable stores implement it so a table stays bounded
|
|
103
|
+
* without a scheduled job; see `createSqlStore` and `createDbStore` for the
|
|
104
|
+
* table shape.
|
|
105
|
+
*
|
|
106
|
+
* `owns` says whether a storage key belongs to the limiter asking for the
|
|
107
|
+
* sweep. A store shared with another limiter must leave the other limiter's
|
|
108
|
+
* keys alone: its horizon is not this one's. Absent means every key is owned.
|
|
109
|
+
*/
|
|
110
|
+
sweep?: (olderThanTs: number, limit: number, owns?: (storageKey: string) => boolean) => Promise<void> | void;
|
|
95
111
|
}
|
|
96
112
|
/** Inputs to {@link evaluate}. */
|
|
97
113
|
interface EvaluateOptions {
|
|
@@ -135,11 +151,15 @@ interface RateLimiterOptions<Names extends string> {
|
|
|
135
151
|
denyList?: Iterable<string>;
|
|
136
152
|
/**
|
|
137
153
|
* Optional key normalizer applied to every incoming `args.key` (the
|
|
138
|
-
* deny-list check
|
|
139
|
-
*
|
|
140
|
-
* IPs/emails so equivalent inputs share a single bucket. The deny-list
|
|
154
|
+
* deny-list check and the storage key both see the normalized form). Use for case-folding, trimming, or canonicalizing
|
|
155
|
+
* emails so equivalent inputs share a single bucket. The deny-list
|
|
141
156
|
* itself is consulted as-is; normalize the deny-list entries up front to
|
|
142
157
|
* match.
|
|
158
|
+
*
|
|
159
|
+
* After it, a key that is an IPv6 address is always collapsed to its /64
|
|
160
|
+
* (`2001:db8:1:2::/64`) and an IPv4-mapped one to its IPv4 address, so a
|
|
161
|
+
* `ctx.ip`-keyed limit cannot be dodged by rotating addresses within one
|
|
162
|
+
* delegated prefix. A deny-list IPv6 entry therefore bans its whole /64.
|
|
143
163
|
*/
|
|
144
164
|
normalize?: (key: string) => string;
|
|
145
165
|
/** Clock injection for tests. Defaults to `Date.now`. */
|
|
@@ -158,7 +178,10 @@ declare class RateLimiter<Names extends string = string> {
|
|
|
158
178
|
private readonly denyList;
|
|
159
179
|
private readonly normalize;
|
|
160
180
|
private readonly now;
|
|
181
|
+
private readonly retention;
|
|
161
182
|
private readonly store;
|
|
183
|
+
/** Whether a stored key is one of this limiter's names; a sweep only evicts those. */
|
|
184
|
+
private readonly owns;
|
|
162
185
|
constructor(options: RateLimiterOptions<Names>);
|
|
163
186
|
/** Peek at whether a request would be permitted without consuming. */
|
|
164
187
|
check(name: Names, args?: Omit<RateLimitArgs, "reserve" | "throws">): Promise<RateLimitStatus>;
|
|
@@ -166,9 +189,7 @@ declare class RateLimiter<Names extends string = string> {
|
|
|
166
189
|
* Read the current config and the units admittable right now for a
|
|
167
190
|
* `(name, key)` pair. The value is projected forward to the current clock
|
|
168
191
|
* (token-bucket refill, fixed-window rollover, sliding-window decay), not
|
|
169
|
-
* the last persisted figure.
|
|
170
|
-
* shard `limit()`/`run()` would route this key to — the sibling shards are
|
|
171
|
-
* never touched by this key, so summing them would over-report.
|
|
192
|
+
* the last persisted figure.
|
|
172
193
|
*/
|
|
173
194
|
getValue(name: Names, args?: {
|
|
174
195
|
key?: string;
|
|
@@ -183,6 +204,22 @@ declare class RateLimiter<Names extends string = string> {
|
|
|
183
204
|
reset(name: Names, args?: {
|
|
184
205
|
key?: string;
|
|
185
206
|
}): Promise<void>;
|
|
207
|
+
/**
|
|
208
|
+
* Read, evaluate and write one consume. A store that reports the write lost
|
|
209
|
+
* (`setIf` resolved `false`: another consume changed the value since this one
|
|
210
|
+
* read it) gets a fresh read and a fresh decision, so the admission always
|
|
211
|
+
* rests on the value the write replaced. Bounded: each lost round means some
|
|
212
|
+
* other consume was admitted (a refusal writes nothing), and past
|
|
213
|
+
* {@link MAX_DECIDE_ATTEMPTS} the call is refused with `retryAfter: 0` rather
|
|
214
|
+
* than admitted.
|
|
215
|
+
*/
|
|
216
|
+
private decide;
|
|
217
|
+
/**
|
|
218
|
+
* Evict what this limiter's horizon has expired, after a write has landed. The
|
|
219
|
+
* write is already done, so awaiting here does not reopen the read-decide-write
|
|
220
|
+
* window. Only a promise-returning sweep (`createDbStore`) is awaited for I/O.
|
|
221
|
+
*/
|
|
222
|
+
private sweep;
|
|
186
223
|
private normalizeKey;
|
|
187
224
|
private resolve;
|
|
188
225
|
private run;
|
|
@@ -203,7 +240,15 @@ interface RateLimitMiddlewareOptions<Context> {
|
|
|
203
240
|
* — note that a failing limiter then permits every request through.
|
|
204
241
|
*/
|
|
205
242
|
failOpen?: boolean;
|
|
206
|
-
/**
|
|
243
|
+
/**
|
|
244
|
+
* Sub-key derived from `ctx` (per-user/IP). Omit for a global limit.
|
|
245
|
+
*
|
|
246
|
+
* A resolver that returns `undefined` is a config bug, not a global limit:
|
|
247
|
+
* the middleware throws `INTERNAL` rather than silently pooling every
|
|
248
|
+
* keyless caller (e.g. every anonymous user) into one shared bucket. Fold
|
|
249
|
+
* the absent case yourself — `ctx.auth.userId ?? "anonymous"` — so the
|
|
250
|
+
* shared bucket is a visible choice.
|
|
251
|
+
*/
|
|
207
252
|
key?: (context: Context) => string | undefined;
|
|
208
253
|
/** Override the error message thrown on rejection. */
|
|
209
254
|
message?: string;
|
|
@@ -212,7 +257,7 @@ interface RateLimitMiddlewareOptions<Context> {
|
|
|
212
257
|
* Procedure middleware that enforces a named rate limit before the handler
|
|
213
258
|
* runs. Attach it with `.use()`. On rejection it throws a structural
|
|
214
259
|
* `LunoraError` (`TOO_MANY_REQUESTS`/429, or `FORBIDDEN`/403 for deny-list
|
|
215
|
-
* hits) carrying `
|
|
260
|
+
* hits) carrying `data.retryAfterMs` — the runtime maps it to the
|
|
216
261
|
* matching RPC/HTTP status without any import of `@lunora/server` at runtime.
|
|
217
262
|
*
|
|
218
263
|
* **Failure policy:** if resolving or invoking the limiter throws for a genuine
|
|
@@ -231,6 +276,9 @@ declare const rateLimit: <Context>(limiter: LimiterResolver<Context>, name: stri
|
|
|
231
276
|
* In-memory store. State lives for the lifetime of the process (or, inside a
|
|
232
277
|
* Durable Object, the instance) — adequate for single-DO limits but not shared
|
|
233
278
|
* across instances. Use {@link createSqlStore} for durable per-DO state.
|
|
279
|
+
*
|
|
280
|
+
* A store may be shared by several limiters: each sweep evicts only the keys its
|
|
281
|
+
* limiter owns, by that limiter's horizon (see `RateLimitStore.sweep`).
|
|
234
282
|
*/
|
|
235
283
|
declare const createMemoryStore: () => RateLimitStore;
|
|
236
284
|
/**
|
|
@@ -247,38 +295,8 @@ interface SqlStoreOptions {
|
|
|
247
295
|
/** Table name. Created if missing. Defaults to `_lunora_rate_limits`. */
|
|
248
296
|
table?: string;
|
|
249
297
|
}
|
|
250
|
-
/**
|
|
251
|
-
* SQLite-backed store for durable, per-DO rate-limit state. Persists each
|
|
252
|
-
* `(name, key)` pair as one row so limits survive hibernation and eviction.
|
|
253
|
-
*
|
|
254
|
-
* **Atomicity:** the store does not wrap individual operations in an explicit
|
|
255
|
-
* SQL transaction. Inside a Durable Object the DO's input gate serializes
|
|
256
|
-
* every RPC call against the storage, so the limiter's read-modify-write
|
|
257
|
-
* sequence runs to completion without interleaving — this is the same
|
|
258
|
-
* guarantee the surrounding `evaluate()` step depends on. **Outside a DO**
|
|
259
|
-
* (e.g. driving `createSqlStore` from a long-lived `node:sqlite` connection in
|
|
260
|
-
* tests or a custom host) the caller is responsible for serialization; the
|
|
261
|
-
* SQL surface used here (`exec`) is not a substitute for transactional
|
|
262
|
-
* isolation across concurrent invocations.
|
|
263
|
-
*/
|
|
298
|
+
/** Sql store, with keys stored losslessly; see {@link encodeStorageKey}. */
|
|
264
299
|
declare const createSqlStore: (options: SqlStoreOptions) => RateLimitStore;
|
|
265
|
-
/**
|
|
266
|
-
* The slice of an index-range builder the store uses. Mirrors `@lunora/server`'s
|
|
267
|
-
* `IndexRangeBuilder` field-for-field so the real `ctx.db` query builder is
|
|
268
|
-
* assignable; only `eq` is exercised.
|
|
269
|
-
*/
|
|
270
|
-
interface RateLimitDatabaseIndexRange {
|
|
271
|
-
eq: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
272
|
-
gt: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
273
|
-
gte: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
274
|
-
lt: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
275
|
-
lte: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
276
|
-
}
|
|
277
|
-
/** The slice of a `ctx.db` table query the store relies on. */
|
|
278
|
-
interface RateLimitDatabaseQuery {
|
|
279
|
-
first: () => Promise<Record<string, unknown> | null>;
|
|
280
|
-
withIndex: (indexName: string, range: (q: RateLimitDatabaseIndexRange) => RateLimitDatabaseIndexRange) => RateLimitDatabaseQuery;
|
|
281
|
-
}
|
|
282
300
|
/**
|
|
283
301
|
* The READ slice — everything the store needs to answer `RateLimiter.getValue`
|
|
284
302
|
* and `check`, which the docs describe as projecting the stored value forward to
|
|
@@ -289,9 +307,16 @@ interface RateLimitDatabaseQuery {
|
|
|
289
307
|
* at all — every remaining-quota display had to cast, and a cast that appears
|
|
290
308
|
* often enough stops carrying information. The distinction was already in the
|
|
291
309
|
* methods: `getValue`/`check` read, `limit`/`reset` write.
|
|
310
|
+
*
|
|
311
|
+
* `findFirst` rather than `query(table).withIndex(...)`: a `.global()` table's
|
|
312
|
+
* reader has no `withIndex`, so the indexed builder failed every read there.
|
|
313
|
+
* `findFirst` routes to whichever backend owns the table, and an equality on the
|
|
314
|
+
* key column still uses its index.
|
|
292
315
|
*/
|
|
293
316
|
interface RateLimitDatabaseReader {
|
|
294
|
-
|
|
317
|
+
findFirst: (table: string, args?: {
|
|
318
|
+
where?: Record<string, unknown>;
|
|
319
|
+
}) => Promise<Record<string, unknown> | null>;
|
|
295
320
|
}
|
|
296
321
|
/**
|
|
297
322
|
* The slice of the Lunora ORM writer (`ctx.db` on a mutation/action) the store
|
|
@@ -300,15 +325,33 @@ interface RateLimitDatabaseReader {
|
|
|
300
325
|
* free of a runtime dependency on `@lunora/server`.
|
|
301
326
|
*/
|
|
302
327
|
interface RateLimitDatabase extends RateLimitDatabaseReader {
|
|
303
|
-
delete: <T extends string>(id: Id<T>) => Promise<void>;
|
|
304
|
-
|
|
305
|
-
|
|
328
|
+
delete: <T extends string>(table: T, id: Id<T>) => Promise<void>;
|
|
329
|
+
/**
|
|
330
|
+
* Used by `sweep` only: rows matching `where`, at most `limit`. Optional in the
|
|
331
|
+
* type because the public `DatabaseWriter` does not declare it; the framework's
|
|
332
|
+
* `ctx.db` implements it, and `sweep` throws if an adapter does not.
|
|
333
|
+
*/
|
|
334
|
+
findMany?: (table: string, args: {
|
|
335
|
+
limit?: number;
|
|
336
|
+
orderBy?: Record<string, "asc" | "desc">[];
|
|
337
|
+
where?: Record<string, unknown>;
|
|
338
|
+
}) => Promise<{
|
|
339
|
+
page: Record<string, unknown>[];
|
|
340
|
+
}>;
|
|
341
|
+
insert: <T extends string>(table: T, document: Record<string, unknown>, options?: {
|
|
342
|
+
clientId?: string;
|
|
343
|
+
}) => Promise<Id<T>>;
|
|
344
|
+
patchIf: <T extends string>(table: T, id: Id<T>, args: {
|
|
345
|
+
patch: Record<string, unknown>;
|
|
346
|
+
where: Record<string, unknown>;
|
|
347
|
+
}) => Promise<{
|
|
348
|
+
applied: boolean;
|
|
349
|
+
doc: Record<string, unknown> | null;
|
|
350
|
+
}>;
|
|
306
351
|
}
|
|
307
|
-
/** The table/column
|
|
352
|
+
/** The table/column knobs shared by the read-only and read-write stores. */
|
|
308
353
|
interface DatabaseStoreLocation {
|
|
309
|
-
/**
|
|
310
|
-
index?: string;
|
|
311
|
-
/** Column storing the opaque key. Defaults to `key`. */
|
|
354
|
+
/** Column storing the opaque key. Defaults to `key`. Index it: every consume reads by it. */
|
|
312
355
|
keyField?: string;
|
|
313
356
|
/** Table holding one row per `(name, key)` pair. Defaults to `rateLimits`. */
|
|
314
357
|
table?: string;
|
|
@@ -321,23 +364,7 @@ interface ReadOnlyDatabaseStoreOptions extends DatabaseStoreLocation {
|
|
|
321
364
|
/** The Lunora ORM reader — `ctx.db` inside a query. */
|
|
322
365
|
db: RateLimitDatabaseReader;
|
|
323
366
|
}
|
|
324
|
-
/**
|
|
325
|
-
* Store backed by a Lunora table through `ctx.db`, for durable per-DO limits
|
|
326
|
-
* inside a procedure (the procedure context exposes no raw SQL). Declare a
|
|
327
|
-
* table with the key column and its index, e.g.
|
|
328
|
-
*
|
|
329
|
-
* ```ts
|
|
330
|
-
* rateLimits: defineTable({
|
|
331
|
-
* key: v.string(),
|
|
332
|
-
* ts: v.number(),
|
|
333
|
-
* value: v.number(),
|
|
334
|
-
* prev: v.optional(v.number()),
|
|
335
|
-
* }).index("by_key", ["key"])
|
|
336
|
-
* ```
|
|
337
|
-
*
|
|
338
|
-
* Each operation is a read-then-write; inside a mutation/action that pair runs
|
|
339
|
-
* under the DO's input gate, so it is atomic against concurrent calls.
|
|
340
|
-
*/
|
|
367
|
+
/** Database store, with keys stored losslessly; see {@link encodeStorageKey}. */
|
|
341
368
|
declare const createDatabaseStore: (options: DatabaseStoreOptions) => RateLimitStore;
|
|
342
369
|
/**
|
|
343
370
|
* Read-only counterpart to {@link createDatabaseStore}, for a query context.
|
|
@@ -365,12 +392,17 @@ declare const createReadOnlyDatabaseStore: (options: ReadOnlyDatabaseStoreOption
|
|
|
365
392
|
* on the DO the procedure runs on). Every query/mutation/action ctx exposes a
|
|
366
393
|
* compatible `db`, so it slots straight into a `.use(...)` chain.
|
|
367
394
|
*
|
|
368
|
-
* Pass `options.store` to point at a non-default backing table/
|
|
369
|
-
* (defaults: table `rateLimits`,
|
|
395
|
+
* Pass `options.store` to point at a non-default backing table/key column
|
|
396
|
+
* (defaults: table `rateLimits`, key column `key`); the rest of
|
|
370
397
|
* `options` (`key`, `count`, `failOpen`, `message`) is forwarded to
|
|
371
398
|
* {@link rateLimit} unchanged. When `config` is precisely typed, `name`
|
|
372
399
|
* autocompletes to its declared limit names.
|
|
373
400
|
*
|
|
401
|
+
* On a mutation the consumed unit commits with the handler: a handler that
|
|
402
|
+
* throws rolls it back, so a failed call costs nothing. Attach it to an action
|
|
403
|
+
* (whose writes commit independently) when failed attempts must count — see
|
|
404
|
+
* {@link createDatabaseStore}.
|
|
405
|
+
*
|
|
374
406
|
* Re-exported as `dbRateLimit` from the package root.
|
|
375
407
|
*
|
|
376
408
|
* ```ts
|
|
@@ -440,5 +472,50 @@ interface RatelimitApiContext<Context> {
|
|
|
440
472
|
* `@lunora/server` a type-only dependency of `@lunora/ratelimit`.
|
|
441
473
|
*/
|
|
442
474
|
declare const ratelimitPlugin: <Context = unknown>(limiter: LimiterResolver<Context>) => Plugin<Record<never, never>, Context, Context & RatelimitApiContext<Context>>;
|
|
475
|
+
/** A budget bound to one named limit — check before the call, record after it. */
|
|
476
|
+
interface TokenBudget {
|
|
477
|
+
/**
|
|
478
|
+
* Peek at the budget before spending. `ok: false` means it is exhausted:
|
|
479
|
+
* refuse the call, and `retryAfter` says when it refills. Consumes nothing.
|
|
480
|
+
*/
|
|
481
|
+
check: (key: string) => Promise<RateLimitStatus>;
|
|
482
|
+
/**
|
|
483
|
+
* Charge the tokens a call actually used. Always call it, including when the
|
|
484
|
+
* call THREW — a failed generation that consumed input tokens still has to be
|
|
485
|
+
* paid for. `tokens` of `0` is a no-op, so a call that spent nothing costs
|
|
486
|
+
* nothing.
|
|
487
|
+
*
|
|
488
|
+
* The charge is a reservation, so it may take the bucket negative: the tokens
|
|
489
|
+
* are already spent, and refusing to record them would let a single oversized
|
|
490
|
+
* call escape the budget entirely.
|
|
491
|
+
*/
|
|
492
|
+
record: (key: string, tokens: number) => Promise<RateLimitStatus>;
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Bind a {@link TokenBudget} to one of a limiter's named limits.
|
|
496
|
+
*
|
|
497
|
+
* ```ts
|
|
498
|
+
* const budget = tokenBudget(limiter, "tokens");
|
|
499
|
+
* const allowed = await budget.check(userId);
|
|
500
|
+
*
|
|
501
|
+
* if (!allowed.ok) {
|
|
502
|
+
* throw new LunoraError("RATE_LIMITED", `token budget exhausted; retry in ${String(allowed.retryAfter)}ms`);
|
|
503
|
+
* }
|
|
504
|
+
*
|
|
505
|
+
* try {
|
|
506
|
+
* const { text, usage } = await generateText({ model: ctx.ai.model(), prompt });
|
|
507
|
+
*
|
|
508
|
+
* await budget.record(userId, usage?.totalTokens ?? 0);
|
|
509
|
+
*
|
|
510
|
+
* return text;
|
|
511
|
+
* } catch (error) {
|
|
512
|
+
* // The prompt was still sent — charge what is known, then rethrow.
|
|
513
|
+
* await budget.record(userId, estimatedInputTokens);
|
|
514
|
+
*
|
|
515
|
+
* throw error;
|
|
516
|
+
* }
|
|
517
|
+
* ```
|
|
518
|
+
*/
|
|
519
|
+
declare const tokenBudget: <Names extends string>(limiter: RateLimiter<Names>, name: Names) => TokenBudget;
|
|
443
520
|
declare const VERSION = "0.0.0";
|
|
444
|
-
export { type DatabaseStoreOptions as DbStoreOptions, type EvaluateOptions, type EvaluateResult, type LimiterResolver, type RateLimitArgs, type RateLimitConfig, type RateLimitConfigMap, type RateLimitDatabase as RateLimitDb, type
|
|
521
|
+
export { type DatabaseStoreOptions as DbStoreOptions, type EvaluateOptions, type EvaluateResult, type LimiterResolver, type RateLimitArgs, type RateLimitConfig, type RateLimitConfigMap, type RateLimitDatabase as RateLimitDb, type RateLimitDatabaseReader as RateLimitDbReader, RateLimitError, type RateLimitKind, type RateLimitMiddlewareOptions, type RateLimitReason, type RateLimitStatus, type RateLimitStore, type RateLimitValue, RateLimiter, type RateLimiterOptions, type RatelimitApiContext, type ReadOnlyDatabaseStoreOptions as ReadOnlyDbStoreOptions, type SqlLike, type SqlStoreOptions, type TokenBudget, VERSION, availableAt, createDatabaseStore as createDbStore, createMemoryStore, createReadOnlyDatabaseStore as createReadOnlyDbStore, createSqlStore, databaseRateLimit as dbRateLimit, evaluate, rateLimit, ratelimitPlugin, tokenBudget };
|
package/dist/index.d.ts
CHANGED
|
@@ -19,18 +19,6 @@ interface RateLimitConfig {
|
|
|
19
19
|
period: number;
|
|
20
20
|
/** Tokens granted per `period`. */
|
|
21
21
|
rate: number;
|
|
22
|
-
/**
|
|
23
|
-
* Split a hot limit across N independent sub-buckets to avoid a single
|
|
24
|
-
* contended key/Durable Object. Each shard enforces `rate / shards` (and
|
|
25
|
-
* `capacity / shards`); a request is routed to a shard via a deterministic
|
|
26
|
-
* hash of `(name, key)`, so the same key always lands on the same shard and
|
|
27
|
-
* a single key's effective throughput is exactly `rate / shards`. Aggregate
|
|
28
|
-
* throughput across many distinct keys approaches `rate` as keys spread
|
|
29
|
-
* uniformly across shards. Reserve it for high-volume limits where
|
|
30
|
-
* contention bites; leave unset (one bucket) otherwise. Must be a positive
|
|
31
|
-
* integer — `1` is equivalent to unset.
|
|
32
|
-
*/
|
|
33
|
-
shards?: number;
|
|
34
22
|
/**
|
|
35
23
|
* Phase offset in epoch milliseconds for windowed algorithms — windows
|
|
36
24
|
* align to `start + n * period`. Ignored by token buckets. Defaults to `0`.
|
|
@@ -92,6 +80,34 @@ interface RateLimitStore {
|
|
|
92
80
|
delete: (storageKey: string) => Promise<void> | void;
|
|
93
81
|
get: (storageKey: string) => Promise<RateLimitValue | undefined> | RateLimitValue | undefined;
|
|
94
82
|
set: (storageKey: string, value: RateLimitValue) => Promise<void> | void;
|
|
83
|
+
/**
|
|
84
|
+
* Optional conditional write: persist `value` only while the stored value is
|
|
85
|
+
* still `prior` (what `get` returned for this consume, `undefined` for no
|
|
86
|
+
* row), and resolve `false` when it no longer is. When present the limiter
|
|
87
|
+
* writes through it instead of `set`, and a `false` makes it read and decide
|
|
88
|
+
* again rather than admit off a stale read.
|
|
89
|
+
*
|
|
90
|
+
* A store whose `get` and write cannot be interleaved by another consume
|
|
91
|
+
* (memory, SQL: synchronous) needs none. One whose calls can be
|
|
92
|
+
* (`createDbStore`: every call is awaited I/O) must have it.
|
|
93
|
+
*/
|
|
94
|
+
setIf?: (storageKey: string, value: RateLimitValue, prior: RateLimitValue | undefined) => Promise<boolean>;
|
|
95
|
+
/**
|
|
96
|
+
* Optional eviction hint, called by the limiter after each successful write.
|
|
97
|
+
* Remove up to `limit` entries whose `ts` is at or before `olderThanTs`, except
|
|
98
|
+
* entries with a negative `value`: a reserved debt is kept, whatever its age.
|
|
99
|
+
* The memory store examines up to `limit` entries from its oldest end; the
|
|
100
|
+
* durable stores delete at most `limit` matching rows. A returned promise is
|
|
101
|
+
* awaited, so a store whose sweep is I/O (`createDbStore`) finishes it before the
|
|
102
|
+
* consume returns. The durable stores implement it so a table stays bounded
|
|
103
|
+
* without a scheduled job; see `createSqlStore` and `createDbStore` for the
|
|
104
|
+
* table shape.
|
|
105
|
+
*
|
|
106
|
+
* `owns` says whether a storage key belongs to the limiter asking for the
|
|
107
|
+
* sweep. A store shared with another limiter must leave the other limiter's
|
|
108
|
+
* keys alone: its horizon is not this one's. Absent means every key is owned.
|
|
109
|
+
*/
|
|
110
|
+
sweep?: (olderThanTs: number, limit: number, owns?: (storageKey: string) => boolean) => Promise<void> | void;
|
|
95
111
|
}
|
|
96
112
|
/** Inputs to {@link evaluate}. */
|
|
97
113
|
interface EvaluateOptions {
|
|
@@ -135,11 +151,15 @@ interface RateLimiterOptions<Names extends string> {
|
|
|
135
151
|
denyList?: Iterable<string>;
|
|
136
152
|
/**
|
|
137
153
|
* Optional key normalizer applied to every incoming `args.key` (the
|
|
138
|
-
* deny-list check
|
|
139
|
-
*
|
|
140
|
-
* IPs/emails so equivalent inputs share a single bucket. The deny-list
|
|
154
|
+
* deny-list check and the storage key both see the normalized form). Use for case-folding, trimming, or canonicalizing
|
|
155
|
+
* emails so equivalent inputs share a single bucket. The deny-list
|
|
141
156
|
* itself is consulted as-is; normalize the deny-list entries up front to
|
|
142
157
|
* match.
|
|
158
|
+
*
|
|
159
|
+
* After it, a key that is an IPv6 address is always collapsed to its /64
|
|
160
|
+
* (`2001:db8:1:2::/64`) and an IPv4-mapped one to its IPv4 address, so a
|
|
161
|
+
* `ctx.ip`-keyed limit cannot be dodged by rotating addresses within one
|
|
162
|
+
* delegated prefix. A deny-list IPv6 entry therefore bans its whole /64.
|
|
143
163
|
*/
|
|
144
164
|
normalize?: (key: string) => string;
|
|
145
165
|
/** Clock injection for tests. Defaults to `Date.now`. */
|
|
@@ -158,7 +178,10 @@ declare class RateLimiter<Names extends string = string> {
|
|
|
158
178
|
private readonly denyList;
|
|
159
179
|
private readonly normalize;
|
|
160
180
|
private readonly now;
|
|
181
|
+
private readonly retention;
|
|
161
182
|
private readonly store;
|
|
183
|
+
/** Whether a stored key is one of this limiter's names; a sweep only evicts those. */
|
|
184
|
+
private readonly owns;
|
|
162
185
|
constructor(options: RateLimiterOptions<Names>);
|
|
163
186
|
/** Peek at whether a request would be permitted without consuming. */
|
|
164
187
|
check(name: Names, args?: Omit<RateLimitArgs, "reserve" | "throws">): Promise<RateLimitStatus>;
|
|
@@ -166,9 +189,7 @@ declare class RateLimiter<Names extends string = string> {
|
|
|
166
189
|
* Read the current config and the units admittable right now for a
|
|
167
190
|
* `(name, key)` pair. The value is projected forward to the current clock
|
|
168
191
|
* (token-bucket refill, fixed-window rollover, sliding-window decay), not
|
|
169
|
-
* the last persisted figure.
|
|
170
|
-
* shard `limit()`/`run()` would route this key to — the sibling shards are
|
|
171
|
-
* never touched by this key, so summing them would over-report.
|
|
192
|
+
* the last persisted figure.
|
|
172
193
|
*/
|
|
173
194
|
getValue(name: Names, args?: {
|
|
174
195
|
key?: string;
|
|
@@ -183,6 +204,22 @@ declare class RateLimiter<Names extends string = string> {
|
|
|
183
204
|
reset(name: Names, args?: {
|
|
184
205
|
key?: string;
|
|
185
206
|
}): Promise<void>;
|
|
207
|
+
/**
|
|
208
|
+
* Read, evaluate and write one consume. A store that reports the write lost
|
|
209
|
+
* (`setIf` resolved `false`: another consume changed the value since this one
|
|
210
|
+
* read it) gets a fresh read and a fresh decision, so the admission always
|
|
211
|
+
* rests on the value the write replaced. Bounded: each lost round means some
|
|
212
|
+
* other consume was admitted (a refusal writes nothing), and past
|
|
213
|
+
* {@link MAX_DECIDE_ATTEMPTS} the call is refused with `retryAfter: 0` rather
|
|
214
|
+
* than admitted.
|
|
215
|
+
*/
|
|
216
|
+
private decide;
|
|
217
|
+
/**
|
|
218
|
+
* Evict what this limiter's horizon has expired, after a write has landed. The
|
|
219
|
+
* write is already done, so awaiting here does not reopen the read-decide-write
|
|
220
|
+
* window. Only a promise-returning sweep (`createDbStore`) is awaited for I/O.
|
|
221
|
+
*/
|
|
222
|
+
private sweep;
|
|
186
223
|
private normalizeKey;
|
|
187
224
|
private resolve;
|
|
188
225
|
private run;
|
|
@@ -203,7 +240,15 @@ interface RateLimitMiddlewareOptions<Context> {
|
|
|
203
240
|
* — note that a failing limiter then permits every request through.
|
|
204
241
|
*/
|
|
205
242
|
failOpen?: boolean;
|
|
206
|
-
/**
|
|
243
|
+
/**
|
|
244
|
+
* Sub-key derived from `ctx` (per-user/IP). Omit for a global limit.
|
|
245
|
+
*
|
|
246
|
+
* A resolver that returns `undefined` is a config bug, not a global limit:
|
|
247
|
+
* the middleware throws `INTERNAL` rather than silently pooling every
|
|
248
|
+
* keyless caller (e.g. every anonymous user) into one shared bucket. Fold
|
|
249
|
+
* the absent case yourself — `ctx.auth.userId ?? "anonymous"` — so the
|
|
250
|
+
* shared bucket is a visible choice.
|
|
251
|
+
*/
|
|
207
252
|
key?: (context: Context) => string | undefined;
|
|
208
253
|
/** Override the error message thrown on rejection. */
|
|
209
254
|
message?: string;
|
|
@@ -212,7 +257,7 @@ interface RateLimitMiddlewareOptions<Context> {
|
|
|
212
257
|
* Procedure middleware that enforces a named rate limit before the handler
|
|
213
258
|
* runs. Attach it with `.use()`. On rejection it throws a structural
|
|
214
259
|
* `LunoraError` (`TOO_MANY_REQUESTS`/429, or `FORBIDDEN`/403 for deny-list
|
|
215
|
-
* hits) carrying `
|
|
260
|
+
* hits) carrying `data.retryAfterMs` — the runtime maps it to the
|
|
216
261
|
* matching RPC/HTTP status without any import of `@lunora/server` at runtime.
|
|
217
262
|
*
|
|
218
263
|
* **Failure policy:** if resolving or invoking the limiter throws for a genuine
|
|
@@ -231,6 +276,9 @@ declare const rateLimit: <Context>(limiter: LimiterResolver<Context>, name: stri
|
|
|
231
276
|
* In-memory store. State lives for the lifetime of the process (or, inside a
|
|
232
277
|
* Durable Object, the instance) — adequate for single-DO limits but not shared
|
|
233
278
|
* across instances. Use {@link createSqlStore} for durable per-DO state.
|
|
279
|
+
*
|
|
280
|
+
* A store may be shared by several limiters: each sweep evicts only the keys its
|
|
281
|
+
* limiter owns, by that limiter's horizon (see `RateLimitStore.sweep`).
|
|
234
282
|
*/
|
|
235
283
|
declare const createMemoryStore: () => RateLimitStore;
|
|
236
284
|
/**
|
|
@@ -247,38 +295,8 @@ interface SqlStoreOptions {
|
|
|
247
295
|
/** Table name. Created if missing. Defaults to `_lunora_rate_limits`. */
|
|
248
296
|
table?: string;
|
|
249
297
|
}
|
|
250
|
-
/**
|
|
251
|
-
* SQLite-backed store for durable, per-DO rate-limit state. Persists each
|
|
252
|
-
* `(name, key)` pair as one row so limits survive hibernation and eviction.
|
|
253
|
-
*
|
|
254
|
-
* **Atomicity:** the store does not wrap individual operations in an explicit
|
|
255
|
-
* SQL transaction. Inside a Durable Object the DO's input gate serializes
|
|
256
|
-
* every RPC call against the storage, so the limiter's read-modify-write
|
|
257
|
-
* sequence runs to completion without interleaving — this is the same
|
|
258
|
-
* guarantee the surrounding `evaluate()` step depends on. **Outside a DO**
|
|
259
|
-
* (e.g. driving `createSqlStore` from a long-lived `node:sqlite` connection in
|
|
260
|
-
* tests or a custom host) the caller is responsible for serialization; the
|
|
261
|
-
* SQL surface used here (`exec`) is not a substitute for transactional
|
|
262
|
-
* isolation across concurrent invocations.
|
|
263
|
-
*/
|
|
298
|
+
/** Sql store, with keys stored losslessly; see {@link encodeStorageKey}. */
|
|
264
299
|
declare const createSqlStore: (options: SqlStoreOptions) => RateLimitStore;
|
|
265
|
-
/**
|
|
266
|
-
* The slice of an index-range builder the store uses. Mirrors `@lunora/server`'s
|
|
267
|
-
* `IndexRangeBuilder` field-for-field so the real `ctx.db` query builder is
|
|
268
|
-
* assignable; only `eq` is exercised.
|
|
269
|
-
*/
|
|
270
|
-
interface RateLimitDatabaseIndexRange {
|
|
271
|
-
eq: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
272
|
-
gt: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
273
|
-
gte: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
274
|
-
lt: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
275
|
-
lte: (field: string, value: unknown) => RateLimitDatabaseIndexRange;
|
|
276
|
-
}
|
|
277
|
-
/** The slice of a `ctx.db` table query the store relies on. */
|
|
278
|
-
interface RateLimitDatabaseQuery {
|
|
279
|
-
first: () => Promise<Record<string, unknown> | null>;
|
|
280
|
-
withIndex: (indexName: string, range: (q: RateLimitDatabaseIndexRange) => RateLimitDatabaseIndexRange) => RateLimitDatabaseQuery;
|
|
281
|
-
}
|
|
282
300
|
/**
|
|
283
301
|
* The READ slice — everything the store needs to answer `RateLimiter.getValue`
|
|
284
302
|
* and `check`, which the docs describe as projecting the stored value forward to
|
|
@@ -289,9 +307,16 @@ interface RateLimitDatabaseQuery {
|
|
|
289
307
|
* at all — every remaining-quota display had to cast, and a cast that appears
|
|
290
308
|
* often enough stops carrying information. The distinction was already in the
|
|
291
309
|
* methods: `getValue`/`check` read, `limit`/`reset` write.
|
|
310
|
+
*
|
|
311
|
+
* `findFirst` rather than `query(table).withIndex(...)`: a `.global()` table's
|
|
312
|
+
* reader has no `withIndex`, so the indexed builder failed every read there.
|
|
313
|
+
* `findFirst` routes to whichever backend owns the table, and an equality on the
|
|
314
|
+
* key column still uses its index.
|
|
292
315
|
*/
|
|
293
316
|
interface RateLimitDatabaseReader {
|
|
294
|
-
|
|
317
|
+
findFirst: (table: string, args?: {
|
|
318
|
+
where?: Record<string, unknown>;
|
|
319
|
+
}) => Promise<Record<string, unknown> | null>;
|
|
295
320
|
}
|
|
296
321
|
/**
|
|
297
322
|
* The slice of the Lunora ORM writer (`ctx.db` on a mutation/action) the store
|
|
@@ -300,15 +325,33 @@ interface RateLimitDatabaseReader {
|
|
|
300
325
|
* free of a runtime dependency on `@lunora/server`.
|
|
301
326
|
*/
|
|
302
327
|
interface RateLimitDatabase extends RateLimitDatabaseReader {
|
|
303
|
-
delete: <T extends string>(id: Id<T>) => Promise<void>;
|
|
304
|
-
|
|
305
|
-
|
|
328
|
+
delete: <T extends string>(table: T, id: Id<T>) => Promise<void>;
|
|
329
|
+
/**
|
|
330
|
+
* Used by `sweep` only: rows matching `where`, at most `limit`. Optional in the
|
|
331
|
+
* type because the public `DatabaseWriter` does not declare it; the framework's
|
|
332
|
+
* `ctx.db` implements it, and `sweep` throws if an adapter does not.
|
|
333
|
+
*/
|
|
334
|
+
findMany?: (table: string, args: {
|
|
335
|
+
limit?: number;
|
|
336
|
+
orderBy?: Record<string, "asc" | "desc">[];
|
|
337
|
+
where?: Record<string, unknown>;
|
|
338
|
+
}) => Promise<{
|
|
339
|
+
page: Record<string, unknown>[];
|
|
340
|
+
}>;
|
|
341
|
+
insert: <T extends string>(table: T, document: Record<string, unknown>, options?: {
|
|
342
|
+
clientId?: string;
|
|
343
|
+
}) => Promise<Id<T>>;
|
|
344
|
+
patchIf: <T extends string>(table: T, id: Id<T>, args: {
|
|
345
|
+
patch: Record<string, unknown>;
|
|
346
|
+
where: Record<string, unknown>;
|
|
347
|
+
}) => Promise<{
|
|
348
|
+
applied: boolean;
|
|
349
|
+
doc: Record<string, unknown> | null;
|
|
350
|
+
}>;
|
|
306
351
|
}
|
|
307
|
-
/** The table/column
|
|
352
|
+
/** The table/column knobs shared by the read-only and read-write stores. */
|
|
308
353
|
interface DatabaseStoreLocation {
|
|
309
|
-
/**
|
|
310
|
-
index?: string;
|
|
311
|
-
/** Column storing the opaque key. Defaults to `key`. */
|
|
354
|
+
/** Column storing the opaque key. Defaults to `key`. Index it: every consume reads by it. */
|
|
312
355
|
keyField?: string;
|
|
313
356
|
/** Table holding one row per `(name, key)` pair. Defaults to `rateLimits`. */
|
|
314
357
|
table?: string;
|
|
@@ -321,23 +364,7 @@ interface ReadOnlyDatabaseStoreOptions extends DatabaseStoreLocation {
|
|
|
321
364
|
/** The Lunora ORM reader — `ctx.db` inside a query. */
|
|
322
365
|
db: RateLimitDatabaseReader;
|
|
323
366
|
}
|
|
324
|
-
/**
|
|
325
|
-
* Store backed by a Lunora table through `ctx.db`, for durable per-DO limits
|
|
326
|
-
* inside a procedure (the procedure context exposes no raw SQL). Declare a
|
|
327
|
-
* table with the key column and its index, e.g.
|
|
328
|
-
*
|
|
329
|
-
* ```ts
|
|
330
|
-
* rateLimits: defineTable({
|
|
331
|
-
* key: v.string(),
|
|
332
|
-
* ts: v.number(),
|
|
333
|
-
* value: v.number(),
|
|
334
|
-
* prev: v.optional(v.number()),
|
|
335
|
-
* }).index("by_key", ["key"])
|
|
336
|
-
* ```
|
|
337
|
-
*
|
|
338
|
-
* Each operation is a read-then-write; inside a mutation/action that pair runs
|
|
339
|
-
* under the DO's input gate, so it is atomic against concurrent calls.
|
|
340
|
-
*/
|
|
367
|
+
/** Database store, with keys stored losslessly; see {@link encodeStorageKey}. */
|
|
341
368
|
declare const createDatabaseStore: (options: DatabaseStoreOptions) => RateLimitStore;
|
|
342
369
|
/**
|
|
343
370
|
* Read-only counterpart to {@link createDatabaseStore}, for a query context.
|
|
@@ -365,12 +392,17 @@ declare const createReadOnlyDatabaseStore: (options: ReadOnlyDatabaseStoreOption
|
|
|
365
392
|
* on the DO the procedure runs on). Every query/mutation/action ctx exposes a
|
|
366
393
|
* compatible `db`, so it slots straight into a `.use(...)` chain.
|
|
367
394
|
*
|
|
368
|
-
* Pass `options.store` to point at a non-default backing table/
|
|
369
|
-
* (defaults: table `rateLimits`,
|
|
395
|
+
* Pass `options.store` to point at a non-default backing table/key column
|
|
396
|
+
* (defaults: table `rateLimits`, key column `key`); the rest of
|
|
370
397
|
* `options` (`key`, `count`, `failOpen`, `message`) is forwarded to
|
|
371
398
|
* {@link rateLimit} unchanged. When `config` is precisely typed, `name`
|
|
372
399
|
* autocompletes to its declared limit names.
|
|
373
400
|
*
|
|
401
|
+
* On a mutation the consumed unit commits with the handler: a handler that
|
|
402
|
+
* throws rolls it back, so a failed call costs nothing. Attach it to an action
|
|
403
|
+
* (whose writes commit independently) when failed attempts must count — see
|
|
404
|
+
* {@link createDatabaseStore}.
|
|
405
|
+
*
|
|
374
406
|
* Re-exported as `dbRateLimit` from the package root.
|
|
375
407
|
*
|
|
376
408
|
* ```ts
|
|
@@ -440,5 +472,50 @@ interface RatelimitApiContext<Context> {
|
|
|
440
472
|
* `@lunora/server` a type-only dependency of `@lunora/ratelimit`.
|
|
441
473
|
*/
|
|
442
474
|
declare const ratelimitPlugin: <Context = unknown>(limiter: LimiterResolver<Context>) => Plugin<Record<never, never>, Context, Context & RatelimitApiContext<Context>>;
|
|
475
|
+
/** A budget bound to one named limit — check before the call, record after it. */
|
|
476
|
+
interface TokenBudget {
|
|
477
|
+
/**
|
|
478
|
+
* Peek at the budget before spending. `ok: false` means it is exhausted:
|
|
479
|
+
* refuse the call, and `retryAfter` says when it refills. Consumes nothing.
|
|
480
|
+
*/
|
|
481
|
+
check: (key: string) => Promise<RateLimitStatus>;
|
|
482
|
+
/**
|
|
483
|
+
* Charge the tokens a call actually used. Always call it, including when the
|
|
484
|
+
* call THREW — a failed generation that consumed input tokens still has to be
|
|
485
|
+
* paid for. `tokens` of `0` is a no-op, so a call that spent nothing costs
|
|
486
|
+
* nothing.
|
|
487
|
+
*
|
|
488
|
+
* The charge is a reservation, so it may take the bucket negative: the tokens
|
|
489
|
+
* are already spent, and refusing to record them would let a single oversized
|
|
490
|
+
* call escape the budget entirely.
|
|
491
|
+
*/
|
|
492
|
+
record: (key: string, tokens: number) => Promise<RateLimitStatus>;
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Bind a {@link TokenBudget} to one of a limiter's named limits.
|
|
496
|
+
*
|
|
497
|
+
* ```ts
|
|
498
|
+
* const budget = tokenBudget(limiter, "tokens");
|
|
499
|
+
* const allowed = await budget.check(userId);
|
|
500
|
+
*
|
|
501
|
+
* if (!allowed.ok) {
|
|
502
|
+
* throw new LunoraError("RATE_LIMITED", `token budget exhausted; retry in ${String(allowed.retryAfter)}ms`);
|
|
503
|
+
* }
|
|
504
|
+
*
|
|
505
|
+
* try {
|
|
506
|
+
* const { text, usage } = await generateText({ model: ctx.ai.model(), prompt });
|
|
507
|
+
*
|
|
508
|
+
* await budget.record(userId, usage?.totalTokens ?? 0);
|
|
509
|
+
*
|
|
510
|
+
* return text;
|
|
511
|
+
* } catch (error) {
|
|
512
|
+
* // The prompt was still sent — charge what is known, then rethrow.
|
|
513
|
+
* await budget.record(userId, estimatedInputTokens);
|
|
514
|
+
*
|
|
515
|
+
* throw error;
|
|
516
|
+
* }
|
|
517
|
+
* ```
|
|
518
|
+
*/
|
|
519
|
+
declare const tokenBudget: <Names extends string>(limiter: RateLimiter<Names>, name: Names) => TokenBudget;
|
|
443
520
|
declare const VERSION = "0.0.0";
|
|
444
|
-
export { type DatabaseStoreOptions as DbStoreOptions, type EvaluateOptions, type EvaluateResult, type LimiterResolver, type RateLimitArgs, type RateLimitConfig, type RateLimitConfigMap, type RateLimitDatabase as RateLimitDb, type
|
|
521
|
+
export { type DatabaseStoreOptions as DbStoreOptions, type EvaluateOptions, type EvaluateResult, type LimiterResolver, type RateLimitArgs, type RateLimitConfig, type RateLimitConfigMap, type RateLimitDatabase as RateLimitDb, type RateLimitDatabaseReader as RateLimitDbReader, RateLimitError, type RateLimitKind, type RateLimitMiddlewareOptions, type RateLimitReason, type RateLimitStatus, type RateLimitStore, type RateLimitValue, RateLimiter, type RateLimiterOptions, type RatelimitApiContext, type ReadOnlyDatabaseStoreOptions as ReadOnlyDbStoreOptions, type SqlLike, type SqlStoreOptions, type TokenBudget, VERSION, availableAt, createDatabaseStore as createDbStore, createMemoryStore, createReadOnlyDatabaseStore as createReadOnlyDbStore, createSqlStore, databaseRateLimit as dbRateLimit, evaluate, rateLimit, ratelimitPlugin, tokenBudget };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{availableAt as o,evaluate as a}from"./packem_shared/availableAt-
|
|
1
|
+
import{availableAt as o,evaluate as a}from"./packem_shared/availableAt-DCUEox4O.mjs";import{default as i}from"./packem_shared/dbRateLimit-D8xJ03b-.mjs";import{default as l}from"./packem_shared/RateLimitError-9Y5OLxpl.mjs";import{rateLimit as x}from"./packem_shared/rateLimit-CWZur6XE.mjs";import{ratelimitPlugin as c}from"./packem_shared/ratelimitPlugin-CFnDs9rj.mjs";import{RateLimiter as u}from"./packem_shared/RateLimiter-C67wj24r.mjs";import{createDbStore as b,createMemoryStore as n,createReadOnlyDbStore as L,createSqlStore as s}from"./packem_shared/createDbStore-DdoYxOaZ.mjs";import{tokenBudget as v}from"./packem_shared/tokenBudget-CPm8DEVi.mjs";const e="0.0.0";export{l as RateLimitError,u as RateLimiter,e as VERSION,o as availableAt,b as createDbStore,n as createMemoryStore,L as createReadOnlyDbStore,s as createSqlStore,i as dbRateLimit,a as evaluate,x as rateLimit,c as ratelimitPlugin,v as tokenBudget};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{STATUS_BY_REASON as a}from"./rateLimit-CWZur6XE.mjs";const s=r=>r.reason==="deny"?"request denied (deny list)":Number.isFinite(r.retryAfter)?`rate limit exceeded; retry after ${String(Math.ceil(r.retryAfter))}ms`:"rate limit exceeded";class c extends n{reason;retryAfter;constructor(e,t){const{code:i,status:o}=a[e.reason??"rate"];super(i,t??s(e),{name:"RateLimitError",status:o}),this.reason=e.reason,this.retryAfter=e.retryAfter}}export{c as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{retentionMs as y,availableAt as v,evaluate as N}from"./availableAt-DCUEox4O.mjs";import w from"./RateLimitError-9Y5OLxpl.mjs";import{createMemoryStore as b}from"./createDbStore-DdoYxOaZ.mjs";const I=/^[\d.:a-f]+$/iu,d=i=>{const t=i.indexOf("%"),e=t===-1?i:i.slice(0,t);if(!e.includes(":")||!I.test(e))return i;let s;try{s=new URL(`http://[${e}]/`).hostname.slice(1,-1)}catch{return i}const[r="",n]=s.split("::"),a=r===""?[]:r.split(":"),l=n===void 0||n===""?[]:n.split(":"),c=[...a,...Array.from({length:8-a.length-l.length},()=>"0"),...l].map(o=>Number.parseInt(o,16));if(c.slice(0,5).every(o=>o===0)&&c[5]===65535){const[o=0,f=0]=c.slice(6);return[o>>8,o&255,f>>8,f&255].join(".")}return`${c.slice(0,4).map(o=>o.toString(16)).join(":")}::/64`},g=new RegExp("(\\p{Cs})","u"),u=i=>i.isWellFormed()?encodeURIComponent(i):i.split(g).map((t,e)=>e%2===1?`%u${(t.codePointAt(0)??0).toString(16).toUpperCase()}`:encodeURIComponent(t)).join(""),m=(i,t)=>t===void 0?u(i):`${u(i)}:${u(t)}`,E=16,L=32,p=i=>typeof i?.then=="function",R=i=>{let t=Number.NEGATIVE_INFINITY;return()=>(t=Math.max(t,i()),t)},T=i=>i?t=>d(i(t)):d,A="@lunora/ratelimit: new RateLimiter() was built with no explicit `store`, so it falls back to `createMemoryStore()` — an in-process Map. That Map is durable and correctly shared only for calls that land on the same Durable Object instance; it is NOT shared across `.shardBy(...)` shards or `.global()` replicas, and it resets when the DO instance is evicted/restarted. For a limit that must hold across any of those, pass a durable `store` (`createDbStore` or `createSqlStore`) instead. Pass `store: createMemoryStore()` explicitly once you've confirmed the in-memory default is correct here, to silence this warning.";class z{config;denyList;normalize;now;retention;store;owns;constructor(t){this.config=structuredClone(t.config);const e=new Set(Object.keys(this.config).map(s=>u(s)));this.owns=s=>e.has(s.split(":")[0]??""),this.normalize=T(t.normalize),this.denyList=new Set([...t.denyList??[]].flatMap(s=>[s,this.normalize(s)])),this.now=R(t.now??Date.now),t.store===void 0&&console.warn(A),this.store=t.store??b(),this.retention=y(Object.values(this.config));for(const[s,r]of Object.entries(this.config)){if(Object.hasOwn(r,"shards"))throw new h("INTERNAL",`rate limit "${s}": \`shards\` is no longer supported — remove it; the limit now enforces its full \`rate\` (lower \`rate\` if you raised it to offset the split)`);if(!Number.isFinite(r.period)||r.period<=0)throw new h("INTERNAL",`rate limit "${s}": period must be a positive number`);if(!Number.isFinite(r.rate)||r.rate<=0)throw new h("INTERNAL",`rate limit "${s}": rate must be a positive number`);if(r.capacity!==void 0&&(!Number.isFinite(r.capacity)||r.capacity<0))throw new h("INTERNAL",`rate limit "${s}": capacity must be a non-negative number`)}}async check(t,e={}){return this.run(t,e,!1)}async getValue(t,e={}){const s=this.resolve(t),r=this.now(),n=m(t,this.normalizeKey(e.key)),a=v(s,await this.store.get(n),r);return{config:s,ts:a.ts,value:a.value}}async limit(t,e={}){return this.run(t,e,!0)}async reset(t,e={}){this.resolve(t),await Promise.resolve(this.store.delete(m(t,this.normalizeKey(e.key))))}async decide(t,e,s){for(let r=0;r<E;r+=1){const n=this.store.get(e),a=p(n)?await n:n,l=this.now(),{status:c,value:o}=N(t,a,{...s,now:l});if(o===void 0)return c;if(this.store.setIf===void 0)return await this.store.set(e,o),await this.sweep(l),c;if(await this.store.setIf(e,o,a))return await this.sweep(l),c}return{ok:!1,reason:"rate",retryAfter:0}}async sweep(t){try{const e=this.store.sweep?.(t-this.retention,L,this.owns);p(e)&&await e}catch(e){console.warn("@lunora/ratelimit: the retention sweep failed; the consume still stands",e)}}normalizeKey(t){return t===void 0?void 0:this.normalize(t)}resolve(t){const e=this.config[t];if(!e)throw new h("INTERNAL",`rate limit "${t}" is not configured`);return e}async run(t,e,s){const r=this.resolve(t),n=this.normalizeKey(e.key);if(n!==void 0&&(this.denyList.has(n)||this.denyList.has(e.key))){const o={ok:!1,reason:"deny",retryAfter:Number.POSITIVE_INFINITY};if(e.throws)throw new w(o);return o}const a=e.count??1;if(!Number.isInteger(a)||a<=0)throw new h("INTERNAL",`rate limit "${t}": count must be a positive integer`);const l=m(t,n),c=await this.decide(r,l,{consume:s,count:a,reserve:e.reserve??!1});if(!c.ok&&e.throws)throw new w(c);return c}}export{z as RateLimiter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";const o=e=>e.capacity??e.rate,f=e=>e.kind==="sliding window"?e.rate:o(e),w=(e,a)=>{throw new S("INTERNAL",`@lunora/ratelimit: requested count ${String(e)} exceeds the limiter capacity ${String(a)}`)},N=4,i=(e,a,t)=>{const s=o(e),r=e.rate/e.period,u=a??{ts:t,value:s},l=Math.max(0,t-u.ts);return{available:Math.min(s,u.value+l*r),capacity:s,ratePerMs:r}},m=(e,a,t)=>{const s=e.start??0,r=s+Math.floor((t-s)/e.period)*e.period;if(!a)return{ts:r,value:o(e)};if(a.ts<r){let u=0,l=1;return(a.value<0||e.capacity!==void 0)&&(u=a.value,l=Math.max(1,Math.ceil((r-a.ts)/e.period))),{ts:r,value:Math.min(o(e),u+l*e.rate)}}return{ts:a.ts,value:a.value}},A=(e,a,t)=>{const s=e.start??0,r=s+Math.floor((t-s)/e.period)*e.period,u=t-r,l=(e.period-u)/e.period;let n=0,c=0;return a?.ts===r?(n=a.prev??0,c=a.value):a?.ts===r-e.period&&(n=a.value),{currentCount:c,elapsed:u,previousCount:n,weight:l,windowStart:r}},y=(e,a,t,s,r)=>{let u=r;for(let l=0;l<N&&!(i(e,a,t+u).available>=s);l+=1){const n=u+1,c=n===u?u+2**(Math.floor(Math.log2(u))-52):n;if(!Number.isFinite(c)||c===u)break;u=c}return u},W=(e,a,t)=>{const{available:s,capacity:r,ratePerMs:u}=i(e,a,t.now);if(s>=t.count){const d={ts:t.now,value:s-t.count};return{status:{ok:!0,retryAfter:0},value:t.consume?d:void 0}}const l=t.count-s;if(t.consume&&t.reserve&&t.count<=r){const d={ts:t.now,value:s-t.count};return{status:{ok:!0,retryAfter:y(e,d,t.now,0,Math.ceil(l/u))},value:d}}t.count>r&&w(t.count,r);const n=a!==void 0&&a.ts>t.now?a.ts:t.now;return{status:{ok:!1,reason:"rate",retryAfter:y(e,a,t.now,t.count,Math.ceil(n-t.now+l/u))},value:void 0}},x=(e,a,t,s,r,u)=>{const l=d=>m(e,a,t+d*e.period).value>=r;let c=s<0||e.capacity!==void 0?Math.max(1,Math.ceil((r-s)/e.rate)):1;for(let d=0;d<4&&c>1&&l(c-1);d+=1)c-=1;for(let d=0;d<4&&!l(c);d+=1)c+=1;return t+c*e.period-u},E=(e,a,t)=>{const s=o(e),r=m(e,a,t.now);if(r.value>=t.count){const u={ts:r.ts,value:r.value-t.count};return{status:{ok:!0,retryAfter:0},value:t.consume?u:void 0}}if(t.consume&&t.reserve&&t.count<=s){const u=r.value-t.count;return{status:{ok:!0,retryAfter:x(e,{ts:r.ts,value:u},r.ts,u,0,t.now)},value:{ts:r.ts,value:u}}}return t.count>s&&w(t.count,s),{status:{ok:!1,reason:"rate",retryAfter:x(e,a,r.ts,r.value,t.count,t.now)},value:void 0}},R=(e,a,t)=>{const s=e.rate,{period:r}=e,{currentCount:u,elapsed:l,previousCount:n,weight:c,windowStart:d}=A(e,a,t.now),h=n*c+u+t.count<=s,k=v=>{const M=s-v-t.count;if(n>0&&M>=0)return Math.ceil(r-l-M*r/n);const b=s-t.count,C=v>0?Math.max(0,r-b*r/v):0;return Math.ceil(r-l+C)};if(h||t.consume&&t.reserve&&t.count<=s){const v={prev:n,ts:d,value:u+t.count};return{status:{ok:!0,retryAfter:h?0:k(v.value)},value:t.consume?v:void 0}}return t.count>s&&w(t.count,s),{status:{ok:!1,reason:"rate",retryAfter:k(u)},value:void 0}},T=(e,a,t)=>{if(e.kind==="token bucket")return{ts:t,value:i(e,a,t).available};if(e.kind==="sliding window"){const{currentCount:s,previousCount:r,weight:u,windowStart:l}=A(e,a,t);return{ts:l,value:Math.max(0,e.rate-(r*u+s))}}return m(e,a,t)},O=e=>Math.max(0,...e.map(a=>a.period*(2+f(a)/a.rate))),_=(e,a,t)=>e.kind==="token bucket"?W(e,a,t):e.kind==="sliding window"?R(e,a,t):E(e,a,t);export{T as availableAt,f as enforcedCapacity,_ as evaluate,O as retentionMs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as I}from"@lunora/errors";const A=()=>{const e=new Map;let t=!0,s=Number.NEGATIVE_INFINITY;return{delete:r=>{e.delete(r)},get:r=>e.get(r),set:(r,a)=>{e.delete(r),e.set(r,a),(Number.isNaN(a.ts)||a.ts<s)&&(t=!1),s=a.ts},sweep:(r,a,c)=>{let d=0;for(const[o,u]of e){if(d>=a||t&&u.ts>r&&c?.(o)!==!1)break;d+=1,e.delete(o),(u.value<0||u.ts>r||c?.(o)===!1)&&(e.set(o,u),(Number.isNaN(u.ts)||u.ts<s)&&(t=!1))}}}},w=(e,t,...s)=>e.exec.call(e,t,...s).toArray(),S="",p=e=>e.isWellFormed()&&!e.startsWith(S)?e:`${S}${JSON.stringify(e)}`,h=e=>{if(!e.startsWith(S))return e;try{const t=JSON.parse(e.slice(S.length));return typeof t=="string"?t:e}catch{return e}},N=e=>{const t={delete:a=>e.delete(p(a)),get:a=>e.get(p(a)),set:(a,c)=>e.set(p(a),c)},{setIf:s,sweep:r}=e;return s&&(t.setIf=(a,c,d)=>s(p(a),c,d)),r&&(t.sweep=(a,c,d)=>r(a,c,d===void 0?void 0:o=>d(h(o)))),t},T=e=>{const{sql:t}=e,s=e.table??"_lunora_rate_limits";return w(t,`CREATE TABLE IF NOT EXISTS "${s}" (k TEXT PRIMARY KEY, value REAL NOT NULL, ts INTEGER NOT NULL, prev REAL)`),w(t,`CREATE INDEX IF NOT EXISTS "${s}_ts" ON "${s}" (ts) WHERE value >= 0`),{delete:r=>{w(t,`DELETE FROM "${s}" WHERE k = ?`,r)},sweep:(r,a,c)=>{const o=w(t,`SELECT k FROM "${s}" WHERE ts <= ? AND value >= 0 ORDER BY ts LIMIT ?`,r,a).map(({k:u})=>u).filter(u=>c?.(u)!==!1);o.length>0&&w(t,`DELETE FROM "${s}" WHERE k IN (SELECT value FROM json_each(?))`,JSON.stringify(o))},get:r=>{const c=w(t,`SELECT value, ts, prev FROM "${s}" WHERE k = ?`,r)[0];if(!c)return;const d={ts:c.ts,value:c.value};return c.prev!==null&&(d.prev=c.prev),d},set:(r,a)=>{w(t,`INSERT INTO "${s}" (k, value, ts, prev) VALUES (?, ?, ?, ?) ON CONFLICT(k) DO UPDATE SET value = excluded.value, ts = excluded.ts, prev = excluded.prev`,r,a.value,a.ts,a.prev??null)}}},D=e=>N(T(e)),m=e=>e.toString(16).padStart(2,"0"),R=async(e,t)=>{const r=[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).subarray(0,16)];r[6]=128+r[6]%16,r[8]=128+r[8]%64;const a=r.map(c=>m(c)).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`},O=e=>e?.code==="CONFLICT",y=e=>{const{db:t}=e,s=e.table??"rateLimits",r=e.keyField??"key",a=new Map;let c=!1;const d=async n=>{const i=await t.findFirst(s,{where:{[r]:n}});return a.set(n,i?i._id:void 0),i},o=async n=>(a.has(n)||await d(n),a.get(n)),u=(n,i)=>{const l={[r]:n,ts:i.ts,value:i.value};return i.prev!==void 0&&(l.prev=i.prev),l},b=async(n,i)=>{try{return a.set(n,await t.insert(s,i,{clientId:await R(s,n)})),!0}catch(l){if(O(l))return a.delete(n),!1;throw l}};return{delete:async n=>{const i=await o(n);i!==void 0&&await t.delete(s,i),a.delete(n)},get:async n=>{const i=await d(n);if(!i)return;const l={ts:i.ts,value:i.value};return i.prev!==null&&i.prev!==void 0&&(l.prev=i.prev),l},set:async(n,i)=>{const l=u(n,i);let v=await o(n);if(v===void 0){if(await b(n,l))return;await d(n),v=a.get(n)}v!==void 0&&await t.patchIf(s,v,{patch:l,where:{}})},setIf:async(n,i,l)=>{const v=u(n,i);if(l===void 0)return b(n,v);const E=await o(n);if(E===void 0)return!1;const{applied:f}=await t.patchIf(s,E,{patch:v,where:{prev:l.prev??null,ts:l.ts,value:l.value}});return f||a.delete(n),f},sweep:async(n,i,l)=>{if(t.findMany===void 0){c||(c=!0,console.warn(`@lunora/ratelimit: table "${s}" is not swept: the adapter has no findMany. Pass the framework's ctx.db.`));return}const{page:v}=await t.findMany(s,{limit:i,orderBy:[{ts:"asc"}],where:{ts:{lte:n},value:{gte:0}}}),E=v.filter(f=>l?.(String(f[r]))!==!1);await Promise.all(E.map(async f=>{await t.findFirst(s,{where:{_id:f._id,prev:f.prev??null,ts:f.ts,value:f.value}})!==null&&await t.delete(s,f._id)}))}}},L=e=>N(y(e)),k=e=>{const t=r=>{throw new I("INTERNAL",`@lunora/ratelimit: \`${r}\` needs a writable \`ctx.db\`, but this store was created with \`createReadOnlyDbStore\` (a query context). Use \`createDbStore\` from a mutation or action; a query can only call \`getValue\`/\`check\`.`)},s=L({...e,db:{delete:()=>t("delete"),findFirst:e.db.findFirst.bind(e.db),insert:()=>t("insert"),patchIf:()=>t("patchIf")}});return{delete:()=>t("reset"),get:s.get,set:()=>t("limit"),setIf:()=>t("limit")}};export{L as createDbStore,A as createMemoryStore,k as createReadOnlyDbStore,D as createSqlStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{rateLimit as o}from"./rateLimit-CWZur6XE.mjs";import{RateLimiter as m}from"./RateLimiter-C67wj24r.mjs";import{createDbStore as i}from"./createDbStore-DdoYxOaZ.mjs";const f=(e,r,t={})=>o(a=>new m({config:e,store:i({db:a.db,...t.store})}),r,t);export{f as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isLunoraError as c,isInternalCode as l,LunoraError as n}from"@lunora/errors";import{tagPerDispatchMiddleware as f}from"@lunora/server";const v={deny:{code:"FORBIDDEN",status:403},rate:{code:"TOO_MANY_REQUESTS",status:429}},y=(r,t,e)=>t==="deny"?`request denied for "${r}"`:e===void 0?`rate limit "${r}" exceeded`:`rate limit "${r}" exceeded; retry after ${String(e)}ms`,w=(r,t,e)=>{if(!e)return;const a=e(t);if(a===void 0)throw new n("INTERNAL",`@lunora/ratelimit: rateLimit("${r}") key resolver returned undefined; return a fallback such as "anonymous" instead`);return a},h=(r,t,e={})=>f(async({ctx:a,next:d})=>{let i;try{i=await(typeof r=="function"?await r(a):r).limit(t,{count:e.count,key:w(t,a,e.key)})}catch(o){if(c(o)&&l(o.code))throw o;if(console.error(`@lunora/ratelimit: rateLimit("${t}") threw; ${e.failOpen?"failing open":"failing closed"}`,o),e.failOpen)return d();throw new n("SERVICE_UNAVAILABLE",`rate limiter unavailable for "${t}"`,{cause:o,status:503})}if(!i.ok){const o=i.reason??"rate",u=v[o],s=Number.isFinite(i.retryAfter)?Math.ceil(i.retryAfter):void 0;throw new n(u.code,e.message??y(t,o,s),{status:u.status,data:s===void 0?void 0:{retryAfterMs:s}})}return d()});export{v as STATUS_BY_REASON,h as rateLimit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=t=>({key:"ratelimit",middleware:async({ctx:e,next:i})=>{const n=typeof t=="function"?await t(e):t,a=e.api??{};return i({ctx:{api:{...a,ratelimit:n}}})}});export{r as ratelimitPlugin};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{enforcedCapacity as n}from"./availableAt-DCUEox4O.mjs";const h=(t,r)=>({check:async c=>t.check(r,{key:c}),record:async(c,a)=>{if(!Number.isFinite(a)||a<=0)return t.check(r,{key:c});const{config:e}=await t.getValue(r,{key:c}),o=Math.max(1,Math.floor(n(e)));return t.limit(r,{count:Math.min(Math.ceil(a),o),key:c,reserve:!0})}});export{h as tokenBudget};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/ratelimit",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
4
|
-
"description": "Rate limiting: token-bucket / fixed-window / sliding-window algorithms, deny list,
|
|
3
|
+
"version": "1.0.0-alpha.191",
|
|
4
|
+
"description": "Rate limiting: token-bucket / fixed-window / sliding-window algorithms, deny list, pluggable stores, and procedure middleware",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
7
7
|
"durable-objects",
|
|
@@ -46,7 +46,11 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
49
|
+
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"@lunora/server": ">=1.0.0-alpha.24 <2.0.0-0",
|
|
53
|
+
"@lunora/values": ">=1.0.0-alpha.7 <2.0.0-0"
|
|
50
54
|
},
|
|
51
55
|
"engines": {
|
|
52
56
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{STATUS_BY_REASON as o}from"./rateLimit-DLcwK-84.mjs";const n=e=>e.reason==="deny"?"request denied (deny list)":Number.isFinite(e.retryAfter)?`rate limit exceeded; retry after ${String(Math.ceil(e.retryAfter))}ms`:"rate limit exceeded";class c extends i{reason;retryAfter;constructor(r,t){const{code:s,status:a}=o[r.reason??"rate"];super(s,t??n(r),{name:"RateLimitError",status:a}),this.reason=r.reason,this.retryAfter=r.retryAfter}}export{c as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as n}from"@lunora/errors";import{availableAt as p,evaluate as N}from"./availableAt-BMlAt2U2.mjs";import w from"./RateLimitError-xJ2Iv-i7.mjs";import{createMemoryStore as g}from"./createDbStore-CwJBMxDQ.mjs";const y=(r,t)=>t===void 0?encodeURIComponent(r):`${encodeURIComponent(r)}:${encodeURIComponent(t)}`,b=(r,t)=>{let e=0;for(let i=0;i<r.length;i+=1)e=e*31+r.charCodeAt(i)|0;return Math.abs(e)%t},d=(r,t)=>t>1?{...r,capacity:(r.capacity??r.rate)/t,rate:r.rate/t}:r,I=(r,t,e)=>{const i=y(r,t);return e>1?Array.from({length:e},(o,s)=>`${i}#${String(s)}`):[i]},f=(r,t,e)=>{const i=y(r,t);return e>1?`${i}#${String(b(i,e))}`:i};class z{config;denyList;normalize;now;store;constructor(t){this.config=t.config,this.denyList=new Set(t.denyList),this.normalize=t.normalize??(e=>e),this.now=t.now??Date.now,this.store=t.store??g();for(const[e,i]of Object.entries(this.config)){if(i.shards!==void 0&&(!Number.isInteger(i.shards)||i.shards<1))throw new n("INTERNAL",`rate limit "${e}": shards must be a positive integer`);if(!Number.isFinite(i.period)||i.period<=0)throw new n("INTERNAL",`rate limit "${e}": period must be a positive number`);if(!Number.isFinite(i.rate)||i.rate<=0)throw new n("INTERNAL",`rate limit "${e}": rate must be a positive number`);if(i.capacity!==void 0&&(!Number.isFinite(i.capacity)||i.capacity<0))throw new n("INTERNAL",`rate limit "${e}": capacity must be a non-negative number`)}}async check(t,e={}){return this.run(t,e,!1)}async getValue(t,e={}){const i=this.resolve(t),o=i.shards??1,s=this.now(),a=this.normalizeKey(e.key),m=f(t,a,o),c=p(d(i,o),await this.store.get(m),s);return{config:i,ts:c.ts,value:c.value}}async limit(t,e={}){return this.run(t,e,!0)}async reset(t,e={}){const i=this.resolve(t).shards??1,o=this.normalizeKey(e.key);await Promise.all(I(t,o,i).map(s=>Promise.resolve(this.store.delete(s))))}normalizeKey(t){return t===void 0?void 0:this.normalize(t)}resolve(t){const e=this.config[t];if(!e)throw new n("INTERNAL",`rate limit "${t}" is not configured`);return e}async run(t,e,i){const o=this.resolve(t),s=this.normalizeKey(e.key);if(s!==void 0&&(this.denyList.has(s)||this.denyList.has(e.key))){const l={ok:!1,reason:"deny",retryAfter:Number.POSITIVE_INFINITY};if(e.throws)throw new w(l);return l}const a=e.count??1;if(!Number.isInteger(a)||a<=0)throw new n("INTERNAL",`rate limit "${t}": count must be a positive integer`);const m=o.shards??1,c=f(t,s,m),v=await this.store.get(c),{status:h,value:u}=N(d(o,m),v,{consume:i,count:a,now:this.now(),reserve:e.reserve??!1});if(u!==void 0&&await this.store.set(c,u),!h.ok&&e.throws)throw new w(h);return h}}export{z as RateLimiter};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as M}from"@lunora/errors";const l=r=>r.capacity??r.rate,v=(r,e)=>{throw new M("INTERNAL",`@lunora/ratelimit: requested count ${String(r)} exceeds the limiter capacity ${String(e)}`)},f=(r,e,t)=>{const o=l(r),u=r.rate/r.period,n=e??{ts:t,value:o},a=Math.max(0,t-n.ts);return{available:Math.min(o,n.value+a*u),capacity:o,ratePerMs:u}},w=(r,e,t)=>{const o=r.start??0,u=o+Math.floor((t-o)/r.period)*r.period;if(!e||e.ts<u){let n=0;return e&&(e.value<0||r.capacity!==void 0)&&(n=e.value),{ts:u,value:Math.min(l(r),n+r.rate)}}return{ts:e.ts,value:e.value}},k=(r,e,t)=>{const o=r.start??0,u=o+Math.floor((t-o)/r.period)*r.period,n=t-u,a=(r.period-n)/r.period;let s=0,i=0;return e?.ts===u?(s=e.prev??0,i=e.value):e?.ts===u-r.period&&(s=e.value),{currentCount:i,elapsed:n,previousCount:s,weight:a,windowStart:u}},A=(r,e,t)=>{const{available:o,capacity:u,ratePerMs:n}=f(r,e,t.now);if(o>=t.count){const i={ts:t.now,value:o-t.count};return{status:{ok:!0,retryAfter:0},value:t.consume?i:void 0}}const a=t.count-o,s=Math.ceil(a/n);return t.consume&&t.reserve&&t.count<=u?{status:{ok:!0,retryAfter:s},value:{ts:t.now,value:o-t.count}}:(t.count>u&&v(t.count,u),{status:{ok:!1,reason:"rate",retryAfter:s},value:void 0})},b=(r,e,t)=>{const o=l(r),u=w(r,e,t.now);if(u.value>=t.count){const a={ts:u.ts,value:u.value-t.count};return{status:{ok:!0,retryAfter:0},value:t.consume?a:void 0}}const n=u.ts+r.period-t.now;return t.consume&&t.reserve&&t.count<=o?{status:{ok:!0,retryAfter:n},value:{ts:u.ts,value:u.value-t.count}}:(t.count>o&&v(t.count,o),{status:{ok:!1,reason:"rate",retryAfter:n},value:void 0})},g=(r,e,t)=>{const o=r.rate,{period:u}=r,{currentCount:n,elapsed:a,previousCount:s,weight:i,windowStart:h}=k(r,e,t.now),d=s*i+n+t.count<=o,p=()=>{const c=o-n-t.count;if(s>0&&c>=0)return Math.ceil(u-a-c*u/s);const m=o-t.count,y=n>0?Math.max(0,u-m*u/n):0;return Math.ceil(u-a+y)};if(d||t.consume&&t.reserve&&t.count<=o){const c={prev:s,ts:h,value:n+t.count};return{status:{ok:!0,retryAfter:d?0:p()},value:t.consume?c:void 0}}return t.count>o&&v(t.count,o),{status:{ok:!1,reason:"rate",retryAfter:p()},value:void 0}},x=(r,e,t)=>{if(r.kind==="token bucket")return{ts:t,value:f(r,e,t).available};if(r.kind==="sliding window"){const{currentCount:o,previousCount:u,weight:n,windowStart:a}=k(r,e,t);return{ts:a,value:Math.max(0,r.rate-(u*n+o))}}return w(r,e,t)},S=(r,e,t)=>r.kind==="token bucket"?A(r,e,t):r.kind==="sliding window"?g(r,e,t):b(r,e,t);export{x as availableAt,S as evaluate};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const p=()=>{const t=new Map;return{delete:e=>{t.delete(e)},get:e=>t.get(e),set:(e,s)=>{t.set(e,s)}}},u=(t,e,...s)=>t.exec.call(t,e,...s).toArray(),y=t=>{const{sql:e}=t,s=t.table??"_lunora_rate_limits";return u(e,`CREATE TABLE IF NOT EXISTS "${s}" (k TEXT PRIMARY KEY, value REAL NOT NULL, ts INTEGER NOT NULL, prev REAL)`),{delete:n=>{u(e,`DELETE FROM "${s}" WHERE k = ?`,n)},get:n=>{const l=u(e,`SELECT value, ts, prev FROM "${s}" WHERE k = ?`,n)[0];if(!l)return;const c={ts:l.ts,value:l.value};return l.prev!==null&&(c.prev=l.prev),c},set:(n,l)=>{u(e,`INSERT INTO "${s}" (k, value, ts, prev) VALUES (?, ?, ?, ?) ON CONFLICT(k) DO UPDATE SET value = excluded.value, ts = excluded.ts, prev = excluded.prev`,n,l.value,l.ts,l.prev??null)}}},E=t=>{const{db:e}=t,s=t.table??"rateLimits",n=t.index??"by_key",l=t.keyField??"key",c=new Map,o=async a=>{const r=await e.query(s).withIndex(n,i=>i.eq(l,a)).first();return c.set(a,r?r._id:void 0),r},v=async a=>(c.has(a)||await o(a),c.get(a));return{delete:async a=>{const r=await v(a);r!==void 0&&await e.delete(r),c.delete(a)},get:async a=>{const r=await o(a);if(!r)return;const i={ts:r.ts,value:r.value};return r.prev!==null&&r.prev!==void 0&&(i.prev=r.prev),i},set:async(a,r)=>{const i=await v(a),d={[l]:a,ts:r.ts,value:r.value};r.prev!==void 0&&(d.prev=r.prev),i===void 0?c.set(a,await e.insert(s,d)):await e.patch(i,d)}}},b=t=>{const e=n=>{throw new Error(`@lunora/ratelimit: \`${n}\` needs a writable \`ctx.db\`, but this store was created with \`createReadOnlyDbStore\` (a query context). Use \`createDbStore\` from a mutation or action; a query can only call \`getValue\`/\`check\`.`)},s=E({...t,db:{delete:()=>e("delete"),insert:()=>e("insert"),patch:()=>e("patch"),query:t.db.query.bind(t.db)}});return{delete:()=>e("reset"),get:s.get,set:()=>e("limit")}};export{E as createDbStore,p as createMemoryStore,b as createReadOnlyDbStore,y as createSqlStore};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{rateLimit as a}from"./rateLimit-DLcwK-84.mjs";import{RateLimiter as i}from"./RateLimiter-CitqoGTI.mjs";import{createDbStore as m}from"./createDbStore-CwJBMxDQ.mjs";const p=(t,o,r={})=>a(e=>new i({config:t,store:m({db:e.db,...r.store})}),o,r);export{p as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as f,isInternalCode as l,LunoraError as c}from"@lunora/errors";const u={deny:{code:"FORBIDDEN",status:403},rate:{code:"TOO_MANY_REQUESTS",status:429}},m=(r,a,e)=>a==="deny"?`request denied for "${r}"`:e===void 0?`rate limit "${r}" exceeded`:`rate limit "${r}" exceeded; retry after ${String(e)}ms`,A=(r,a,e={})=>async({ctx:n,next:s})=>{let i;try{i=await(typeof r=="function"?await r(n):r).limit(a,{count:e.count,key:e.key?.(n)})}catch(t){if(f(t)&&l(t.code))throw t;if(console.error(`@lunora/ratelimit: rateLimit("${a}") threw; ${e.failOpen?"failing open":"failing closed"}`,t),e.failOpen)return s();throw new c("SERVICE_UNAVAILABLE",`rate limiter unavailable for "${a}"`,{cause:t,status:503})}if(!i.ok){const t=i.reason??"rate",d=u[t],o=Number.isFinite(i.retryAfter)?Math.ceil(i.retryAfter):void 0;throw new c(d.code,e.message??m(a,t,o),{status:d.status,data:o===void 0?void 0:{retryAfter:o}})}return s()};export{u as STATUS_BY_REASON,A as rateLimit};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const r=t=>({key:"ratelimit",middleware:async({ctx:i,next:a})=>{const n=typeof t=="function"?await t(i):t,e=i.api??{};return a({ctx:{api:{...e,ratelimit:n}}})}});export{r as ratelimitPlugin};
|