@vllnt/convex-quota 0.1.1-canary.eb7c0b5 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,7 +4,7 @@ All notable changes to this project are documented here. The format is based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
- ## [Unreleased]
7
+ ## [0.1.1] - 2026-11-29
8
8
 
9
9
  ### Added
10
10
 
@@ -14,16 +14,27 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
14
14
  version. `llms.txt` links shipped files with relative paths and adds an
15
15
  Ecosystem link; the README adds Related packages. `docs/API.md` lists the
16
16
  package entry points and exported types.
17
- - `pnpm check:pack` fails when a required file is missing from the tarball or a
18
- relative `llms.txt` link does not resolve inside it.
17
+ - The README is rewritten for coding agents: install and a quick start first, an
18
+ API table linked to `docs/API.md`, common tasks, an errors-and-fixes table for
19
+ every `ConvexError` code, limits and gotchas, and compatibility. `docs/API.md`
20
+ documents every public export with its signature, defaults, result shape and
21
+ error codes; `llms.txt` carries the same summary and ends with an Ecosystem
22
+ block. The README shows a listing image.
23
+ - Every public export and `Quota` method has a TSDoc summary.
19
24
 
20
25
  ### Changed
21
26
 
22
27
  - `homepage` points to https://oss.vllnt.com/packages/convex-quota.
23
- - Every push to `main` that touches the package or its shipped docs publishes a
24
- `canary`, with no repository-variable gate.
28
+ - The `package.json` description and keywords name the problem and the stack
29
+ (Convex, TypeScript, quota, allowance, reset windows).
30
+ - A `canary` build is published to npm on every push to `main`.
25
31
  - `refund` skips the write when the allowance's `used` would not change (already
26
32
  zero), so a no-op refund no longer re-runs `remaining` subscribers.
33
+ - Internal: dev dependencies upgraded; CI sets up pnpm through Corepack with
34
+ pinned actions and no update bot; `pnpm lint` checks the docs; `pnpm check:pack`
35
+ checks required tarball files, `llms.txt` links and every TypeScript doc
36
+ example against the packed package; tests cover every public function's
37
+ documented behaviour and failure path.
27
38
 
28
39
  ## [0.1.0] - 2026-11-23
29
40
 
package/README.md CHANGED
@@ -1,66 +1,32 @@
1
- <!-- Badges -->
2
-
3
- [![convex-component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
4
- [![npm](https://img.shields.io/npm/v/@vllnt/convex-quota.svg)](https://www.npmjs.com/package/@vllnt/convex-quota)
5
- [![CI](https://github.com/vllnt/convex-quota/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-quota/actions/workflows/ci.yml)
6
- [![license](https://img.shields.io/npm/l/@vllnt/convex-quota.svg)](./LICENSE)
7
-
8
1
  # @vllnt/convex-quota
9
2
 
10
- Scheduled-reset per-subject allowances as a Convex component.
3
+ TypeScript Convex component for quotas and allowances: daily, weekly, monthly, rolling or epoch reset windows per user or key, with a readable remaining count.
11
4
 
12
- Readable remaining in a window — calendar day/week/month, rolling, or epoch.
13
- Daily/weekly play caps, free-tier slots, Codex-style limits.
5
+ ## For coding agents
14
6
 
15
- ## When to use it
7
+ Docs for the installed version ship in the package: `README.md`, `CHANGELOG.md`, `llms.txt`, `docs/API.md` and typed `src/` under `node_modules/@vllnt/convex-quota/`. Read them before writing code.
16
8
 
17
- Use it for allowances that reset on a schedule and that your UI needs to read:
18
- "3 plays left today", a weekly cap in the subject's own timezone, free-tier
19
- slots, a refund when an action is cancelled. For other needs, see
20
- [Related packages](#related-packages).
9
+ ## When to use
21
10
 
22
- ```ts
23
- const quota = new Quota(components.quota);
24
- const r = await quota.consume(ctx, subjectRef, "plays", 3, {
25
- kind: "calendar",
26
- period: "day",
27
- timeZone: "Europe/Paris",
28
- });
29
- if (!r.allowed) throw new Error(`try again at ${r.resetsAt}`);
30
- ```
11
+ Use it when:
31
12
 
32
- ## Features
13
+ - A user, API key or tenant gets a number of actions per calendar day, week or month in a given IANA timezone, and the UI shows how many are left and when they reset.
14
+ - An allowance resets on a rolling duration that starts at first use, or on fixed epoch-aligned buckets such as every hour.
15
+ - A cancelled action should give its units back within the same window.
33
16
 
34
- - **Readable remaining** — `consume` and `remaining` both return
35
- `{ used, remaining, limit, periodKey, resetsAt }`; only `consume` includes
36
- `allowed`.
37
- - **Window kinds** — calendar (`day` / `week` / `month` + IANA timezone),
38
- rolling (from first allowed consume), epoch (`floor(now / durationMs)`).
39
- - **Server-sourced time** — window math uses `Date.now()` inside the component.
40
- - **Opaque refs** — `subjectRef`, `key`, and `scope` are host strings (1..256
41
- UTF-16 code units).
42
- - **Bounded erase** — `eraseSubject` deletes in batches and reschedules until
43
- clean.
44
- - **Scopes** — default `"global"`, or namespace per tenant / product.
17
+ Do not use it when:
45
18
 
46
- ## For coding agents
47
-
48
- The docs are bundled in the npm package at
49
- `node_modules/@vllnt/convex-quota/docs/`, with `README.md`, `CHANGELOG.md` and
50
- `llms.txt` in the package root and the TypeScript sources in `src/`. They match
51
- the installed version. Read them before writing code.
19
+ - You need throttling or rate limiting of bursts: use `@convex-dev/rate-limiter`.
20
+ - The count never resets: a balance that is spent and topped up (`@vllnt/convex-wallet`), or an API key's lifetime use limit (`@vllnt/convex-api-keys`).
21
+ - You need billable usage records rolled up per billing period: use `@vllnt/convex-metering`.
52
22
 
53
- ## Installation
23
+ ## Install
54
24
 
55
25
  ```bash
56
26
  pnpm add @vllnt/convex-quota
57
27
  ```
58
28
 
59
- Node.js >=22.12.0; required peer: `convex@^1.45.0`. Stable releases are
60
- published to the `latest` dist-tag with npm provenance. Unreleased builds from
61
- `main` go to the `canary` dist-tag (`pnpm add @vllnt/convex-quota@canary`).
62
-
63
- ## Usage
29
+ ## Quick start
64
30
 
65
31
  ```ts
66
32
  // convex/convex.config.ts
@@ -72,15 +38,12 @@ app.use(quota);
72
38
  export default app;
73
39
  ```
74
40
 
75
- The host authenticates, derives the `subjectRef`, and owns the limit and window.
76
- The component never sees the end-user's request.
77
-
78
41
  ```ts
79
42
  // convex/plays.ts
80
43
  import { v } from "convex/values";
44
+ import { Quota } from "@vllnt/convex-quota";
81
45
  import { components } from "./_generated/api";
82
46
  import { mutation, query } from "./_generated/server";
83
- import { Quota } from "@vllnt/convex-quota";
84
47
 
85
48
  const quota = new Quota(components.quota);
86
49
  const DAILY_PLAYS = 5; // host-owned, never from the client
@@ -96,9 +59,14 @@ export const play = mutation({
96
59
  handler: async (ctx) => {
97
60
  const identity = await ctx.auth.getUserIdentity();
98
61
  if (!identity) throw new Error("Unauthenticated");
99
- const subjectRef = identity.tokenIdentifier;
100
- const r = await quota.consume(ctx, subjectRef, "plays", DAILY_PLAYS, daily);
101
- if (!r.allowed) throw new Error("daily cap reached");
62
+ const r = await quota.consume(
63
+ ctx,
64
+ identity.tokenIdentifier,
65
+ "plays",
66
+ DAILY_PLAYS,
67
+ daily,
68
+ );
69
+ if (!r.allowed) throw new Error(`Daily cap reached until ${r.resetsAt}`);
102
70
  return null;
103
71
  },
104
72
  });
@@ -121,70 +89,131 @@ export const playsLeft = query({
121
89
  });
122
90
  ```
123
91
 
124
- After mounting, run `pnpm convex dev` to generate the host's component
125
- references.
126
-
127
- **Host rules:**
128
-
129
- - Never take `limit` or `amount` from the end-user. The host supplies them.
130
- - `consume` is not idempotent. Pair it with `@vllnt/convex-idempotency` (see
131
- [Retries and idempotency](#retries-and-idempotency)).
132
- - `refund` is privileged and **not idempotent**. Deduplicate refund events in
133
- the host transaction; `periodKey` is a window label, not a receipt or replay
134
- token.
135
- - Keep window policy fixed for each `(scope, subjectRef, key)`; changes throw
136
- `POLICY_MISMATCH`. Use a new key for a new policy. Limits may change without
137
- resetting usage.
138
- - Stop new consumes before erasing a subject and keep them stopped until
139
- scheduled passes drain. Erasure is not a tombstone; concurrent writes can
140
- survive or be swept.
141
- - The example wrappers are unauthenticated test fixtures, not production
142
- endpoints.
143
-
144
- ## Configuration and limits
145
-
146
- `new Quota(component, { defaultScope: "global" })` sets the only client option.
147
- `consume` accepts `{ amount?: number, scope?: string }`; amount defaults to 1.
148
- Limits and amounts must be positive safe integers. Erase batches default to 200
149
- and are capped at 500. Calendar weeks default to Monday; set `weekStartsOn` to
150
- `"sunday"` when needed. Rolling and epoch windows require a positive safe
151
- integer `durationMs`. See the API reference for timezone transitions and error
152
- codes.
153
-
154
- ## API Reference
155
-
156
- | Method | Kind | Result |
157
- | --------------------------------------------------------- | -------- | ---------------------------------------------------------- |
158
- | `consume(ctx, subjectRef, key, limit, window, opts?)` | mutation | `{ allowed, remaining, used, limit, periodKey, resetsAt }` |
159
- | `remaining(ctx, subjectRef, key, limit, window, scope?)` | query | same fields without `allowed` |
160
- | `refund(ctx, subjectRef, key, amount, periodKey, scope?)` | mutation | `{ refunded, used, remaining }` |
161
- | `eraseSubject(ctx, subjectRef, scope?, batch?)` | mutation | `number` deleted this pass |
162
-
163
- Full reference: [docs/API.md](docs/API.md).
164
-
165
- ## Retries and idempotency
166
-
167
- `consume` is not idempotent: a retried mutation consumes again. When a retry
168
- must not double-count, claim the request with `@vllnt/convex-idempotency` inside
169
- the **same host mutation**. The claim, the consume and the completion commit or
170
- roll back together, so a failed attempt leaves nothing behind and a successful
171
- one is replayed instead of re-run.
172
-
173
- Install it next to this component:
92
+ ![Quotas — @vllnt/convex-quota](https://raw.githubusercontent.com/vllnt/convex-quota/main/.github/assets/thumbnail.png)
174
93
 
175
- ```bash
176
- pnpm add @vllnt/convex-idempotency
94
+ Run `npx convex dev` after mounting so `components.quota` is generated. The host
95
+ authenticates, derives the `subjectRef` (here the caller's `tokenIdentifier`)
96
+ and owns the limit and the window; the component never sees the end user's
97
+ request.
98
+
99
+ [![Convex component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
100
+ [![npm version](https://img.shields.io/npm/v/@vllnt/convex-quota.svg)](https://www.npmjs.com/package/@vllnt/convex-quota)
101
+ [![CI status](https://github.com/vllnt/convex-quota/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-quota/actions/workflows/ci.yml)
102
+ [![MIT license](https://img.shields.io/npm/l/@vllnt/convex-quota.svg)](./LICENSE)
103
+
104
+ ## API
105
+
106
+ Full reference: [docs/API.md](./docs/API.md).
107
+
108
+ | Export | Kind | What it does |
109
+ | ----------------------------------------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------- |
110
+ | [`Quota`](./docs/API.md#quota) | class (`@vllnt/convex-quota`) | Client: `new Quota(components.quota, options?)` |
111
+ | [`consume`](./docs/API.md#consume) | method, `runMutation` ctx | Use `amount` units if they fit; returns `{ allowed, used, remaining, limit, periodKey, resetsAt }` |
112
+ | [`remaining`](./docs/API.md#remaining) | method, `runQuery` ctx | Read the current window without writing; returns `{ used, remaining, limit, periodKey, resetsAt }` |
113
+ | [`refund`](./docs/API.md#refund) | method, `runMutation` ctx | Give units back to the stored, unexpired window; returns `{ refunded, used, remaining }` |
114
+ | [`eraseSubject`](./docs/API.md#erasesubject) | method, `runMutation` ctx | Delete a subject's rows in one scope in batches; returns the count deleted in the first pass |
115
+ | [`QuotaOptions`](./docs/API.md#quotaoptions) | type | Constructor options: `{ defaultScope?: string }` |
116
+ | [`ConsumeOptions`](./docs/API.md#consumeoptions) | type | `consume` options: `{ amount?: number; scope?: string }` |
117
+ | [`WindowSpec`](./docs/API.md#windowspec) | type | Window policy: `calendar` (`day` / `week` / `month` in a timezone), `rolling` or `epoch` |
118
+ | [`ConsumeResult`](./docs/API.md#consumeresult) | type | Return type of `consume` |
119
+ | [`RemainingState`](./docs/API.md#remainingstate) | type | Return type of `remaining` |
120
+ | [`RefundResult`](./docs/API.md#refundresult) | type | Return type of `refund` |
121
+ | [`QuotaComponent`](./docs/API.md#quotacomponent) | type | The function references the client needs (`components.quota`) |
122
+ | [`convex.config` default](./docs/API.md#convexconfig) | component (`/convex.config`) | The component definition for `app.use(...)`, mounted as `quota` by default |
123
+ | [`register`](./docs/API.md#register) | function (`/test`) | `register(t, name = "quota")` mounts the component in a `convex-test` instance |
124
+ | [`ComponentApi`](./docs/API.md#componentapi) | type (`/_generated/component`) | Generated type of the mounted component's functions |
125
+
126
+ ## Common tasks
127
+
128
+ **Pick a window.** A `WindowSpec` is fixed per `(scope, subjectRef, key)`:
129
+
130
+ ```ts
131
+ // convex/windows.ts
132
+ import type { WindowSpec } from "@vllnt/convex-quota";
133
+
134
+ // Resets at local midnight in Paris.
135
+ export const daily: WindowSpec = {
136
+ kind: "calendar",
137
+ period: "day",
138
+ timeZone: "Europe/Paris",
139
+ };
140
+ // Resets on Sunday at local midnight (the default week start is Monday).
141
+ export const weekly: WindowSpec = {
142
+ kind: "calendar",
143
+ period: "week",
144
+ timeZone: "America/New_York",
145
+ weekStartsOn: "sunday",
146
+ };
147
+ // Resets on the 1st of each month at UTC midnight.
148
+ export const monthly: WindowSpec = {
149
+ kind: "calendar",
150
+ period: "month",
151
+ timeZone: "UTC",
152
+ };
153
+ // 24 hours from the first allowed consume.
154
+ export const rolling: WindowSpec = { kind: "rolling", durationMs: 86_400_000 };
155
+ // Fixed hourly buckets aligned to the Unix epoch.
156
+ export const hourly: WindowSpec = { kind: "epoch", durationMs: 3_600_000 };
157
+ ```
158
+
159
+ **Consume several units or use a tenant scope.** Pass `{ amount, scope }` as
160
+ the last argument of `consume`, or set `defaultScope` once with
161
+ `new Quota(components.quota, { defaultScope: "tenant-a" })`. `remaining`,
162
+ `refund` and `eraseSubject` take `scope` as their last optional argument.
163
+
164
+ ```ts
165
+ // convex/exports.ts
166
+ import { v } from "convex/values";
167
+ import { Quota } from "@vllnt/convex-quota";
168
+ import { components } from "./_generated/api";
169
+ import { mutation } from "./_generated/server";
170
+
171
+ const quota = new Quota(components.quota);
172
+ const MONTHLY_CREDITS = 100;
173
+ const EXPORT_COST = 10; // host-owned, never from the client
174
+ const monthly = { kind: "calendar", period: "month", timeZone: "UTC" } as const;
175
+
176
+ export const startExport = mutation({
177
+ args: {},
178
+ returns: v.object({ allowed: v.boolean(), remaining: v.number() }),
179
+ handler: async (ctx) => {
180
+ const identity = await ctx.auth.getUserIdentity();
181
+ if (!identity) throw new Error("Unauthenticated");
182
+ const { allowed, remaining } = await quota.consume(
183
+ ctx,
184
+ identity.tokenIdentifier,
185
+ "credits",
186
+ MONTHLY_CREDITS,
187
+ monthly,
188
+ { amount: EXPORT_COST, scope: "exports" },
189
+ );
190
+ return { allowed, remaining };
191
+ },
192
+ });
177
193
  ```
178
194
 
195
+ An `amount` larger than what is left is denied in full; nothing is consumed
196
+ partially.
197
+
198
+ **Make `consume` and `refund` retry-safe.** `consume` and `refund` are not
199
+ idempotent: a retried mutation consumes again. Claim the request with
200
+ `@vllnt/convex-idempotency` inside the same host mutation; the claim, the
201
+ consume and the completion commit or roll back together. Mount both components:
202
+
179
203
  ```ts
180
- // convex/convex.config.ts — mount both components
204
+ // convex/convex.config.ts
205
+ import { defineApp } from "convex/server";
181
206
  import idempotency from "@vllnt/convex-idempotency/convex.config";
207
+ import quota from "@vllnt/convex-quota/convex.config";
208
+
209
+ const app = defineApp();
182
210
  app.use(quota);
183
211
  app.use(idempotency);
212
+ export default app;
184
213
  ```
185
214
 
186
215
  ```ts
187
- // convex/plays.ts
216
+ // convex/safe_plays.ts
188
217
  import { v } from "convex/values";
189
218
  import { Idempotency } from "@vllnt/convex-idempotency";
190
219
  import {
@@ -199,6 +228,7 @@ const quota = new Quota(components.quota);
199
228
  const consumeIdempotency = new Idempotency<ConsumeResult>(
200
229
  components.idempotency,
201
230
  );
231
+ const refundIdempotency = new Idempotency<RefundResult>(components.idempotency);
202
232
  const DAILY_PLAYS = 5;
203
233
  const daily = {
204
234
  kind: "calendar",
@@ -242,21 +272,15 @@ export const play = mutation({
242
272
  return result;
243
273
  },
244
274
  });
245
- ```
246
-
247
- Refunds are privileged; trigger them only from verified host events. Expose them
248
- as an `internalMutation` that a trusted caller (a webhook or a scheduled job
249
- after a verified cancellation) invokes with values from the host's own record of
250
- the play, never with a public argument chosen by the end user:
251
-
252
- ```ts
253
- const refundIdempotency = new Idempotency<RefundResult>(components.idempotency);
254
275
 
276
+ // Privileged: only trusted host code (a webhook handler or a scheduled job
277
+ // after a verified cancellation) calls this, with values from the host's own
278
+ // record of the play, never from an end-user argument.
255
279
  export const refundPlay = internalMutation({
256
280
  args: {
257
- subjectRef: v.string(), // from the host's record of the play
258
- requestId: v.string(), // the request being cancelled
259
- periodKey: v.string(), // from the same record
281
+ subjectRef: v.string(),
282
+ requestId: v.string(),
283
+ periodKey: v.string(),
260
284
  },
261
285
  returns: v.object({
262
286
  refunded: v.boolean(),
@@ -282,115 +306,212 @@ export const refundPlay = internalMutation({
282
306
  });
283
307
  ```
284
308
 
285
- This exact pattern is exercised in
309
+ The same `play` and `refundPlay` are tested in
286
310
  [`example/convex/idempotency.test.ts`](https://github.com/vllnt/convex-quota/blob/main/example/convex/idempotency.test.ts):
287
311
  a duplicate `requestId` replays the stored result and consumes once, a new
288
- `requestId` consumes again, the caller `scope` isolates identical request ids, a
289
- host failure after `consume` rolls back both the allowance and the claim, and a
290
- refund event deduplicated by `requestId` refunds once.
291
-
292
- Caveats:
312
+ `requestId` consumes again, the caller `scope` isolates identical request IDs,
313
+ a host failure after `consume` rolls back both the allowance and the claim, and
314
+ a refund deduplicated by `requestId` refunds once. Caveats:
293
315
 
294
316
  - A denied consume (`allowed: false`) is recorded too, so a replay returns the
295
- same denial even if the allowance was freed in between.
296
- - The claim lives for the idempotency component's done-grace TTL (24 hours by
297
- default). A retry after that is a new request and consumes again, so pick a
298
- TTL longer than your clients' retry horizon.
299
- - Do no external work between `begin` and `complete`. Keep it to transactional
300
- host writes; use a separate action for network calls.
317
+ same denial even if units were freed in between.
318
+ - The claim lives for the idempotency component's done grace (24 hours by
319
+ default). A retry after that is a new request and consumes again.
320
+ - Do no external work between `begin` and `complete`; use a separate action
321
+ for network calls.
301
322
  - Namespace the idempotency key per operation (`consume:${requestId}`,
302
- `refund:${requestId}`). The ledger is keyed by caller scope and key only, so
303
- two operations sharing a key would replay each other's stored result.
304
- - Never accept refund ids or a `periodKey` from the end user: a public refund
323
+ `refund:${requestId}`). The ledger is keyed by scope and key only, so two
324
+ operations sharing a key would replay each other's stored result.
325
+ - Never accept refund IDs or a `periodKey` from the end user: a public refund
305
326
  endpoint lets a caller fabricate cancellations and clear their own quota.
306
327
 
307
- ## Multiple mounts
328
+ **Mount the component more than once.** Each named mount has its own tables:
308
329
 
309
330
  ```ts
331
+ // convex/convex.config.ts
332
+ import { defineApp } from "convex/server";
333
+ import quota from "@vllnt/convex-quota/convex.config";
334
+
335
+ const app = defineApp();
310
336
  app.use(quota, { name: "webQuota" });
311
337
  app.use(quota, { name: "mobileQuota" });
312
- // new Quota(components.webQuota), new Quota(components.mobileQuota)
338
+ export default app;
313
339
  ```
314
340
 
315
- Each mount has independent sandboxed tables. Use `scope` for runtime namespaces.
316
-
317
- ## Operational behavior
318
-
319
- `remaining` is a snapshot when its query executes: **time passing alone does not
320
- invalidate a Convex subscription**. Treat `resetsAt` as an expiry hint, not a
321
- scheduled notification; `consume` always rechecks server time. Rolling windows
322
- start on the first **allowed** consume. No history or audit events are retained.
323
- Hosts should record denied decisions and privileged refunds in their own audit
324
- system without logging sensitive refs. A hot allowance is one contended row;
325
- different indexed keys remain independent. Monitor Convex OCC retries and
326
- scheduled-function failures. Erasure returns only its first pass count.
327
-
328
- ## React
329
-
330
- Backend-only — no `./react` entry. Remaining is typically shown through the
331
- host's own query.
332
-
333
- ## Security
341
+ ```ts
342
+ // convex/mounts.ts
343
+ import { Quota } from "@vllnt/convex-quota";
344
+ import { components } from "./_generated/api";
334
345
 
335
- - Auth-agnostic — the host resolves identity and passes an opaque `subjectRef`.
336
- - Tables sandboxed — reached only through the exported functions.
337
- - Server-sourced windows — a skewed client clock cannot pick the period.
346
+ export const webQuota = new Quota(components.webQuota);
347
+ export const mobileQuota = new Quota(components.mobileQuota);
348
+ ```
338
349
 
339
- See [docs/API.md](docs/API.md).
350
+ Use `scope` instead when you need namespaces at runtime inside one mount.
351
+
352
+ **Erase a subject.** `quota.eraseSubject(ctx, subjectRef, scope?, batch?)`
353
+ deletes that subject's rows in one scope and schedules further passes until a
354
+ pass deletes fewer than `batch` rows. Stop new consumes for the subject first.
355
+
356
+ **Show the remaining count in a UI.** Read it through your own query, as
357
+ `playsLeft` does in the [Quick start](#quick-start). There is no React entry
358
+ point. A subscription does not refresh when the window resets on its own; use
359
+ `resetsAt` to know when to read again.
360
+
361
+ **Test your app.** Mount the component in `convex-test`; see
362
+ [Testing your app](#testing-your-app).
363
+
364
+ ## Errors and fixes
365
+
366
+ Invalid input throws a `ConvexError` whose `data` is `{ code, message }`:
367
+
368
+ | Error (`data.code`) | Message | Cause | Fix |
369
+ | ------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
370
+ | `INVALID_REF` | `subjectRef must be 1..256 UTF-16 code units` (or `key`, `scope`, `periodKey`) | An empty string or more than 256 UTF-16 code units in `subjectRef`, `key`, `scope` or the refund `periodKey` | Pass a non-empty value of at most 256 code units; hash longer identifiers |
371
+ | `INVALID_LIMIT` | `limit must be a positive safe integer` | `consume` or `remaining` got a `limit` that is 0, negative, fractional, `NaN`, infinite or above `Number.MAX_SAFE_INTEGER` | Pass a positive integer limit from host config |
372
+ | `INVALID_AMOUNT` | `amount must be a positive safe integer` | `consume` or `refund` got an `amount` that is 0, negative, fractional or not a safe integer | Pass a positive integer, or omit it on `consume` (default 1) |
373
+ | `INVALID_DURATION` | `durationMs must be a positive safe integer` | A `rolling` or `epoch` window has a `durationMs` that is 0, negative, fractional or not a safe integer | Pass whole milliseconds, for example `86_400_000` for one day |
374
+ | `INVALID_DURATION` | `window end must be a positive safe integer` | The server time plus `durationMs` is above `Number.MAX_SAFE_INTEGER` | Use a shorter `durationMs` |
375
+ | `INVALID_TIME_ZONE` | the `timeZone` value, for example `Not/AZone` | A `calendar` window's `timeZone` is not accepted by `Intl.DateTimeFormat` | Pass an IANA name such as `Europe/Paris` or `UTC` |
376
+ | `INVALID_BATCH` | `batch must be a positive integer` | `eraseSubject` got a `batch` that is 0, negative, fractional, `NaN` or infinite | Pass a positive integer or omit it (default 200); values above 500 are capped to 500 |
377
+ | `POLICY_MISMATCH` | `Use a new key to change window policy` | `consume` or `remaining` got a different window policy than the stored row for this `(scope, subjectRef, key)` | Keep the window fixed per key, or use a new `key` for the new policy |
378
+
379
+ ## Limits and gotchas
380
+
381
+ - Defaults: `scope` `"global"`, `amount` 1, `weekStartsOn` `"monday"`,
382
+ `eraseSubject` batch 200. A batch above 500 is capped to 500, not rejected.
383
+ - Refs (`subjectRef`, `key`, `scope`, refund `periodKey`) are 1 to 256 UTF-16
384
+ code units. Limits and amounts are positive safe integers. Durations are
385
+ positive safe integer milliseconds.
386
+ - `consume` and `refund` are not idempotent. A retried mutation consumes or
387
+ refunds again; see [Common tasks](#common-tasks) for the idempotency pattern.
388
+ - A denied `consume` writes nothing: it does not start a rolling window and
389
+ does not store the new limit. An `amount` above what is left is denied in full.
390
+ - The window policy is fixed per `(scope, subjectRef, key)`. Changing the kind,
391
+ `durationMs`, calendar `period`, `timeZone` spelling, or the week start of a
392
+ `week` window throws `POLICY_MISMATCH`, even after the window expired. The
393
+ limit may change at any time without resetting usage; a lower limit can
394
+ return `used` above `limit` with `remaining: 0`.
395
+ - `refund` only applies when `periodKey` matches the stored row and that window
396
+ has not ended. Otherwise it returns `refunded: false` with the stored row's
397
+ `used` and `remaining` (zeros if there is no row) and writes nothing. Those
398
+ numbers are not recomputed for the current window.
399
+ - `refund`'s `remaining` uses the limit stored by the last allowed `consume`. A
400
+ refund on a matching row with `used: 0` returns `refunded: true` and writes
401
+ nothing.
402
+ - `remaining` is a query: it never writes, never starts a rolling window, and
403
+ reports an expired row as zero usage. Time passing alone does not invalidate a
404
+ Convex query subscription, so treat `resetsAt` as an expiry hint; `consume`
405
+ always rechecks server time.
406
+ - Rolling windows start at the first allowed `consume`. Epoch windows are
407
+ `floor(now / durationMs)` buckets. Calendar days are not always 24 hours (for
408
+ example 23 or 25 on a DST change); a
409
+ repeated local midnight uses the earlier instant, and a skipped midnight or
410
+ date advances through the gap.
411
+ - `periodKey` is an opaque window label, not a receipt or idempotency token. Do
412
+ not parse it. After `eraseSubject`, the same calendar period can produce the
413
+ same label again, so never replay old refunds against it.
414
+ - `eraseSubject` returns the count from its first pass only and schedules more
415
+ passes while a pass is full, including a possible final empty pass. It is not
416
+ a tombstone: a `consume` that races the sweep can survive or be deleted.
417
+ - One row per `(scope, subjectRef, key)`: concurrent consumes on the same key
418
+ contend on that row (Convex retries conflicting mutations); different keys are independent.
419
+ - No usage history, receipts or audit events are stored. Record denials and
420
+ refunds in your own tables if you need them.
421
+
422
+ ## Compatibility
423
+
424
+ - Peer dependency: `convex@^1.45.0`. CI builds and tests against the locked
425
+ dev version, `convex` 1.51.0.
426
+ - Node: `engines.node` is `>=22.12.0`. The package is ESM only.
427
+ - `@vllnt/convex-quota/test` ships as TypeScript source and needs `convex-test`
428
+ (tested with 0.0.73, which itself needs `convex@^1.46.0`), `vitest` and
429
+ `vite` in your app: it calls Vite's `import.meta.glob`, so add
430
+ `/// <reference types="vite/client" />` to the test file.
431
+ - TypeScript: the packed exports and the `./test` helper type-check under both
432
+ `bundler` and `nodenext` module resolution (`pnpm check:pack`).
433
+ - No React entry point: the package is backend only.
434
+ - Releases: stable versions are published to the `latest` dist-tag with npm
435
+ provenance; builds from `main` go to `canary`
436
+ (`pnpm add @vllnt/convex-quota@canary`).
340
437
 
341
438
  ## Testing
342
439
 
343
440
  ```bash
344
- pnpm test
345
- pnpm test:coverage
441
+ pnpm test # single run
442
+ pnpm test:coverage # 100% enforced on the source files listed in vitest.config.mts
346
443
  ```
347
444
 
348
- Unit/integration tests use the **mock backend** `convex-test`
349
- (`@edge-runtime/vm`). They do not establish real-backend OCC or scheduler
350
- guarantees.
445
+ Tests run the component's real functions in `convex-test`'s in-memory backend
446
+ (`@edge-runtime/vm`), including adversarial input, civil-time transitions and
447
+ scheduled erase batches. They do not prove real Convex OCC retries or real
448
+ scheduler delivery.
351
449
 
352
450
  ### Testing your app
353
451
 
354
452
  `@vllnt/convex-quota/test` exports `register(t, name = "quota")` to mount the
355
- component in a `convex-test` instance. It needs `convex-test` and `vitest` (with
356
- Vite's `import.meta.glob`) in the consuming app:
453
+ component in a `convex-test` instance built from your app's schema:
357
454
 
358
455
  ```ts
456
+ // convex/plays.test.ts
359
457
  /// <reference types="vite/client" />
360
458
  import { convexTest } from "convex-test";
361
459
  import { register } from "@vllnt/convex-quota/test";
460
+ import { expect, test } from "vitest";
461
+ import { api } from "./_generated/api";
362
462
  import schema from "./schema";
363
463
 
364
- const t = convexTest(schema, import.meta.glob("./**/*.ts"));
365
- register(t);
464
+ test("a play uses one unit of the daily allowance", async () => {
465
+ const t = convexTest(schema, import.meta.glob("./**/*.ts"));
466
+ register(t);
467
+ const user = t.withIdentity({ tokenIdentifier: "user|1" });
468
+ await user.mutation(api.plays.play, {});
469
+ const left = await user.query(api.plays.playsLeft, {});
470
+ expect(left.remaining).toBe(4);
471
+ });
472
+ ```
473
+
474
+ ```ts
475
+ // convex/schema.ts
476
+ import { defineSchema } from "convex/server";
477
+
478
+ export default defineSchema({});
366
479
  ```
367
480
 
481
+ ## Security
482
+
483
+ - Auth-agnostic: the host resolves identity and passes an opaque `subjectRef`.
484
+ - Tables are sandboxed: they are reached only through the exported functions.
485
+ - Server-sourced windows: a skewed client clock cannot pick the period.
486
+ - Never take `limit`, `amount`, `scope` or the window from an untrusted caller,
487
+ and call `refund` only from verified host records.
488
+ - The functions in the repository's `example/convex/example.ts` are
489
+ unauthenticated test fixtures, not production endpoints.
490
+
491
+ See [docs/API.md](./docs/API.md).
492
+
368
493
  ## Related packages
369
494
 
370
- | Package | Use it when |
371
- | --------------------------- | -------------------------------------------------------------------------------------------------------------- |
372
- | `@convex-dev/rate-limiter` | You need general throttling (token buckets, fixed windows, React hooks), not a readable allowance. |
373
- | `@vllnt/convex-idempotency` | Retries must not double-count `consume` or `refund` (see [Retries and idempotency](#retries-and-idempotency)). |
374
- | `@vllnt/convex-metering` | You need billable usage records rolled up per billing period. |
375
- | `@vllnt/convex-wallet` | You need a balance that persists and is spent down, not reset on a schedule. |
376
- | `@vllnt/convex-api-keys` | You issue API keys; pass a validated key's ID as `subjectRef` to cap that key's usage per window. |
495
+ - [`@vllnt/convex-idempotency`](https://oss.vllnt.com/packages/convex-idempotency): the example app mounts both components and wraps `quota.consume` and `quota.refund` in `begin` → `complete` inside one host mutation, so a retried request is not counted twice.
377
496
 
378
497
  ## Contributing
379
498
 
380
499
  See
381
500
  [CONTRIBUTING.md](https://github.com/vllnt/convex-quota/blob/main/CONTRIBUTING.md).
382
501
 
383
- ## Author
384
-
385
- Built by [bntvllnt](https://github.com/bntvllnt) ·
386
- [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
502
+ ## Links
387
503
 
388
- If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
504
+ - Docs and changelog: [oss.vllnt.com/packages/convex-quota](https://oss.vllnt.com/packages/convex-quota) · [release feed](https://oss.vllnt.com/packages/convex-quota/rss.xml)
505
+ - All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
506
+ - Source and issues: [GitHub](https://github.com/vllnt/convex-quota) · [issues](https://github.com/vllnt/convex-quota/issues) · [npm](https://www.npmjs.com/package/@vllnt/convex-quota)
507
+ - Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
508
+ - Company and author: [vllnt.com](https://vllnt.com) · [bntvllnt.com](https://bntvllnt.com) · [GitHub @bntvllnt](https://github.com/bntvllnt) · [LinkedIn](https://linkedin.com/in/bntvllnt)
509
+ - Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
389
510
 
390
511
  ## License
391
512
 
392
- MIT — see [LICENSE](LICENSE).
513
+ MIT, see [LICENSE](./LICENSE).
393
514
 
394
515
  ---
395
516
 
396
- Part of vllnt oss: https://oss.vllnt.com
517
+ Part of [vllnt open source](https://oss.vllnt.com) · [Package page](https://oss.vllnt.com/packages/convex-quota) · [vllnt.com](https://vllnt.com) · Built by [bntvllnt](https://bntvllnt.com)