@vllnt/convex-quota 0.1.0-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/LICENSE +21 -0
- package/README.md +158 -0
- package/dist/client/index.d.ts +59 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +58 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/types.d.ts +32 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +3 -0
- package/dist/client/types.js.map +1 -0
- package/dist/component/_generated/api.d.ts +38 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +31 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/component.d.ts +100 -0
- package/dist/component/_generated/component.d.ts.map +1 -0
- package/dist/component/_generated/component.js +11 -0
- package/dist/component/_generated/component.js.map +1 -0
- package/dist/component/_generated/dataModel.d.ts +46 -0
- package/dist/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/component/_generated/dataModel.js +11 -0
- package/dist/component/_generated/dataModel.js.map +1 -0
- package/dist/component/_generated/server.d.ts +133 -0
- package/dist/component/_generated/server.d.ts.map +1 -0
- package/dist/component/_generated/server.js +80 -0
- package/dist/component/_generated/server.js.map +1 -0
- package/dist/component/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +4 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/mutations.d.ts +43 -0
- package/dist/component/mutations.d.ts.map +1 -0
- package/dist/component/mutations.js +164 -0
- package/dist/component/mutations.js.map +1 -0
- package/dist/component/queries.d.ts +25 -0
- package/dist/component/queries.d.ts.map +1 -0
- package/dist/component/queries.js +52 -0
- package/dist/component/queries.js.map +1 -0
- package/dist/component/schema.d.ts +34 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +22 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/component/validators.d.ts +101 -0
- package/dist/component/validators.d.ts.map +1 -0
- package/dist/component/validators.js +61 -0
- package/dist/component/validators.js.map +1 -0
- package/dist/shared.d.ts +66 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +208 -0
- package/dist/shared.js.map +1 -0
- package/docs/API.md +94 -0
- package/llms-full.txt +1324 -0
- package/llms.txt +43 -0
- package/package.json +90 -0
- package/src/client/index.ts +179 -0
- package/src/client/types.ts +37 -0
- package/src/component/_generated/api.ts +54 -0
- package/src/component/_generated/component.ts +114 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +169 -0
- package/src/component/convex.config.ts +5 -0
- package/src/component/mutations.ts +219 -0
- package/src/component/queries.ts +72 -0
- package/src/component/schema.ts +22 -0
- package/src/component/validators.ts +89 -0
- package/src/shared.ts +324 -0
- package/src/test.ts +16 -0
package/llms-full.txt
ADDED
|
@@ -0,0 +1,1324 @@
|
|
|
1
|
+
# @vllnt/convex-quota — Full Source
|
|
2
|
+
|
|
3
|
+
Auto-generated by `pnpm generate:llms`. Do not edit manually.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## README.md
|
|
8
|
+
|
|
9
|
+
<!-- Badges -->
|
|
10
|
+
[](https://www.convex.dev/components)
|
|
11
|
+
[](https://www.npmjs.com/package/@vllnt/convex-quota)
|
|
12
|
+
[](https://github.com/vllnt/convex-quota/actions/workflows/ci.yml)
|
|
13
|
+
[](./LICENSE)
|
|
14
|
+
|
|
15
|
+
# @vllnt/convex-quota
|
|
16
|
+
|
|
17
|
+
Scheduled-reset per-subject allowances as a Convex component.
|
|
18
|
+
|
|
19
|
+
Readable remaining in a window — calendar day/week/month, rolling, or epoch.
|
|
20
|
+
Daily/weekly play caps, free-tier slots, Codex-style limits.
|
|
21
|
+
|
|
22
|
+
The official `@convex-dev/rate-limiter` already supports fixed windows, token
|
|
23
|
+
buckets, readable status and React hooks. Prefer it for general throttling.
|
|
24
|
+
This experimental component explores the narrower calendar/timezone reset and
|
|
25
|
+
privileged allowance-refund surface. It is not billable metering or a persistent
|
|
26
|
+
balance. Publication remains blocked on demonstrated independent consumers and
|
|
27
|
+
justification of this boundary; readable remaining alone is not a distinction.
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
const quota = new Quota(components.quota);
|
|
31
|
+
const r = await quota.consume(ctx, subjectRef, "plays", 3, {
|
|
32
|
+
kind: "calendar",
|
|
33
|
+
period: "day",
|
|
34
|
+
timeZone: "Europe/Paris",
|
|
35
|
+
});
|
|
36
|
+
if (!r.allowed) throw new Error(`try again at ${r.resetsAt}`);
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Features
|
|
40
|
+
|
|
41
|
+
- **Readable remaining** — both return `{ used, remaining, limit, periodKey, resetsAt }`; only `consume` includes `allowed`.
|
|
42
|
+
- **Window kinds** — calendar (`day` / `week` / `month` + IANA timezone), rolling (from first consume), epoch (`floor(now / durationMs)`).
|
|
43
|
+
- **Server-sourced time** — window math uses `Date.now()` inside the component.
|
|
44
|
+
- **Opaque refs** — `subjectRef`, `key`, and `scope` are host strings (1..256 UTF-16 code units).
|
|
45
|
+
- **Bounded erase** — `eraseSubject` deletes in batches and reschedules until clean.
|
|
46
|
+
- **Scopes** — default `"global"`, or namespace per tenant / product.
|
|
47
|
+
|
|
48
|
+
## Installation
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pnpm add @vllnt/convex-quota
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Node.js >=22.12.0; peer dependency: `convex@^1.45.0`.
|
|
55
|
+
|
|
56
|
+
## Usage
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
// convex/convex.config.ts
|
|
60
|
+
import { defineApp } from "convex/server";
|
|
61
|
+
import quota from "@vllnt/convex-quota/convex.config";
|
|
62
|
+
|
|
63
|
+
const app = defineApp();
|
|
64
|
+
app.use(quota);
|
|
65
|
+
export default app;
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { components } from "./_generated/api";
|
|
70
|
+
import { mutation } from "./_generated/server";
|
|
71
|
+
import { Quota } from "@vllnt/convex-quota";
|
|
72
|
+
|
|
73
|
+
const quota = new Quota(components.quota);
|
|
74
|
+
|
|
75
|
+
export const play = mutation({
|
|
76
|
+
args: {},
|
|
77
|
+
handler: async (ctx) => {
|
|
78
|
+
const subjectRef = /* host-resolved identity */ "user_1";
|
|
79
|
+
const r = await quota.consume(ctx, subjectRef, "plays", 5, {
|
|
80
|
+
kind: "calendar",
|
|
81
|
+
period: "day",
|
|
82
|
+
timeZone: "Europe/Paris",
|
|
83
|
+
});
|
|
84
|
+
if (!r.allowed) throw new Error("daily cap reached");
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
**Host rules:**
|
|
90
|
+
|
|
91
|
+
- Never take `limit` or `amount` from the end-user. The host supplies them.
|
|
92
|
+
- `consume` is not idempotent. Wrap retries with `@vllnt/convex-idempotency`.
|
|
93
|
+
- `refund` is privileged and **not idempotent**. Deduplicate refund events in the host transaction; `periodKey` is a window label, not a receipt or replay token.
|
|
94
|
+
- Keep window policy fixed for each `(scope, subjectRef, key)`; changes throw `POLICY_MISMATCH`. Use a new key for a new policy. Limits may change without resetting usage.
|
|
95
|
+
- Stop new consumes before erasing a subject and keep them stopped until scheduled passes drain. Erasure is not a tombstone; concurrent writes can survive or be swept.
|
|
96
|
+
- The example wrappers are unauthenticated test fixtures, not production endpoints.
|
|
97
|
+
|
|
98
|
+
## API Reference
|
|
99
|
+
|
|
100
|
+
| Method | Kind | Result |
|
|
101
|
+
|--------|------|--------|
|
|
102
|
+
| `consume(ctx, subjectRef, key, limit, window, opts?)` | mutation | `{ allowed, remaining, used, limit, periodKey, resetsAt }` |
|
|
103
|
+
| `remaining(ctx, subjectRef, key, limit, window, scope?)` | query | same fields without `allowed` |
|
|
104
|
+
| `refund(ctx, subjectRef, key, amount, periodKey, scope?)` | mutation | `{ refunded, used, remaining }` |
|
|
105
|
+
| `eraseSubject(ctx, subjectRef, scope?, batch?)` | mutation | `number` deleted this pass |
|
|
106
|
+
|
|
107
|
+
Full reference: [docs/API.md](docs/API.md).
|
|
108
|
+
|
|
109
|
+
## Multiple mounts
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
app.use(quota, { name: "webQuota" });
|
|
113
|
+
app.use(quota, { name: "mobileQuota" });
|
|
114
|
+
// new Quota(components.webQuota), new Quota(components.mobileQuota)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Each mount has independent sandboxed tables. Use `scope` for runtime namespaces.
|
|
118
|
+
|
|
119
|
+
## Operational behavior
|
|
120
|
+
|
|
121
|
+
`remaining` is a snapshot when its query executes: **time passing alone does not
|
|
122
|
+
invalidate a Convex subscription**. Treat `resetsAt` as an expiry hint, not a
|
|
123
|
+
scheduled notification; `consume` always rechecks server time. Rolling windows
|
|
124
|
+
start on the first **allowed** consume. No history or audit events are retained.
|
|
125
|
+
Hosts should record denied decisions and privileged refunds in their own audit
|
|
126
|
+
system without logging sensitive refs. A hot allowance is one contended row;
|
|
127
|
+
different indexed keys remain independent. Monitor Convex OCC retries and
|
|
128
|
+
scheduled-function failures. Erasure returns only its first pass count.
|
|
129
|
+
|
|
130
|
+
## React
|
|
131
|
+
|
|
132
|
+
Backend-only — no `./react` entry. Remaining is typically shown through the host's own query.
|
|
133
|
+
|
|
134
|
+
## Security
|
|
135
|
+
|
|
136
|
+
- Auth-agnostic — the host resolves identity and passes an opaque `subjectRef`.
|
|
137
|
+
- Tables sandboxed — reached only through the exported functions.
|
|
138
|
+
- Server-sourced windows — a skewed client clock cannot pick the period.
|
|
139
|
+
|
|
140
|
+
See [docs/API.md](docs/API.md).
|
|
141
|
+
|
|
142
|
+
## Testing
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
pnpm test
|
|
146
|
+
pnpm test:coverage
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Unit/integration tests use the **mock backend** `convex-test` (`@edge-runtime/vm`).
|
|
150
|
+
They do not establish real-backend OCC or scheduler guarantees.
|
|
151
|
+
|
|
152
|
+
## Contributing
|
|
153
|
+
|
|
154
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
155
|
+
|
|
156
|
+
## Author
|
|
157
|
+
|
|
158
|
+
Built by [bntvllnt](https://github.com/bntvllnt) · [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
|
|
159
|
+
|
|
160
|
+
Part of the [@vllnt](https://github.com/vllnt) Convex component fleet — [vllnt.com](https://vllnt.com)
|
|
161
|
+
|
|
162
|
+
If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
|
|
163
|
+
|
|
164
|
+
## License
|
|
165
|
+
|
|
166
|
+
MIT — see [LICENSE](LICENSE).
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
## CHANGELOG.md
|
|
172
|
+
|
|
173
|
+
# Changelog
|
|
174
|
+
|
|
175
|
+
All notable changes to this project are documented here. The format is based on
|
|
176
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
|
|
177
|
+
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
178
|
+
|
|
179
|
+
## [Unreleased]
|
|
180
|
+
|
|
181
|
+
### Added
|
|
182
|
+
|
|
183
|
+
- Initial implementation of `@vllnt/convex-quota` (not yet released).
|
|
184
|
+
- Calendar (day / week / month), rolling, and epoch windows.
|
|
185
|
+
- `consume`, `remaining`, `refund`, `eraseSubject` (batched).
|
|
186
|
+
- Ref length limits (1..256). Server-sourced window math.
|
|
187
|
+
|
|
188
|
+
### Fixed
|
|
189
|
+
|
|
190
|
+
- Reject unsafe numeric allowance values, invalid query inputs, unbounded scopes,
|
|
191
|
+
and overflowing or sub-millisecond durations.
|
|
192
|
+
- Bind each allowance to its window policy and reject policy reinterpretation.
|
|
193
|
+
- Resolve skipped/repeated civil midnights and reject refunds of expired rows.
|
|
194
|
+
- Correct mock-backend testing claims and document refund deduplication,
|
|
195
|
+
subscription expiry, erasure races, and multi-mount behavior.
|
|
196
|
+
|
|
197
|
+
### Migration note
|
|
198
|
+
|
|
199
|
+
- The unreleased allowance schema now requires `policyKey`. Existing development
|
|
200
|
+
rows must be cleared in an isolated development deployment before updating;
|
|
201
|
+
no production migration has been performed.
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
---
|
|
205
|
+
|
|
206
|
+
## docs/API.md
|
|
207
|
+
|
|
208
|
+
# API Reference — @vllnt/convex-quota
|
|
209
|
+
|
|
210
|
+
**Compatibility:** `convex@^1.45.0`
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
import { Quota } from "@vllnt/convex-quota";
|
|
214
|
+
const quota = new Quota(components.quota, { defaultScope: "global" });
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
The host owns authentication, authorization and policy. Never accept identity,
|
|
218
|
+
limit, amount, scope or window policy directly from an untrusted caller.
|
|
219
|
+
`subjectRef`, `key`, `scope`, and refund `periodKey` must be nonempty strings of
|
|
220
|
+
at most 256 UTF-16 code units (`INVALID_REF`). Amounts and limits must be positive
|
|
221
|
+
safe integers (`INVALID_AMOUNT`, `INVALID_LIMIT`). Scope defaults to `"global"`.
|
|
222
|
+
All component errors use `ConvexError({ code, message })`.
|
|
223
|
+
|
|
224
|
+
## Windows
|
|
225
|
+
|
|
226
|
+
- `{ kind: "calendar", period: "day" | "week" | "month", timeZone: string, weekStartsOn?: "monday" | "sunday" }`
|
|
227
|
+
- `{ kind: "rolling", durationMs: number }` — starts at first **allowed** consume.
|
|
228
|
+
- `{ kind: "epoch", durationMs: number }` — Unix epoch-aligned duration buckets.
|
|
229
|
+
|
|
230
|
+
Calendar weeks default to Monday. Timezones are validated by `Intl`; invalid
|
|
231
|
+
names throw `INVALID_TIME_ZONE`. Repeated midnight uses the earlier occurrence;
|
|
232
|
+
skipped midnight/date advances through the gap. Days can have 23 or 25 hours.
|
|
233
|
+
Durations must be positive safe integer milliseconds with a safely representable
|
|
234
|
+
end timestamp (`INVALID_DURATION`).
|
|
235
|
+
|
|
236
|
+
A `(scope, subjectRef, key)` has a fixed window policy. Changing kind, duration,
|
|
237
|
+
calendar period, timezone spelling, or effective week start throws
|
|
238
|
+
`POLICY_MISMATCH`, even after expiry. Use a new key for a new policy. Changing the
|
|
239
|
+
limit does not reset usage. `periodKey` is an opaque window label, not an
|
|
240
|
+
idempotency token; do not parse it or reuse it across keys, scopes, or erased rows.
|
|
241
|
+
|
|
242
|
+
## Mutations
|
|
243
|
+
|
|
244
|
+
### `consume(ctx, subjectRef, key, limit, window, opts?)`
|
|
245
|
+
|
|
246
|
+
`opts: { scope?: string; amount?: number }`; amount defaults to 1.
|
|
247
|
+
Returns `{ allowed: boolean, remaining: number, used: number, limit: number,
|
|
248
|
+
periodKey: string, resetsAt: number }`. Denied calls do not write. A lower limit
|
|
249
|
+
can return `used > limit` with zero remaining. Successful calls store the latest
|
|
250
|
+
limit for refund calculations. Not idempotent: deduplicate host event retries
|
|
251
|
+
in the same transaction (e.g. with `@vllnt/convex-idempotency`).
|
|
252
|
+
|
|
253
|
+
### `refund(ctx, subjectRef, key, amount, periodKey, scope?)`
|
|
254
|
+
|
|
255
|
+
Returns `{ refunded: boolean, used: number, remaining: number }` in all cases.
|
|
256
|
+
Subtracts amount, clamped at zero, only if the stored period matches and has not
|
|
257
|
+
expired. Otherwise returns `refunded: false` and the stored row's usage/remaining
|
|
258
|
+
(or zeros if absent); these are not a recomputed current-window allowance.
|
|
259
|
+
Remaining uses the limit from the last successful consume, not a later query or
|
|
260
|
+
denied call. A matching zero-usage row still returns `refunded: true`.
|
|
261
|
+
|
|
262
|
+
Privileged, **not idempotent**: repeated refunds subtract repeatedly. The host
|
|
263
|
+
must authorize and deduplicate compensation events transactionally. Erasing and
|
|
264
|
+
recreating the same calendar period can reuse a label: old refunds must not be
|
|
265
|
+
replayed against it.
|
|
266
|
+
|
|
267
|
+
### `eraseSubject(ctx, subjectRef, scope?, batch?)`
|
|
268
|
+
|
|
269
|
+
Returns the number deleted **this pass**, not the total. Deletes up to batch
|
|
270
|
+
rows (positive integer, default 200, capped at 500; `INVALID_BATCH` otherwise).
|
|
271
|
+
Schedules another pass if full, including a possible final empty pass. Scope is
|
|
272
|
+
always enforced. The host must quiesce writes until scheduled cleanup completes;
|
|
273
|
+
there is no tombstone and a racing consume can survive or be swept. Monitor the
|
|
274
|
+
Convex scheduler for failures. Component mutations are atomic within each pass,
|
|
275
|
+
not across the whole sweep.
|
|
276
|
+
|
|
277
|
+
## Queries
|
|
278
|
+
|
|
279
|
+
### `remaining(ctx, subjectRef, key, limit, window, scope?)`
|
|
280
|
+
|
|
281
|
+
Returns `{ remaining: number, used: number, limit: number, periodKey: string,
|
|
282
|
+
resetsAt: number }`. Computes the current window when the query runs; an expired
|
|
283
|
+
row reads as zero usage without writing. A query does not start a rolling window.
|
|
284
|
+
Time is server-sourced, but **time passing alone does not invalidate a cached
|
|
285
|
+
query/subscription**. Treat resetsAt as an expiry hint and use consume for the
|
|
286
|
+
authoritative decision. No timer or reset scheduler is installed.
|
|
287
|
+
|
|
288
|
+
## Isolation and operations
|
|
289
|
+
|
|
290
|
+
Mount multiple instances with `app.use(quota, { name: "webQuota" })` and
|
|
291
|
+
`app.use(quota, { name: "mobileQuota" })`; each client receives its own generated
|
|
292
|
+
component reference. Runtime scopes isolate indexed reads and erasures inside a
|
|
293
|
+
mount. One row per allowance means hot-key writes contend; different keys are
|
|
294
|
+
independent. No historical usage, receipts, logs or audit trail are stored.
|
|
295
|
+
Host audit instrumentation should avoid exposing opaque refs or sensitive data.
|
|
296
|
+
|
|
297
|
+
## Testing limits
|
|
298
|
+
|
|
299
|
+
`pnpm test:coverage` runs convex-test's mock backend, including adversarial
|
|
300
|
+
validation, civil-time transitions and scheduled-batch tests. It is not evidence
|
|
301
|
+
of real Convex OCC retries or real scheduler delivery.
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
---
|
|
305
|
+
|
|
306
|
+
## src/shared.ts
|
|
307
|
+
|
|
308
|
+
```ts
|
|
309
|
+
/** Shared constants and window math used by both `client/` and `component/`. */
|
|
310
|
+
|
|
311
|
+
export const COMPONENT_NAME = "quota";
|
|
312
|
+
|
|
313
|
+
/** Default namespace when the host does not scope an allowance. */
|
|
314
|
+
export const DEFAULT_SCOPE = "global";
|
|
315
|
+
|
|
316
|
+
/** Length limit for opaque refs. */
|
|
317
|
+
export const MAX_REF_LENGTH = 256;
|
|
318
|
+
|
|
319
|
+
/** Default / max rows deleted per erase pass before the sweep reschedules. */
|
|
320
|
+
export const DEFAULT_ERASE_BATCH = 200;
|
|
321
|
+
export const MAX_ERASE_BATCH = 500;
|
|
322
|
+
|
|
323
|
+
export type CalendarPeriod = "day" | "month" | "week";
|
|
324
|
+
export type WeekStartsOn = "monday" | "sunday";
|
|
325
|
+
|
|
326
|
+
export type WindowSpec =
|
|
327
|
+
| {
|
|
328
|
+
durationMs: number;
|
|
329
|
+
kind: "epoch";
|
|
330
|
+
}
|
|
331
|
+
| {
|
|
332
|
+
durationMs: number;
|
|
333
|
+
kind: "rolling";
|
|
334
|
+
}
|
|
335
|
+
| {
|
|
336
|
+
kind: "calendar";
|
|
337
|
+
period: CalendarPeriod;
|
|
338
|
+
timeZone: string;
|
|
339
|
+
weekStartsOn?: WeekStartsOn;
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
export type ResolvedWindow = {
|
|
343
|
+
endAt: number;
|
|
344
|
+
periodKey: string;
|
|
345
|
+
startAt: number;
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
/** Stable policy identity; hosts must use a new key to change window policy. */
|
|
349
|
+
export function windowPolicyKey(spec: WindowSpec): string {
|
|
350
|
+
return spec.kind === "calendar"
|
|
351
|
+
? JSON.stringify([
|
|
352
|
+
spec.kind,
|
|
353
|
+
spec.period,
|
|
354
|
+
spec.timeZone,
|
|
355
|
+
spec.period === "week" ? (spec.weekStartsOn ?? "monday") : undefined,
|
|
356
|
+
])
|
|
357
|
+
: JSON.stringify([spec.kind, spec.durationMs]);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const formatterCache = new Map<string, Intl.DateTimeFormat>();
|
|
361
|
+
|
|
362
|
+
function pad2(value: number): string {
|
|
363
|
+
return value.toString().padStart(2, "0");
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function assertFinitePositive(
|
|
367
|
+
value: number,
|
|
368
|
+
code: string,
|
|
369
|
+
message: string,
|
|
370
|
+
): void {
|
|
371
|
+
if (!(value > 0 && Number.isSafeInteger(value))) {
|
|
372
|
+
throw new Error(`${code}:${message}`);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function formatterFor(timeZone: string): Intl.DateTimeFormat {
|
|
377
|
+
const cached = formatterCache.get(timeZone);
|
|
378
|
+
if (cached !== undefined) {
|
|
379
|
+
return cached;
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
const created = new Intl.DateTimeFormat("en-US", {
|
|
383
|
+
day: "2-digit",
|
|
384
|
+
hour: "2-digit",
|
|
385
|
+
hourCycle: "h23",
|
|
386
|
+
minute: "2-digit",
|
|
387
|
+
month: "2-digit",
|
|
388
|
+
second: "2-digit",
|
|
389
|
+
timeZone,
|
|
390
|
+
weekday: "short",
|
|
391
|
+
year: "numeric",
|
|
392
|
+
});
|
|
393
|
+
formatterCache.set(timeZone, created);
|
|
394
|
+
return created;
|
|
395
|
+
} catch {
|
|
396
|
+
throw new Error(`INVALID_TIME_ZONE: ${timeZone}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function partMap(
|
|
401
|
+
parts: readonly Intl.DateTimeFormatPart[],
|
|
402
|
+
): Record<string, string> {
|
|
403
|
+
return parts.reduce<Record<string, string>>((accumulator, part) => {
|
|
404
|
+
accumulator[part.type] = part.value;
|
|
405
|
+
return accumulator;
|
|
406
|
+
}, {});
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Read calendar parts of `now` in `timeZone`. Throws if `timeZone` is not a
|
|
411
|
+
* valid IANA name.
|
|
412
|
+
*/
|
|
413
|
+
export function zonedParts(
|
|
414
|
+
now: number,
|
|
415
|
+
timeZone: string,
|
|
416
|
+
): {
|
|
417
|
+
day: number;
|
|
418
|
+
hour: number;
|
|
419
|
+
minute: number;
|
|
420
|
+
month: number;
|
|
421
|
+
second: number;
|
|
422
|
+
weekday: number;
|
|
423
|
+
year: number;
|
|
424
|
+
} {
|
|
425
|
+
const byType = partMap(formatterFor(timeZone).formatToParts(new Date(now)));
|
|
426
|
+
const weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(
|
|
427
|
+
String(byType.weekday),
|
|
428
|
+
);
|
|
429
|
+
return {
|
|
430
|
+
day: Number(byType.day),
|
|
431
|
+
hour: Number(byType.hour),
|
|
432
|
+
minute: Number(byType.minute),
|
|
433
|
+
month: Number(byType.month),
|
|
434
|
+
second: Number(byType.second),
|
|
435
|
+
weekday,
|
|
436
|
+
year: Number(byType.year),
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
type CivilDate = { day: number; month: number; year: number };
|
|
441
|
+
|
|
442
|
+
function stepMidnight(
|
|
443
|
+
guess: number,
|
|
444
|
+
{ day, month, year }: CivilDate,
|
|
445
|
+
timeZone: string,
|
|
446
|
+
): number {
|
|
447
|
+
const parts = zonedParts(guess, timeZone);
|
|
448
|
+
const asUtc = Date.UTC(
|
|
449
|
+
parts.year,
|
|
450
|
+
parts.month - 1,
|
|
451
|
+
parts.day,
|
|
452
|
+
parts.hour,
|
|
453
|
+
parts.minute,
|
|
454
|
+
parts.second,
|
|
455
|
+
);
|
|
456
|
+
const target = Date.UTC(year, month - 1, day);
|
|
457
|
+
const diff = asUtc - target;
|
|
458
|
+
if (diff === 0) {
|
|
459
|
+
return guess;
|
|
460
|
+
}
|
|
461
|
+
return guess - diff;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* UTC ms for the start of a civil date. Repeated midnight chooses the earlier
|
|
466
|
+
* occurrence; a skipped midnight/date advances through the timezone gap.
|
|
467
|
+
*/
|
|
468
|
+
export function utcMsForLocalMidnight(
|
|
469
|
+
{ day, month, year }: CivilDate,
|
|
470
|
+
timeZone: string,
|
|
471
|
+
): number {
|
|
472
|
+
const first = Date.UTC(year, month - 1, day);
|
|
473
|
+
const corrected = stepMidnight(first, { day, month, year }, timeZone);
|
|
474
|
+
const candidates = [-86_400_000, 0, 86_400_000].map((delta) =>
|
|
475
|
+
stepMidnight(corrected + delta, { day, month, year }, timeZone),
|
|
476
|
+
);
|
|
477
|
+
const exact = candidates.filter((candidate) => {
|
|
478
|
+
const parts = zonedParts(candidate, timeZone);
|
|
479
|
+
return (
|
|
480
|
+
parts.year === year &&
|
|
481
|
+
parts.month === month &&
|
|
482
|
+
parts.day === day &&
|
|
483
|
+
parts.hour === 0 &&
|
|
484
|
+
parts.minute === 0 &&
|
|
485
|
+
parts.second === 0
|
|
486
|
+
);
|
|
487
|
+
});
|
|
488
|
+
return exact.length > 0
|
|
489
|
+
? Math.min(...exact)
|
|
490
|
+
: Math.max(corrected, ...candidates);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function addDays(
|
|
494
|
+
{ day, month, year }: CivilDate,
|
|
495
|
+
delta: number,
|
|
496
|
+
): { day: number; month: number; year: number } {
|
|
497
|
+
const date = new Date(Date.UTC(year, month - 1, day + delta));
|
|
498
|
+
return {
|
|
499
|
+
day: date.getUTCDate(),
|
|
500
|
+
month: date.getUTCMonth() + 1,
|
|
501
|
+
year: date.getUTCFullYear(),
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** ISO week (Monday start) for a civil date. */
|
|
506
|
+
export function isoWeek(
|
|
507
|
+
year: number,
|
|
508
|
+
month: number,
|
|
509
|
+
day: number,
|
|
510
|
+
): { week: number; year: number } {
|
|
511
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
512
|
+
const thursday = new Date(date);
|
|
513
|
+
thursday.setUTCDate(date.getUTCDate() + 4 - (date.getUTCDay() || 7));
|
|
514
|
+
const yearStart = new Date(Date.UTC(thursday.getUTCFullYear(), 0, 1));
|
|
515
|
+
const week = Math.ceil(
|
|
516
|
+
((thursday.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7,
|
|
517
|
+
);
|
|
518
|
+
return { week, year: thursday.getUTCFullYear() };
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function resolveWeek(
|
|
522
|
+
parts: ReturnType<typeof zonedParts>,
|
|
523
|
+
timeZone: string,
|
|
524
|
+
weekStartsOn: WeekStartsOn,
|
|
525
|
+
): ResolvedWindow {
|
|
526
|
+
const sunday = weekStartsOn === "sunday";
|
|
527
|
+
const mondayDelta = parts.weekday === 0 ? -6 : 1 - parts.weekday;
|
|
528
|
+
const delta = sunday ? -parts.weekday : mondayDelta;
|
|
529
|
+
const start = addDays(parts, delta);
|
|
530
|
+
const end = addDays(start, 7);
|
|
531
|
+
const labelDate = sunday ? start : parts;
|
|
532
|
+
const label = isoWeek(labelDate.year, labelDate.month, labelDate.day);
|
|
533
|
+
return {
|
|
534
|
+
endAt: utcMsForLocalMidnight(end, timeZone),
|
|
535
|
+
periodKey: `${label.year.toString()}-W${pad2(label.week)}${sunday ? "-sun" : ""}`,
|
|
536
|
+
startAt: utcMsForLocalMidnight(start, timeZone),
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function resolveCalendar(
|
|
541
|
+
now: number,
|
|
542
|
+
spec: Extract<WindowSpec, { kind: "calendar" }>,
|
|
543
|
+
): ResolvedWindow {
|
|
544
|
+
const { period, timeZone, weekStartsOn } = spec;
|
|
545
|
+
const parts = zonedParts(now, timeZone);
|
|
546
|
+
if (period === "week")
|
|
547
|
+
return resolveWeek(parts, timeZone, weekStartsOn ?? "monday");
|
|
548
|
+
const start = period === "day" ? parts : { ...parts, day: 1 };
|
|
549
|
+
const next =
|
|
550
|
+
period === "day"
|
|
551
|
+
? addDays(parts, 1)
|
|
552
|
+
: {
|
|
553
|
+
day: 1,
|
|
554
|
+
month: parts.month === 12 ? 1 : parts.month + 1,
|
|
555
|
+
year: parts.month === 12 ? parts.year + 1 : parts.year,
|
|
556
|
+
};
|
|
557
|
+
return {
|
|
558
|
+
endAt: utcMsForLocalMidnight(next, timeZone),
|
|
559
|
+
periodKey: `${parts.year.toString()}-${pad2(parts.month)}${period === "day" ? `-${pad2(parts.day)}` : ""}`,
|
|
560
|
+
startAt: utcMsForLocalMidnight(start, timeZone),
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Resolve the current window for `spec` at `now`. For `rolling`, pass the
|
|
566
|
+
* stored `windowStartAt` to reuse an in-progress window until it elapses.
|
|
567
|
+
*/
|
|
568
|
+
function validateDuration(now: number, durationMs: number): void {
|
|
569
|
+
assertFinitePositive(
|
|
570
|
+
durationMs,
|
|
571
|
+
"INVALID_DURATION",
|
|
572
|
+
"durationMs must be a positive safe integer",
|
|
573
|
+
);
|
|
574
|
+
assertFinitePositive(
|
|
575
|
+
now + durationMs,
|
|
576
|
+
"INVALID_DURATION",
|
|
577
|
+
"window end must be a positive safe integer",
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
export function resolveWindow(
|
|
582
|
+
now: number,
|
|
583
|
+
spec: WindowSpec,
|
|
584
|
+
rollingStartAt?: number,
|
|
585
|
+
): ResolvedWindow {
|
|
586
|
+
if (spec.kind === "calendar") {
|
|
587
|
+
return resolveCalendar(now, spec);
|
|
588
|
+
}
|
|
589
|
+
validateDuration(now, spec.durationMs);
|
|
590
|
+
if (spec.kind === "epoch") {
|
|
591
|
+
const index = Math.floor(now / spec.durationMs);
|
|
592
|
+
const startAt = index * spec.durationMs;
|
|
593
|
+
return {
|
|
594
|
+
endAt: startAt + spec.durationMs,
|
|
595
|
+
periodKey: `e${index.toString()}`,
|
|
596
|
+
startAt,
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
const startAt =
|
|
600
|
+
rollingStartAt !== undefined && now < rollingStartAt + spec.durationMs
|
|
601
|
+
? rollingStartAt
|
|
602
|
+
: now;
|
|
603
|
+
return {
|
|
604
|
+
endAt: startAt + spec.durationMs,
|
|
605
|
+
periodKey: `r${startAt.toString()}`,
|
|
606
|
+
startAt,
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
export function interpretWindowError(error: unknown): {
|
|
611
|
+
code: "INVALID_DURATION" | "INVALID_TIME_ZONE";
|
|
612
|
+
message: string;
|
|
613
|
+
} {
|
|
614
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
615
|
+
if (message.startsWith("INVALID_DURATION:")) {
|
|
616
|
+
return {
|
|
617
|
+
code: "INVALID_DURATION",
|
|
618
|
+
message: message.slice("INVALID_DURATION:".length),
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
return {
|
|
622
|
+
code: "INVALID_TIME_ZONE",
|
|
623
|
+
message: message.replace(/^INVALID_TIME_ZONE:\s*/, ""),
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
export function clampEraseBatch(batch: number): number {
|
|
628
|
+
if (!Number.isInteger(batch) || batch < 1) {
|
|
629
|
+
throw new Error("INVALID_BATCH: batch must be a positive integer");
|
|
630
|
+
}
|
|
631
|
+
return Math.min(batch, MAX_ERASE_BATCH);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
```
|
|
635
|
+
|
|
636
|
+
---
|
|
637
|
+
|
|
638
|
+
## src/client/types.ts
|
|
639
|
+
|
|
640
|
+
```ts
|
|
641
|
+
/** Public TypeScript surface for the quota client. */
|
|
642
|
+
|
|
643
|
+
export type ConsumeResult = {
|
|
644
|
+
allowed: boolean;
|
|
645
|
+
limit: number;
|
|
646
|
+
periodKey: string;
|
|
647
|
+
remaining: number;
|
|
648
|
+
resetsAt: number;
|
|
649
|
+
used: number;
|
|
650
|
+
};
|
|
651
|
+
|
|
652
|
+
export type RemainingState = {
|
|
653
|
+
limit: number;
|
|
654
|
+
periodKey: string;
|
|
655
|
+
remaining: number;
|
|
656
|
+
resetsAt: number;
|
|
657
|
+
used: number;
|
|
658
|
+
};
|
|
659
|
+
|
|
660
|
+
export type RefundResult = {
|
|
661
|
+
refunded: boolean;
|
|
662
|
+
remaining: number;
|
|
663
|
+
used: number;
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
export type QuotaOptions = {
|
|
667
|
+
/** Namespace applied when a call omits `scope`. Default `"global"`. */
|
|
668
|
+
defaultScope?: string;
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
export type ConsumeOptions = {
|
|
672
|
+
/** Units to consume. Default `1`. */
|
|
673
|
+
amount?: number;
|
|
674
|
+
scope?: string;
|
|
675
|
+
};
|
|
676
|
+
|
|
677
|
+
export { type WindowSpec } from "../shared.js";
|
|
678
|
+
|
|
679
|
+
```
|
|
680
|
+
|
|
681
|
+
---
|
|
682
|
+
|
|
683
|
+
## src/client/index.ts
|
|
684
|
+
|
|
685
|
+
```ts
|
|
686
|
+
import type {
|
|
687
|
+
FunctionArgs,
|
|
688
|
+
FunctionReference,
|
|
689
|
+
FunctionReturnType,
|
|
690
|
+
} from "convex/server";
|
|
691
|
+
|
|
692
|
+
import { DEFAULT_SCOPE } from "../shared.js";
|
|
693
|
+
|
|
694
|
+
import type {
|
|
695
|
+
ConsumeOptions,
|
|
696
|
+
ConsumeResult,
|
|
697
|
+
QuotaOptions,
|
|
698
|
+
RefundResult,
|
|
699
|
+
RemainingState,
|
|
700
|
+
WindowSpec,
|
|
701
|
+
} from "./types.js";
|
|
702
|
+
|
|
703
|
+
export type QuotaComponent = {
|
|
704
|
+
mutations: {
|
|
705
|
+
consume: FunctionReference<
|
|
706
|
+
"mutation",
|
|
707
|
+
"internal",
|
|
708
|
+
{
|
|
709
|
+
amount: number;
|
|
710
|
+
key: string;
|
|
711
|
+
limit: number;
|
|
712
|
+
scope: string;
|
|
713
|
+
subjectRef: string;
|
|
714
|
+
window: WindowSpec;
|
|
715
|
+
},
|
|
716
|
+
ConsumeResult
|
|
717
|
+
>;
|
|
718
|
+
eraseSubject: FunctionReference<
|
|
719
|
+
"mutation",
|
|
720
|
+
"internal",
|
|
721
|
+
{ batch?: number; scope: string; subjectRef: string },
|
|
722
|
+
number
|
|
723
|
+
>;
|
|
724
|
+
refund: FunctionReference<
|
|
725
|
+
"mutation",
|
|
726
|
+
"internal",
|
|
727
|
+
{
|
|
728
|
+
amount: number;
|
|
729
|
+
key: string;
|
|
730
|
+
periodKey: string;
|
|
731
|
+
scope: string;
|
|
732
|
+
subjectRef: string;
|
|
733
|
+
},
|
|
734
|
+
RefundResult
|
|
735
|
+
>;
|
|
736
|
+
};
|
|
737
|
+
queries: {
|
|
738
|
+
remaining: FunctionReference<
|
|
739
|
+
"query",
|
|
740
|
+
"internal",
|
|
741
|
+
{
|
|
742
|
+
key: string;
|
|
743
|
+
limit: number;
|
|
744
|
+
scope: string;
|
|
745
|
+
subjectRef: string;
|
|
746
|
+
window: WindowSpec;
|
|
747
|
+
},
|
|
748
|
+
RemainingState
|
|
749
|
+
>;
|
|
750
|
+
};
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
type RunQueryCtx = {
|
|
754
|
+
runQuery<TQuery extends FunctionReference<"query", "internal">>(
|
|
755
|
+
reference: TQuery,
|
|
756
|
+
arguments_: FunctionArgs<TQuery>,
|
|
757
|
+
): Promise<FunctionReturnType<TQuery>>;
|
|
758
|
+
};
|
|
759
|
+
|
|
760
|
+
type RunMutationCtx = {
|
|
761
|
+
runMutation<TMutation extends FunctionReference<"mutation", "internal">>(
|
|
762
|
+
reference: TMutation,
|
|
763
|
+
arguments_: FunctionArgs<TMutation>,
|
|
764
|
+
): Promise<FunctionReturnType<TMutation>>;
|
|
765
|
+
};
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* Consumer-facing client for the scheduled-reset quota ledger. The host owns
|
|
769
|
+
* auth and meaning; it passes an opaque `subjectRef` + `key` and a window spec.
|
|
770
|
+
* Never take `limit` from an end-user. Time is server-sourced. Consume is not
|
|
771
|
+
* idempotent — wrap with `@vllnt/convex-idempotency` if retries must not double-count.
|
|
772
|
+
*/
|
|
773
|
+
export class Quota {
|
|
774
|
+
private readonly defaultScope: string;
|
|
775
|
+
|
|
776
|
+
constructor(
|
|
777
|
+
private readonly component: QuotaComponent,
|
|
778
|
+
options: QuotaOptions = {},
|
|
779
|
+
) {
|
|
780
|
+
this.defaultScope = options.defaultScope ?? DEFAULT_SCOPE;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
private scopeOf(scope?: string): string {
|
|
784
|
+
return scope ?? this.defaultScope;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// eslint-disable-next-line max-params -- Preserve the published positional client contract.
|
|
788
|
+
consume(
|
|
789
|
+
ctx: RunMutationCtx,
|
|
790
|
+
subjectRef: string,
|
|
791
|
+
key: string,
|
|
792
|
+
limit: number,
|
|
793
|
+
window: WindowSpec,
|
|
794
|
+
options: ConsumeOptions = {},
|
|
795
|
+
): Promise<ConsumeResult> {
|
|
796
|
+
return ctx.runMutation(this.component.mutations.consume, {
|
|
797
|
+
amount: options.amount ?? 1,
|
|
798
|
+
key,
|
|
799
|
+
limit,
|
|
800
|
+
scope: this.scopeOf(options.scope),
|
|
801
|
+
subjectRef,
|
|
802
|
+
window,
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// eslint-disable-next-line max-params -- Preserve the published positional client contract.
|
|
807
|
+
remaining(
|
|
808
|
+
ctx: RunQueryCtx,
|
|
809
|
+
subjectRef: string,
|
|
810
|
+
key: string,
|
|
811
|
+
limit: number,
|
|
812
|
+
window: WindowSpec,
|
|
813
|
+
scope?: string,
|
|
814
|
+
): Promise<RemainingState> {
|
|
815
|
+
return ctx.runQuery(this.component.queries.remaining, {
|
|
816
|
+
key,
|
|
817
|
+
limit,
|
|
818
|
+
scope: this.scopeOf(scope),
|
|
819
|
+
subjectRef,
|
|
820
|
+
window,
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// eslint-disable-next-line max-params -- Preserve the published positional client contract.
|
|
825
|
+
refund(
|
|
826
|
+
ctx: RunMutationCtx,
|
|
827
|
+
subjectRef: string,
|
|
828
|
+
key: string,
|
|
829
|
+
amount: number,
|
|
830
|
+
periodKey: string,
|
|
831
|
+
scope?: string,
|
|
832
|
+
): Promise<RefundResult> {
|
|
833
|
+
return ctx.runMutation(this.component.mutations.refund, {
|
|
834
|
+
amount,
|
|
835
|
+
key,
|
|
836
|
+
periodKey,
|
|
837
|
+
scope: this.scopeOf(scope),
|
|
838
|
+
subjectRef,
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// eslint-disable-next-line max-params -- Preserve the published positional client contract.
|
|
843
|
+
eraseSubject(
|
|
844
|
+
ctx: RunMutationCtx,
|
|
845
|
+
subjectRef: string,
|
|
846
|
+
scope?: string,
|
|
847
|
+
batch?: number,
|
|
848
|
+
): Promise<number> {
|
|
849
|
+
return ctx.runMutation(this.component.mutations.eraseSubject, {
|
|
850
|
+
batch,
|
|
851
|
+
scope: this.scopeOf(scope),
|
|
852
|
+
subjectRef,
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
export {
|
|
858
|
+
type ConsumeOptions,
|
|
859
|
+
type ConsumeResult,
|
|
860
|
+
type QuotaOptions,
|
|
861
|
+
type RefundResult,
|
|
862
|
+
type RemainingState,
|
|
863
|
+
type WindowSpec,
|
|
864
|
+
} from "./types.js";
|
|
865
|
+
|
|
866
|
+
```
|
|
867
|
+
|
|
868
|
+
---
|
|
869
|
+
|
|
870
|
+
## src/component/schema.ts
|
|
871
|
+
|
|
872
|
+
```ts
|
|
873
|
+
import { defineSchema, defineTable } from "convex/server";
|
|
874
|
+
import { v } from "convex/values";
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* Sandboxed tables — the quota ledger's own concern. `subjectRef`, `key`, and
|
|
878
|
+
* `scope` are opaque host-owned strings. The row stores the current window;
|
|
879
|
+
* a new period overwrites `used` in place (no history table).
|
|
880
|
+
*/
|
|
881
|
+
export default defineSchema({
|
|
882
|
+
allowances: defineTable({
|
|
883
|
+
key: v.string(),
|
|
884
|
+
limit: v.number(),
|
|
885
|
+
periodKey: v.string(),
|
|
886
|
+
policyKey: v.string(),
|
|
887
|
+
scope: v.string(),
|
|
888
|
+
subjectRef: v.string(),
|
|
889
|
+
updatedAt: v.number(),
|
|
890
|
+
used: v.number(),
|
|
891
|
+
windowEndAt: v.number(),
|
|
892
|
+
windowStartAt: v.number(),
|
|
893
|
+
}).index("by_scope_subject_key", ["scope", "subjectRef", "key"]),
|
|
894
|
+
});
|
|
895
|
+
|
|
896
|
+
```
|
|
897
|
+
|
|
898
|
+
---
|
|
899
|
+
|
|
900
|
+
## src/component/validators.ts
|
|
901
|
+
|
|
902
|
+
```ts
|
|
903
|
+
import { ConvexError, v } from "convex/values";
|
|
904
|
+
|
|
905
|
+
import { MAX_REF_LENGTH } from "../shared";
|
|
906
|
+
|
|
907
|
+
export function requireRef(value: string, name: string): void {
|
|
908
|
+
if (value.length === 0 || value.length > MAX_REF_LENGTH) {
|
|
909
|
+
throw new ConvexError({
|
|
910
|
+
code: "INVALID_REF",
|
|
911
|
+
message: `${name} must be 1..${MAX_REF_LENGTH.toString()} UTF-16 code units`,
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
export function requirePositiveInt(
|
|
917
|
+
value: number,
|
|
918
|
+
name: string,
|
|
919
|
+
code: string,
|
|
920
|
+
): void {
|
|
921
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
922
|
+
throw new ConvexError({
|
|
923
|
+
code,
|
|
924
|
+
message: `${name} must be a positive safe integer`,
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
export function requireAllowanceInput(input: {
|
|
930
|
+
key: string;
|
|
931
|
+
limit: number;
|
|
932
|
+
scope: string;
|
|
933
|
+
subjectRef: string;
|
|
934
|
+
}): void {
|
|
935
|
+
requireRef(input.subjectRef, "subjectRef");
|
|
936
|
+
requireRef(input.key, "key");
|
|
937
|
+
requireRef(input.scope, "scope");
|
|
938
|
+
requirePositiveInt(input.limit, "limit", "INVALID_LIMIT");
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
export const calendarPeriod = v.union(
|
|
942
|
+
v.literal("day"),
|
|
943
|
+
v.literal("week"),
|
|
944
|
+
v.literal("month"),
|
|
945
|
+
);
|
|
946
|
+
|
|
947
|
+
export const weekStartsOn = v.union(v.literal("monday"), v.literal("sunday"));
|
|
948
|
+
|
|
949
|
+
export const windowSpec = v.union(
|
|
950
|
+
v.object({
|
|
951
|
+
kind: v.literal("calendar"),
|
|
952
|
+
period: calendarPeriod,
|
|
953
|
+
timeZone: v.string(),
|
|
954
|
+
weekStartsOn: v.optional(weekStartsOn),
|
|
955
|
+
}),
|
|
956
|
+
v.object({
|
|
957
|
+
durationMs: v.number(),
|
|
958
|
+
kind: v.literal("rolling"),
|
|
959
|
+
}),
|
|
960
|
+
v.object({
|
|
961
|
+
durationMs: v.number(),
|
|
962
|
+
kind: v.literal("epoch"),
|
|
963
|
+
}),
|
|
964
|
+
);
|
|
965
|
+
|
|
966
|
+
export const consumeResult = v.union(
|
|
967
|
+
v.object({
|
|
968
|
+
allowed: v.literal(true),
|
|
969
|
+
limit: v.number(),
|
|
970
|
+
periodKey: v.string(),
|
|
971
|
+
remaining: v.number(),
|
|
972
|
+
resetsAt: v.number(),
|
|
973
|
+
used: v.number(),
|
|
974
|
+
}),
|
|
975
|
+
v.object({
|
|
976
|
+
allowed: v.literal(false),
|
|
977
|
+
limit: v.number(),
|
|
978
|
+
periodKey: v.string(),
|
|
979
|
+
remaining: v.number(),
|
|
980
|
+
resetsAt: v.number(),
|
|
981
|
+
used: v.number(),
|
|
982
|
+
}),
|
|
983
|
+
);
|
|
984
|
+
|
|
985
|
+
export const remainingState = v.object({
|
|
986
|
+
limit: v.number(),
|
|
987
|
+
periodKey: v.string(),
|
|
988
|
+
remaining: v.number(),
|
|
989
|
+
resetsAt: v.number(),
|
|
990
|
+
used: v.number(),
|
|
991
|
+
});
|
|
992
|
+
|
|
993
|
+
```
|
|
994
|
+
|
|
995
|
+
---
|
|
996
|
+
|
|
997
|
+
## src/component/mutations.ts
|
|
998
|
+
|
|
999
|
+
```ts
|
|
1000
|
+
import { ConvexError, v } from "convex/values";
|
|
1001
|
+
|
|
1002
|
+
import {
|
|
1003
|
+
DEFAULT_ERASE_BATCH,
|
|
1004
|
+
interpretWindowError,
|
|
1005
|
+
MAX_ERASE_BATCH,
|
|
1006
|
+
type ResolvedWindow,
|
|
1007
|
+
resolveWindow,
|
|
1008
|
+
windowPolicyKey,
|
|
1009
|
+
type WindowSpec,
|
|
1010
|
+
} from "../shared";
|
|
1011
|
+
|
|
1012
|
+
import { api } from "./_generated/api";
|
|
1013
|
+
import type { Doc as Document_ } from "./_generated/dataModel";
|
|
1014
|
+
import { mutation, type MutationCtx } from "./_generated/server";
|
|
1015
|
+
import {
|
|
1016
|
+
consumeResult,
|
|
1017
|
+
requireAllowanceInput,
|
|
1018
|
+
requirePositiveInt,
|
|
1019
|
+
requireRef,
|
|
1020
|
+
windowSpec,
|
|
1021
|
+
} from "./validators";
|
|
1022
|
+
|
|
1023
|
+
function fail(code: string, message: string): never {
|
|
1024
|
+
throw new ConvexError({ code, message });
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
function currentWindow(
|
|
1028
|
+
spec: WindowSpec,
|
|
1029
|
+
rollingStartAt: number | undefined,
|
|
1030
|
+
): ResolvedWindow {
|
|
1031
|
+
try {
|
|
1032
|
+
return resolveWindow(Date.now(), spec, rollingStartAt);
|
|
1033
|
+
} catch (error) {
|
|
1034
|
+
const parsed = interpretWindowError(error);
|
|
1035
|
+
fail(parsed.code, parsed.message);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
async function loadAllowance(
|
|
1040
|
+
ctx: MutationCtx,
|
|
1041
|
+
{
|
|
1042
|
+
key,
|
|
1043
|
+
scope,
|
|
1044
|
+
subjectRef,
|
|
1045
|
+
}: { key: string; scope: string; subjectRef: string },
|
|
1046
|
+
): Promise<Document_<"allowances"> | null> {
|
|
1047
|
+
return ctx.db
|
|
1048
|
+
.query("allowances")
|
|
1049
|
+
.withIndex("by_scope_subject_key", (q) =>
|
|
1050
|
+
q.eq("scope", scope).eq("subjectRef", subjectRef).eq("key", key),
|
|
1051
|
+
)
|
|
1052
|
+
.first();
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
function allowanceWindow(
|
|
1056
|
+
existing: Document_<"allowances"> | null,
|
|
1057
|
+
spec: WindowSpec,
|
|
1058
|
+
) {
|
|
1059
|
+
const rollingStart =
|
|
1060
|
+
existing !== null && spec.kind === "rolling"
|
|
1061
|
+
? existing.windowStartAt
|
|
1062
|
+
: undefined;
|
|
1063
|
+
const window = currentWindow(spec, rollingStart);
|
|
1064
|
+
const policyKey = windowPolicyKey(spec);
|
|
1065
|
+
if (existing !== null && existing.policyKey !== policyKey) {
|
|
1066
|
+
fail("POLICY_MISMATCH", "Use a new key to change window policy");
|
|
1067
|
+
}
|
|
1068
|
+
const used =
|
|
1069
|
+
existing !== null && existing.periodKey === window.periodKey
|
|
1070
|
+
? existing.used
|
|
1071
|
+
: 0;
|
|
1072
|
+
return { policyKey, used, window };
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
function consumptionState(window: ResolvedWindow, limit: number, used: number) {
|
|
1076
|
+
return {
|
|
1077
|
+
limit,
|
|
1078
|
+
periodKey: window.periodKey,
|
|
1079
|
+
remaining: Math.max(limit - used, 0),
|
|
1080
|
+
resetsAt: window.endAt,
|
|
1081
|
+
used,
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
async function saveAllowance(
|
|
1086
|
+
ctx: MutationCtx,
|
|
1087
|
+
existing: Document_<"allowances"> | null,
|
|
1088
|
+
row: Omit<Document_<"allowances">, "_creationTime" | "_id">,
|
|
1089
|
+
) {
|
|
1090
|
+
await (existing === null
|
|
1091
|
+
? ctx.db.insert("allowances", row)
|
|
1092
|
+
: ctx.db.patch("allowances", existing._id, row));
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
export const consume = mutation({
|
|
1096
|
+
args: {
|
|
1097
|
+
amount: v.number(),
|
|
1098
|
+
key: v.string(),
|
|
1099
|
+
limit: v.number(),
|
|
1100
|
+
scope: v.string(),
|
|
1101
|
+
subjectRef: v.string(),
|
|
1102
|
+
window: windowSpec,
|
|
1103
|
+
},
|
|
1104
|
+
handler: async (ctx, arguments_) => {
|
|
1105
|
+
requireAllowanceInput(arguments_);
|
|
1106
|
+
requirePositiveInt(arguments_.amount, "amount", "INVALID_AMOUNT");
|
|
1107
|
+
|
|
1108
|
+
const existing = await loadAllowance(ctx, arguments_);
|
|
1109
|
+
const { policyKey, used, window } = allowanceWindow(
|
|
1110
|
+
existing,
|
|
1111
|
+
arguments_.window,
|
|
1112
|
+
);
|
|
1113
|
+
// Compare before addition: even safe operands can have an unsafe sum.
|
|
1114
|
+
const allowed = arguments_.amount <= arguments_.limit - used;
|
|
1115
|
+
const nextUsed = allowed ? used + arguments_.amount : used;
|
|
1116
|
+
const result = {
|
|
1117
|
+
allowed,
|
|
1118
|
+
...consumptionState(window, arguments_.limit, nextUsed),
|
|
1119
|
+
};
|
|
1120
|
+
if (!allowed) return result;
|
|
1121
|
+
await saveAllowance(ctx, existing, {
|
|
1122
|
+
key: arguments_.key,
|
|
1123
|
+
limit: arguments_.limit,
|
|
1124
|
+
periodKey: window.periodKey,
|
|
1125
|
+
policyKey,
|
|
1126
|
+
scope: arguments_.scope,
|
|
1127
|
+
subjectRef: arguments_.subjectRef,
|
|
1128
|
+
updatedAt: Date.now(),
|
|
1129
|
+
used: nextUsed,
|
|
1130
|
+
windowEndAt: window.endAt,
|
|
1131
|
+
windowStartAt: window.startAt,
|
|
1132
|
+
});
|
|
1133
|
+
return result;
|
|
1134
|
+
},
|
|
1135
|
+
returns: consumeResult,
|
|
1136
|
+
});
|
|
1137
|
+
|
|
1138
|
+
export const refund = mutation({
|
|
1139
|
+
args: {
|
|
1140
|
+
amount: v.number(),
|
|
1141
|
+
key: v.string(),
|
|
1142
|
+
periodKey: v.string(),
|
|
1143
|
+
scope: v.string(),
|
|
1144
|
+
subjectRef: v.string(),
|
|
1145
|
+
},
|
|
1146
|
+
handler: async (ctx, arguments_) => {
|
|
1147
|
+
requireRef(arguments_.subjectRef, "subjectRef");
|
|
1148
|
+
requireRef(arguments_.key, "key");
|
|
1149
|
+
requireRef(arguments_.scope, "scope");
|
|
1150
|
+
requireRef(arguments_.periodKey, "periodKey");
|
|
1151
|
+
requirePositiveInt(arguments_.amount, "amount", "INVALID_AMOUNT");
|
|
1152
|
+
|
|
1153
|
+
const existing = await loadAllowance(ctx, arguments_);
|
|
1154
|
+
if (
|
|
1155
|
+
existing?.periodKey !== arguments_.periodKey ||
|
|
1156
|
+
Date.now() >= existing.windowEndAt
|
|
1157
|
+
) {
|
|
1158
|
+
return {
|
|
1159
|
+
refunded: false,
|
|
1160
|
+
remaining:
|
|
1161
|
+
existing === null ? 0 : Math.max(existing.limit - existing.used, 0),
|
|
1162
|
+
used: existing?.used ?? 0,
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
const used = Math.max(existing.used - arguments_.amount, 0);
|
|
1167
|
+
await ctx.db.patch("allowances", existing._id, {
|
|
1168
|
+
updatedAt: Date.now(),
|
|
1169
|
+
used,
|
|
1170
|
+
});
|
|
1171
|
+
return {
|
|
1172
|
+
refunded: true,
|
|
1173
|
+
remaining: Math.max(existing.limit - used, 0),
|
|
1174
|
+
used,
|
|
1175
|
+
};
|
|
1176
|
+
},
|
|
1177
|
+
returns: v.object({
|
|
1178
|
+
refunded: v.boolean(),
|
|
1179
|
+
remaining: v.number(),
|
|
1180
|
+
used: v.number(),
|
|
1181
|
+
}),
|
|
1182
|
+
});
|
|
1183
|
+
|
|
1184
|
+
export const eraseSubject = mutation({
|
|
1185
|
+
args: {
|
|
1186
|
+
batch: v.optional(v.number()),
|
|
1187
|
+
scope: v.string(),
|
|
1188
|
+
subjectRef: v.string(),
|
|
1189
|
+
},
|
|
1190
|
+
handler: async (ctx, arguments_) => {
|
|
1191
|
+
requireRef(arguments_.subjectRef, "subjectRef");
|
|
1192
|
+
requireRef(arguments_.scope, "scope");
|
|
1193
|
+
const raw = arguments_.batch ?? DEFAULT_ERASE_BATCH;
|
|
1194
|
+
if (!Number.isInteger(raw)) {
|
|
1195
|
+
fail("INVALID_BATCH", "batch must be a positive integer");
|
|
1196
|
+
}
|
|
1197
|
+
if (raw < 1) {
|
|
1198
|
+
fail("INVALID_BATCH", "batch must be a positive integer");
|
|
1199
|
+
}
|
|
1200
|
+
const batch = Math.min(raw, MAX_ERASE_BATCH);
|
|
1201
|
+
const rows = await ctx.db
|
|
1202
|
+
.query("allowances")
|
|
1203
|
+
.withIndex("by_scope_subject_key", (q) =>
|
|
1204
|
+
q.eq("scope", arguments_.scope).eq("subjectRef", arguments_.subjectRef),
|
|
1205
|
+
)
|
|
1206
|
+
.take(batch);
|
|
1207
|
+
await Promise.all(rows.map((row) => ctx.db.delete("allowances", row._id)));
|
|
1208
|
+
if (rows.length === batch) {
|
|
1209
|
+
await ctx.scheduler.runAfter(0, api.mutations.eraseSubject, {
|
|
1210
|
+
batch,
|
|
1211
|
+
scope: arguments_.scope,
|
|
1212
|
+
subjectRef: arguments_.subjectRef,
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
return rows.length;
|
|
1216
|
+
},
|
|
1217
|
+
returns: v.number(),
|
|
1218
|
+
});
|
|
1219
|
+
|
|
1220
|
+
```
|
|
1221
|
+
|
|
1222
|
+
---
|
|
1223
|
+
|
|
1224
|
+
## src/component/queries.ts
|
|
1225
|
+
|
|
1226
|
+
```ts
|
|
1227
|
+
import { ConvexError, v } from "convex/values";
|
|
1228
|
+
|
|
1229
|
+
import {
|
|
1230
|
+
interpretWindowError,
|
|
1231
|
+
type ResolvedWindow,
|
|
1232
|
+
resolveWindow,
|
|
1233
|
+
windowPolicyKey,
|
|
1234
|
+
type WindowSpec,
|
|
1235
|
+
} from "../shared";
|
|
1236
|
+
|
|
1237
|
+
import { query } from "./_generated/server";
|
|
1238
|
+
import {
|
|
1239
|
+
remainingState,
|
|
1240
|
+
requireAllowanceInput,
|
|
1241
|
+
windowSpec,
|
|
1242
|
+
} from "./validators";
|
|
1243
|
+
|
|
1244
|
+
function fail(code: string, message: string): never {
|
|
1245
|
+
throw new ConvexError({ code, message });
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
function currentWindow(
|
|
1249
|
+
spec: WindowSpec,
|
|
1250
|
+
rollingStartAt: number | undefined,
|
|
1251
|
+
): ResolvedWindow {
|
|
1252
|
+
try {
|
|
1253
|
+
return resolveWindow(Date.now(), spec, rollingStartAt);
|
|
1254
|
+
} catch (error) {
|
|
1255
|
+
const parsed = interpretWindowError(error);
|
|
1256
|
+
fail(parsed.code, parsed.message);
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
export const remaining = query({
|
|
1261
|
+
args: {
|
|
1262
|
+
key: v.string(),
|
|
1263
|
+
limit: v.number(),
|
|
1264
|
+
scope: v.string(),
|
|
1265
|
+
subjectRef: v.string(),
|
|
1266
|
+
window: windowSpec,
|
|
1267
|
+
},
|
|
1268
|
+
handler: async (ctx, arguments_) => {
|
|
1269
|
+
requireAllowanceInput(arguments_);
|
|
1270
|
+
const row = await ctx.db
|
|
1271
|
+
.query("allowances")
|
|
1272
|
+
.withIndex("by_scope_subject_key", (q) =>
|
|
1273
|
+
q
|
|
1274
|
+
.eq("scope", arguments_.scope)
|
|
1275
|
+
.eq("subjectRef", arguments_.subjectRef)
|
|
1276
|
+
.eq("key", arguments_.key),
|
|
1277
|
+
)
|
|
1278
|
+
.first();
|
|
1279
|
+
const rollingStart =
|
|
1280
|
+
row !== null && arguments_.window.kind === "rolling"
|
|
1281
|
+
? row.windowStartAt
|
|
1282
|
+
: undefined;
|
|
1283
|
+
const window = currentWindow(arguments_.window, rollingStart);
|
|
1284
|
+
if (row !== null && row.policyKey !== windowPolicyKey(arguments_.window)) {
|
|
1285
|
+
fail("POLICY_MISMATCH", "Use a new key to change window policy");
|
|
1286
|
+
}
|
|
1287
|
+
const used =
|
|
1288
|
+
row !== null && row.periodKey === window.periodKey ? row.used : 0;
|
|
1289
|
+
return {
|
|
1290
|
+
limit: arguments_.limit,
|
|
1291
|
+
periodKey: window.periodKey,
|
|
1292
|
+
remaining: Math.max(arguments_.limit - used, 0),
|
|
1293
|
+
resetsAt: window.endAt,
|
|
1294
|
+
used,
|
|
1295
|
+
};
|
|
1296
|
+
},
|
|
1297
|
+
returns: remainingState,
|
|
1298
|
+
});
|
|
1299
|
+
|
|
1300
|
+
```
|
|
1301
|
+
|
|
1302
|
+
---
|
|
1303
|
+
|
|
1304
|
+
## src/test.ts
|
|
1305
|
+
|
|
1306
|
+
```ts
|
|
1307
|
+
import type { TestConvex } from "convex-test";
|
|
1308
|
+
|
|
1309
|
+
import schema from "./component/schema";
|
|
1310
|
+
|
|
1311
|
+
const modules = import.meta.glob("./component/**/*.ts");
|
|
1312
|
+
|
|
1313
|
+
/**
|
|
1314
|
+
* Register this component with a `convex-test` instance so consuming apps can
|
|
1315
|
+
* test integration: `import { register } from "@vllnt/convex-quota/test"`.
|
|
1316
|
+
*/
|
|
1317
|
+
export function register(
|
|
1318
|
+
t: Pick<TestConvex<typeof schema>, "registerComponent">,
|
|
1319
|
+
name = "quota",
|
|
1320
|
+
): void {
|
|
1321
|
+
t.registerComponent(name, schema, modules);
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
```
|