@vantedev/groundwork 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/LICENSE +21 -0
- package/README.md +350 -2
- package/dist/api-keys/api-keys.d.ts +56 -0
- package/dist/api-keys/api-keys.d.ts.map +1 -0
- package/dist/api-keys/api-keys.js +619 -0
- package/dist/api-keys/api-keys.js.map +1 -0
- package/dist/api-keys/audit.d.ts +17 -0
- package/dist/api-keys/audit.d.ts.map +1 -0
- package/dist/api-keys/audit.js +76 -0
- package/dist/api-keys/audit.js.map +1 -0
- package/dist/api-keys/format.d.ts +32 -0
- package/dist/api-keys/format.d.ts.map +1 -0
- package/dist/api-keys/format.js +92 -0
- package/dist/api-keys/format.js.map +1 -0
- package/dist/api-keys/index.d.ts +25 -0
- package/dist/api-keys/index.d.ts.map +1 -0
- package/dist/api-keys/index.js +23 -0
- package/dist/api-keys/index.js.map +1 -0
- package/dist/api-keys/policy.d.ts +16 -0
- package/dist/api-keys/policy.d.ts.map +1 -0
- package/dist/api-keys/policy.js +95 -0
- package/dist/api-keys/policy.js.map +1 -0
- package/dist/api-keys/responses.d.ts +6 -0
- package/dist/api-keys/responses.d.ts.map +1 -0
- package/dist/api-keys/responses.js +54 -0
- package/dist/api-keys/responses.js.map +1 -0
- package/dist/api-keys/scopes.d.ts +13 -0
- package/dist/api-keys/scopes.d.ts.map +1 -0
- package/dist/api-keys/scopes.js +49 -0
- package/dist/api-keys/scopes.js.map +1 -0
- package/dist/api-keys/types.d.ts +173 -0
- package/dist/api-keys/types.d.ts.map +1 -0
- package/dist/api-keys/types.js +2 -0
- package/dist/api-keys/types.js.map +1 -0
- package/dist/audit/audit-log.d.ts +35 -0
- package/dist/audit/audit-log.d.ts.map +1 -0
- package/dist/audit/audit-log.js +277 -0
- package/dist/audit/audit-log.js.map +1 -0
- package/dist/audit/cursor.d.ts +13 -0
- package/dist/audit/cursor.d.ts.map +1 -0
- package/dist/audit/cursor.js +26 -0
- package/dist/audit/cursor.js.map +1 -0
- package/dist/audit/diff.d.ts +19 -0
- package/dist/audit/diff.d.ts.map +1 -0
- package/dist/audit/diff.js +59 -0
- package/dist/audit/diff.js.map +1 -0
- package/dist/audit/index.d.ts +25 -0
- package/dist/audit/index.d.ts.map +1 -0
- package/dist/audit/index.js +24 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/audit/json.d.ts +23 -0
- package/dist/audit/json.d.ts.map +1 -0
- package/dist/audit/json.js +120 -0
- package/dist/audit/json.js.map +1 -0
- package/dist/audit/types.d.ts +118 -0
- package/dist/audit/types.d.ts.map +1 -0
- package/dist/audit/types.js +2 -0
- package/dist/audit/types.js.map +1 -0
- package/dist/idempotency/http.d.ts +27 -0
- package/dist/idempotency/http.d.ts.map +1 -0
- package/dist/idempotency/http.js +130 -0
- package/dist/idempotency/http.js.map +1 -0
- package/dist/idempotency/idempotency.d.ts +45 -0
- package/dist/idempotency/idempotency.d.ts.map +1 -0
- package/dist/idempotency/idempotency.js +302 -0
- package/dist/idempotency/idempotency.js.map +1 -0
- package/dist/idempotency/index.d.ts +25 -0
- package/dist/idempotency/index.d.ts.map +1 -0
- package/dist/idempotency/index.js +24 -0
- package/dist/idempotency/index.js.map +1 -0
- package/dist/idempotency/keys.d.ts +13 -0
- package/dist/idempotency/keys.d.ts.map +1 -0
- package/dist/idempotency/keys.js +9 -0
- package/dist/idempotency/keys.js.map +1 -0
- package/dist/idempotency/types.d.ts +92 -0
- package/dist/idempotency/types.d.ts.map +1 -0
- package/dist/idempotency/types.js +2 -0
- package/dist/idempotency/types.js.map +1 -0
- package/dist/index.d.ts +122 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +201 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/cidr.d.ts +21 -0
- package/dist/internal/cidr.d.ts.map +1 -0
- package/dist/internal/cidr.js +159 -0
- package/dist/internal/cidr.js.map +1 -0
- package/dist/internal/clock.d.ts +6 -0
- package/dist/internal/clock.d.ts.map +1 -0
- package/dist/internal/clock.js +4 -0
- package/dist/internal/clock.js.map +1 -0
- package/dist/internal/crypto.d.ts +44 -0
- package/dist/internal/crypto.d.ts.map +1 -0
- package/dist/internal/crypto.js +97 -0
- package/dist/internal/crypto.js.map +1 -0
- package/dist/internal/db.d.ts +14 -0
- package/dist/internal/db.d.ts.map +1 -0
- package/dist/internal/db.js +20 -0
- package/dist/internal/db.js.map +1 -0
- package/dist/internal/duration.d.ts +25 -0
- package/dist/internal/duration.d.ts.map +1 -0
- package/dist/internal/duration.js +39 -0
- package/dist/internal/duration.js.map +1 -0
- package/dist/internal/errors.d.ts +33 -0
- package/dist/internal/errors.d.ts.map +1 -0
- package/dist/internal/errors.js +29 -0
- package/dist/internal/errors.js.map +1 -0
- package/dist/internal/logger.d.ts +37 -0
- package/dist/internal/logger.d.ts.map +1 -0
- package/dist/internal/logger.js +54 -0
- package/dist/internal/logger.js.map +1 -0
- package/dist/internal/standard-schema.d.ts +49 -0
- package/dist/internal/standard-schema.d.ts.map +1 -0
- package/dist/internal/standard-schema.js +16 -0
- package/dist/internal/standard-schema.js.map +1 -0
- package/dist/internal/table.d.ts +7 -0
- package/dist/internal/table.d.ts.map +1 -0
- package/dist/internal/table.js +20 -0
- package/dist/internal/table.js.map +1 -0
- package/dist/jobs/backoff.d.ts +7 -0
- package/dist/jobs/backoff.d.ts.map +1 -0
- package/dist/jobs/backoff.js +10 -0
- package/dist/jobs/backoff.js.map +1 -0
- package/dist/jobs/index.d.ts +31 -0
- package/dist/jobs/index.d.ts.map +1 -0
- package/dist/jobs/index.js +29 -0
- package/dist/jobs/index.js.map +1 -0
- package/dist/jobs/jobs.d.ts +42 -0
- package/dist/jobs/jobs.d.ts.map +1 -0
- package/dist/jobs/jobs.js +741 -0
- package/dist/jobs/jobs.js.map +1 -0
- package/dist/jobs/types.d.ts +199 -0
- package/dist/jobs/types.d.ts.map +1 -0
- package/dist/jobs/types.js +2 -0
- package/dist/jobs/types.js.map +1 -0
- package/dist/next/client-ip.d.ts +42 -0
- package/dist/next/client-ip.d.ts.map +1 -0
- package/dist/next/client-ip.js +59 -0
- package/dist/next/client-ip.js.map +1 -0
- package/dist/next/index.d.ts +29 -0
- package/dist/next/index.d.ts.map +1 -0
- package/dist/next/index.js +29 -0
- package/dist/next/index.js.map +1 -0
- package/dist/next/jobs-route.d.ts +31 -0
- package/dist/next/jobs-route.d.ts.map +1 -0
- package/dist/next/jobs-route.js +53 -0
- package/dist/next/jobs-route.js.map +1 -0
- package/dist/next/response.d.ts +6 -0
- package/dist/next/response.d.ts.map +1 -0
- package/dist/next/response.js +25 -0
- package/dist/next/response.js.map +1 -0
- package/dist/next/route-helpers.d.ts +67 -0
- package/dist/next/route-helpers.d.ts.map +1 -0
- package/dist/next/route-helpers.js +93 -0
- package/dist/next/route-helpers.js.map +1 -0
- package/dist/rate-limit/index.d.ts +19 -0
- package/dist/rate-limit/index.d.ts.map +1 -0
- package/dist/rate-limit/index.js +18 -0
- package/dist/rate-limit/index.js.map +1 -0
- package/dist/rate-limit/limiter.d.ts +60 -0
- package/dist/rate-limit/limiter.d.ts.map +1 -0
- package/dist/rate-limit/limiter.js +147 -0
- package/dist/rate-limit/limiter.js.map +1 -0
- package/dist/rate-limit/memory-store.d.ts +23 -0
- package/dist/rate-limit/memory-store.d.ts.map +1 -0
- package/dist/rate-limit/memory-store.js +77 -0
- package/dist/rate-limit/memory-store.js.map +1 -0
- package/dist/rate-limit/policy.d.ts +31 -0
- package/dist/rate-limit/policy.d.ts.map +1 -0
- package/dist/rate-limit/policy.js +174 -0
- package/dist/rate-limit/policy.js.map +1 -0
- package/dist/rate-limit/postgres-store.d.ts +13 -0
- package/dist/rate-limit/postgres-store.d.ts.map +1 -0
- package/dist/rate-limit/postgres-store.js +129 -0
- package/dist/rate-limit/postgres-store.js.map +1 -0
- package/dist/rate-limit/redis-store.d.ts +24 -0
- package/dist/rate-limit/redis-store.d.ts.map +1 -0
- package/dist/rate-limit/redis-store.js +97 -0
- package/dist/rate-limit/redis-store.js.map +1 -0
- package/dist/rate-limit/types.d.ts +140 -0
- package/dist/rate-limit/types.d.ts.map +1 -0
- package/dist/rate-limit/types.js +2 -0
- package/dist/rate-limit/types.js.map +1 -0
- package/dist/schema/api-keys.d.ts +545 -0
- package/dist/schema/api-keys.d.ts.map +1 -0
- package/dist/schema/api-keys.js +83 -0
- package/dist/schema/api-keys.js.map +1 -0
- package/dist/schema/audit-log.d.ts +248 -0
- package/dist/schema/audit-log.d.ts.map +1 -0
- package/dist/schema/audit-log.js +56 -0
- package/dist/schema/audit-log.js.map +1 -0
- package/dist/schema/factory.d.ts +19 -0
- package/dist/schema/factory.d.ts.map +1 -0
- package/dist/schema/factory.js +39 -0
- package/dist/schema/factory.js.map +1 -0
- package/dist/schema/idempotency-keys.d.ts +178 -0
- package/dist/schema/idempotency-keys.d.ts.map +1 -0
- package/dist/schema/idempotency-keys.js +41 -0
- package/dist/schema/idempotency-keys.js.map +1 -0
- package/dist/schema/index.d.ts +61 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/index.js +28 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/schema/jobs.d.ts +487 -0
- package/dist/schema/jobs.d.ts.map +1 -0
- package/dist/schema/jobs.js +103 -0
- package/dist/schema/jobs.js.map +1 -0
- package/dist/schema/rate-limits.d.ts +108 -0
- package/dist/schema/rate-limits.d.ts.map +1 -0
- package/dist/schema/rate-limits.js +27 -0
- package/dist/schema/rate-limits.js.map +1 -0
- package/dist/testing/index.d.ts +25 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +37 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +117 -4
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import { lazySubkey, randomHex, timingSafeEqual } from "../internal/crypto.js";
|
|
3
|
+
import { rowsOf, toNumber } from "../internal/db.js";
|
|
4
|
+
import { parseDuration } from "../internal/duration.js";
|
|
5
|
+
import { errorText, GroundworkError } from "../internal/errors.js";
|
|
6
|
+
import { consoleLogger, createOnceLogger } from "../internal/logger.js";
|
|
7
|
+
import { assertTableColumns } from "../internal/table.js";
|
|
8
|
+
import { IDEMPOTENCY_KEY_COLUMNS } from "../schema/idempotency-keys.js";
|
|
9
|
+
import { decodeResponse, encodeResponse, errorResponse, isStoredResponse, parseIdempotencyKey, } from "./http.js";
|
|
10
|
+
import { createKeyHasher } from "./keys.js";
|
|
11
|
+
const MAX_SCOPE_LENGTH = 255;
|
|
12
|
+
const MAX_RUN_KEY_LENGTH = 255;
|
|
13
|
+
const CLEANUP_BATCH = 5_000;
|
|
14
|
+
const NULL_BODY_STATUSES = new Set([204, 205, 304]);
|
|
15
|
+
function checkScope(scope) {
|
|
16
|
+
if (typeof scope !== "string" || scope.length === 0 || scope.length > MAX_SCOPE_LENGTH) {
|
|
17
|
+
throw new GroundworkError("invalid_argument", `scope must be a string of 1 to ${MAX_SCOPE_LENGTH} characters, such as \`apikey:\${key.id}\`.`);
|
|
18
|
+
}
|
|
19
|
+
return scope;
|
|
20
|
+
}
|
|
21
|
+
function checkFingerprint(value) {
|
|
22
|
+
if (value === undefined || typeof value === "string" || value instanceof Uint8Array)
|
|
23
|
+
return value;
|
|
24
|
+
throw new GroundworkError("invalid_argument", "fingerprint must be a string or a Uint8Array.");
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Creates idempotency keys on your Postgres.
|
|
28
|
+
*
|
|
29
|
+
* ```ts
|
|
30
|
+
* const idempotency = createIdempotency({ db, table: tables.idempotencyKeys, secret });
|
|
31
|
+
* export async function POST(request: Request) {
|
|
32
|
+
* return idempotency.handle(request, { scope: `user:${user.id}` }, async () => {
|
|
33
|
+
* const order = await createOrder(await request.json());
|
|
34
|
+
* return Response.json(order, { status: 201 });
|
|
35
|
+
* });
|
|
36
|
+
* }
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export function createIdempotency(options) {
|
|
40
|
+
if (typeof options !== "object" || options === null) {
|
|
41
|
+
throw new GroundworkError("invalid_config", "createIdempotency needs an options object.");
|
|
42
|
+
}
|
|
43
|
+
const { db, table, clock } = options;
|
|
44
|
+
if (!db || typeof db.execute !== "function") {
|
|
45
|
+
throw new GroundworkError("invalid_config", "db must be a Drizzle Postgres database.");
|
|
46
|
+
}
|
|
47
|
+
assertTableColumns(table, IDEMPOTENCY_KEY_COLUMNS, "idempotency-key table from groundworkTables()");
|
|
48
|
+
const subkey = lazySubkey(options.secret, "idempotency");
|
|
49
|
+
const defaultTtlMs = parseDuration(options.ttl ?? "24h", { label: "ttl", minMs: 1_000 });
|
|
50
|
+
const leaseMs = parseDuration(options.lease ?? "30s", { label: "lease", minMs: 1_000 });
|
|
51
|
+
const logger = options.logger ?? consoleLogger;
|
|
52
|
+
const once = createOnceLogger(logger);
|
|
53
|
+
/** The time a statement works with: the injected clock, else Postgres's `now()`. */
|
|
54
|
+
const now = () => (clock ? sql `${clock.now().toISOString()}::timestamptz` : sql `now()`);
|
|
55
|
+
const interval = (ms) => sql `${ms}::float8 * interval '1 millisecond'`;
|
|
56
|
+
const ttlOf = (ttl) => ttl === undefined ? defaultTtlMs : parseDuration(ttl, { label: "ttl", minMs: 1_000 });
|
|
57
|
+
const hasher = createKeyHasher(subkey);
|
|
58
|
+
const storageKey = hasher.storageKey;
|
|
59
|
+
const fingerprintOf = hasher.fingerprint;
|
|
60
|
+
/**
|
|
61
|
+
* Claims `key` in one statement: inserts it, or takes over a row that has expired or whose
|
|
62
|
+
* request crashed (its lease ran out) with the same fingerprint. Otherwise returns the row as it
|
|
63
|
+
* is. A row inserted by a transaction that committed after this statement's snapshot is
|
|
64
|
+
* invisible to the fallback select, so that case is retried with a fresh snapshot.
|
|
65
|
+
*/
|
|
66
|
+
async function begin(key, scope, fingerprint, ttlMs) {
|
|
67
|
+
const token = randomHex(16);
|
|
68
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
69
|
+
const rows = rowsOf(await db.execute(sql `
|
|
70
|
+
with input as (select ${now()} as now),
|
|
71
|
+
claimed as (
|
|
72
|
+
insert into ${table} as i
|
|
73
|
+
(key, scope, fingerprint, locked_by, locked_until, response, created_at, completed_at, expires_at)
|
|
74
|
+
select ${key}, ${scope}, ${fingerprint}, ${token}, input.now + ${interval(leaseMs)},
|
|
75
|
+
null, input.now, null, input.now + ${interval(ttlMs)}
|
|
76
|
+
from input
|
|
77
|
+
on conflict (key) do update set
|
|
78
|
+
scope = excluded.scope, fingerprint = excluded.fingerprint,
|
|
79
|
+
locked_by = excluded.locked_by, locked_until = excluded.locked_until,
|
|
80
|
+
response = null, created_at = excluded.created_at, completed_at = null,
|
|
81
|
+
expires_at = excluded.expires_at
|
|
82
|
+
where (i.expires_at <= excluded.created_at
|
|
83
|
+
and (i.completed_at is not null or i.locked_until <= excluded.created_at))
|
|
84
|
+
or (i.completed_at is null and i.locked_until <= excluded.created_at
|
|
85
|
+
and i.fingerprint = excluded.fingerprint)
|
|
86
|
+
returning 1
|
|
87
|
+
)
|
|
88
|
+
select 'claimed' as state, null::text as fingerprint, null::text as response,
|
|
89
|
+
null::boolean as completed
|
|
90
|
+
from claimed
|
|
91
|
+
union all
|
|
92
|
+
select 'existing', e.fingerprint, e.response, e.completed_at is not null
|
|
93
|
+
from ${table} as e
|
|
94
|
+
where e.key = ${key} and not exists (select 1 from claimed)`));
|
|
95
|
+
const row = rows[0];
|
|
96
|
+
if (row === undefined)
|
|
97
|
+
continue;
|
|
98
|
+
if (row.state === "claimed")
|
|
99
|
+
return { kind: "claimed", token };
|
|
100
|
+
if (!timingSafeEqual(row.fingerprint ?? "", fingerprint))
|
|
101
|
+
return { kind: "mismatch" };
|
|
102
|
+
if (row.completed === true && row.response !== null) {
|
|
103
|
+
return { kind: "completed", response: row.response };
|
|
104
|
+
}
|
|
105
|
+
return { kind: "in_progress" };
|
|
106
|
+
}
|
|
107
|
+
// The row keeps changing under us: another request is working on this key right now.
|
|
108
|
+
return { kind: "in_progress" };
|
|
109
|
+
}
|
|
110
|
+
/** Renews the lease every third of its length until the returned function is called. */
|
|
111
|
+
function holdLease(key, token) {
|
|
112
|
+
const timer = setInterval(() => {
|
|
113
|
+
Promise.resolve(db.execute(sql `
|
|
114
|
+
update ${table} set locked_until = ${now()} + ${interval(leaseMs)}
|
|
115
|
+
where key = ${key} and locked_by = ${token} and completed_at is null`)).catch((error) => {
|
|
116
|
+
once.once("warn", "heartbeat", "Could not renew an idempotency key's lease; retrying.", {
|
|
117
|
+
error: errorText(error),
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
}, Math.max(1_000, Math.floor(leaseMs / 3)));
|
|
121
|
+
timer.unref?.();
|
|
122
|
+
return () => clearInterval(timer);
|
|
123
|
+
}
|
|
124
|
+
/** Stores the result, unless this request no longer holds the key (its lease ran out). */
|
|
125
|
+
async function complete(key, token, response, ttlMs) {
|
|
126
|
+
try {
|
|
127
|
+
const rows = rowsOf(await db.execute(sql `
|
|
128
|
+
with input as (select ${now()} as now)
|
|
129
|
+
update ${table} as t set response = ${response}, completed_at = input.now,
|
|
130
|
+
locked_by = null, locked_until = null, expires_at = input.now + ${interval(ttlMs)}
|
|
131
|
+
from input
|
|
132
|
+
where t.key = ${key} and t.locked_by = ${token}
|
|
133
|
+
returning 1`));
|
|
134
|
+
if (rows.length === 0) {
|
|
135
|
+
logger.warn("An idempotent request finished after its key's lease ran out, so its result was not stored. Raise lease if requests run this long.");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
// The work is done; failing the request now would only make the client retry it.
|
|
140
|
+
logger.error("Could not store an idempotent result; a retry may run it again.", {
|
|
141
|
+
error: errorText(error),
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** Frees the key so the client can retry. If this fails, the lease frees it soon anyway. */
|
|
146
|
+
async function release(key, token) {
|
|
147
|
+
try {
|
|
148
|
+
await db.execute(sql `delete from ${table} where key = ${key} and locked_by = ${token}`);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
logger.warn("Could not release an idempotency key; it frees itself when its lease ends.", {
|
|
152
|
+
error: errorText(error),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
async function requestFingerprint(request, custom) {
|
|
157
|
+
if (custom !== undefined)
|
|
158
|
+
return fingerprintOf(["custom", custom]);
|
|
159
|
+
if (request.bodyUsed) {
|
|
160
|
+
throw new GroundworkError("invalid_argument", "The request body was already read. Call handle() before reading it, or pass the fingerprint option.");
|
|
161
|
+
}
|
|
162
|
+
const url = new URL(request.url);
|
|
163
|
+
const body = request.body === null
|
|
164
|
+
? new Uint8Array(0)
|
|
165
|
+
: new Uint8Array(await request.clone().arrayBuffer());
|
|
166
|
+
return fingerprintOf([
|
|
167
|
+
"request",
|
|
168
|
+
request.method.toUpperCase(),
|
|
169
|
+
url.pathname + url.search,
|
|
170
|
+
body,
|
|
171
|
+
]);
|
|
172
|
+
}
|
|
173
|
+
return {
|
|
174
|
+
async handle(request, handleOptions, handler) {
|
|
175
|
+
if (typeof handleOptions !== "object" || handleOptions === null) {
|
|
176
|
+
throw new GroundworkError("invalid_argument", "handle() needs options with a scope.");
|
|
177
|
+
}
|
|
178
|
+
const scope = checkScope(handleOptions.scope);
|
|
179
|
+
const ttlMs = ttlOf(handleOptions.ttl);
|
|
180
|
+
const custom = checkFingerprint(handleOptions.fingerprint);
|
|
181
|
+
const header = request.headers.get("idempotency-key");
|
|
182
|
+
if (header === null) {
|
|
183
|
+
return handleOptions.required ? errorResponse("idempotency_key_missing") : handler();
|
|
184
|
+
}
|
|
185
|
+
const clientKey = parseIdempotencyKey(header);
|
|
186
|
+
if (clientKey === null)
|
|
187
|
+
return errorResponse("idempotency_key_invalid");
|
|
188
|
+
const key = storageKey("http", scope, clientKey);
|
|
189
|
+
const claim = await begin(key, scope, await requestFingerprint(request, custom), ttlMs);
|
|
190
|
+
if (claim.kind === "mismatch")
|
|
191
|
+
return errorResponse("idempotency_key_reused");
|
|
192
|
+
if (claim.kind === "in_progress")
|
|
193
|
+
return errorResponse("idempotency_key_in_use");
|
|
194
|
+
if (claim.kind === "completed") {
|
|
195
|
+
const stored = JSON.parse(claim.response);
|
|
196
|
+
if (isStoredResponse(stored))
|
|
197
|
+
return decodeResponse(stored);
|
|
198
|
+
// Only a damaged row gets here. Never replay something that can't be rebuilt.
|
|
199
|
+
return errorResponse("idempotency_key_reused");
|
|
200
|
+
}
|
|
201
|
+
const stop = holdLease(key, claim.token);
|
|
202
|
+
let response;
|
|
203
|
+
let body;
|
|
204
|
+
try {
|
|
205
|
+
response = await handler();
|
|
206
|
+
if (response.status < 200 || response.status >= 400) {
|
|
207
|
+
stop();
|
|
208
|
+
await release(key, claim.token);
|
|
209
|
+
return response;
|
|
210
|
+
}
|
|
211
|
+
body = new Uint8Array(await response.arrayBuffer());
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
stop();
|
|
215
|
+
await release(key, claim.token);
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
stop();
|
|
219
|
+
await complete(key, claim.token, JSON.stringify(encodeResponse(response, body)), ttlMs);
|
|
220
|
+
// The body was read to store it, so send a copy. Every header, cookies included, is kept.
|
|
221
|
+
return new Response(NULL_BODY_STATUSES.has(response.status) ? null : body, {
|
|
222
|
+
status: response.status,
|
|
223
|
+
statusText: response.statusText,
|
|
224
|
+
headers: response.headers,
|
|
225
|
+
});
|
|
226
|
+
},
|
|
227
|
+
async run(input, fn) {
|
|
228
|
+
if (typeof input !== "object" || input === null) {
|
|
229
|
+
throw new GroundworkError("invalid_argument", "run() needs { scope, key }.");
|
|
230
|
+
}
|
|
231
|
+
const scope = checkScope(input.scope);
|
|
232
|
+
if (typeof input.key !== "string" ||
|
|
233
|
+
input.key.length === 0 ||
|
|
234
|
+
input.key.length > MAX_RUN_KEY_LENGTH) {
|
|
235
|
+
throw new GroundworkError("invalid_argument", `key must be a string of 1 to ${MAX_RUN_KEY_LENGTH} characters.`);
|
|
236
|
+
}
|
|
237
|
+
if (typeof fn !== "function") {
|
|
238
|
+
throw new GroundworkError("invalid_argument", "run() needs a function to run.");
|
|
239
|
+
}
|
|
240
|
+
const custom = checkFingerprint(input.fingerprint);
|
|
241
|
+
const ttlMs = ttlOf(input.ttl);
|
|
242
|
+
const fingerprint = fingerprintOf(custom === undefined ? ["none"] : ["custom", custom]);
|
|
243
|
+
const key = storageKey("run", scope, input.key);
|
|
244
|
+
const claim = await begin(key, scope, fingerprint, ttlMs);
|
|
245
|
+
if (claim.kind === "mismatch" || claim.kind === "in_progress") {
|
|
246
|
+
return { ok: false, reason: claim.kind };
|
|
247
|
+
}
|
|
248
|
+
if (claim.kind === "completed") {
|
|
249
|
+
const stored = JSON.parse(claim.response);
|
|
250
|
+
return {
|
|
251
|
+
ok: true,
|
|
252
|
+
value: stored.value,
|
|
253
|
+
replayed: true,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
const stop = holdLease(key, claim.token);
|
|
257
|
+
let text;
|
|
258
|
+
try {
|
|
259
|
+
const value = await fn();
|
|
260
|
+
try {
|
|
261
|
+
text = JSON.stringify({ value });
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
throw new GroundworkError("invalid_argument", "run() results are stored as JSON, and this one can't be (a bigint or a cycle?).", { cause: error });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
catch (error) {
|
|
268
|
+
stop();
|
|
269
|
+
await release(key, claim.token);
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
stop();
|
|
273
|
+
await complete(key, claim.token, text, ttlMs);
|
|
274
|
+
// Return what a replay will return, so the first call and every retry see the same value.
|
|
275
|
+
const stored = JSON.parse(text);
|
|
276
|
+
return { ok: true, value: stored.value, replayed: false };
|
|
277
|
+
},
|
|
278
|
+
async cleanup() {
|
|
279
|
+
let total = 0;
|
|
280
|
+
for (;;) {
|
|
281
|
+
const [row] = rowsOf(await db.execute(sql `
|
|
282
|
+
with input as (select ${now()} as now),
|
|
283
|
+
deleted as (
|
|
284
|
+
delete from ${table} as t
|
|
285
|
+
where t.key in (
|
|
286
|
+
select e.key from ${table} as e, input
|
|
287
|
+
where e.expires_at <= input.now
|
|
288
|
+
and (e.completed_at is not null or e.locked_until <= input.now)
|
|
289
|
+
limit ${CLEANUP_BATCH}
|
|
290
|
+
)
|
|
291
|
+
returning 1
|
|
292
|
+
)
|
|
293
|
+
select count(*)::int as deleted from deleted`));
|
|
294
|
+
const deleted = row === undefined ? 0 : toNumber(row.deleted);
|
|
295
|
+
total += deleted;
|
|
296
|
+
if (deleted < CLEANUP_BATCH)
|
|
297
|
+
return total;
|
|
298
|
+
}
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
//# sourceMappingURL=idempotency.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idempotency.js","sourceRoot":"","sources":["../../src/idempotency/idempotency.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,GAAG,EAAE,MAAM,aAAa,CAAC;AAE5C,OAAO,EAAE,UAAU,EAAE,SAAS,EAAqB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAClG,OAAO,EAA2B,MAAM,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAiB,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAe,MAAM,uBAAuB,CAAC;AACrF,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAA6B,MAAM,+BAA+B,CAAC;AACnG,OAAO,EACL,cAAc,EACd,cAAc,EACd,aAAa,EACb,gBAAgB,EAChB,mBAAmB,GACpB,MAAM,WAAW,CAAC;AAC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ED,KAAK,CAAC,OAAO;YACX,IAAI,KAAK,GAAG,CAAC,CAAC;YACd,SAAS,CAAC;gBACR,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAClB,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,CAAA;oCACM,GAAG,EAAE;;4BAEb,KAAK;;oCAEG,KAAK;;;wBAGjB,aAAa;;;;yDAIoB,CAAC,CACjD,CAAC;gBACF,MAAM,OAAO,GAAG,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;gBAC9D,KAAK,IAAI,OAAO,CAAC;gBACjB,IAAI,OAAO,GAAG,aAAa;oBAAE,OAAO,KAAK,CAAC;YAC5C,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@vantedev/groundwork/idempotency`: Idempotency-Key handling with stored responses.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { createIdempotency } from "@vantedev/groundwork/idempotency";
|
|
6
|
+
*
|
|
7
|
+
* const idempotency = createIdempotency({ db, table: idempotencyKeys, secret });
|
|
8
|
+
*
|
|
9
|
+
* export async function POST(request: Request) {
|
|
10
|
+
* return idempotency.handle(request, { scope: `user:${user.id}` }, async () => {
|
|
11
|
+
* const order = await createOrder(await request.json());
|
|
12
|
+
* return Response.json(order, { status: 201 });
|
|
13
|
+
* });
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* // Anything that isn't an HTTP handler, such as a webhook event:
|
|
17
|
+
* const result = await idempotency.run({ scope: "stripe", key: event.id }, () => fulfil(event));
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @module
|
|
21
|
+
*/
|
|
22
|
+
export { IDEMPOTENCY_KEY_HEADER, type IdempotencyErrorCode, parseIdempotencyKey, REPLAYED_HEADER, } from "./http.ts";
|
|
23
|
+
export { createIdempotency, type IdempotencyOptions } from "./idempotency.ts";
|
|
24
|
+
export type { HandleOptions, Idempotency, Jsonify, RunInput, RunResult } from "./types.ts";
|
|
25
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/idempotency/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EACL,sBAAsB,EACtB,KAAK,oBAAoB,EACzB,mBAAmB,EACnB,eAAe,GAChB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,iBAAiB,EAAE,KAAK,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@vantedev/groundwork/idempotency`: Idempotency-Key handling with stored responses.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { createIdempotency } from "@vantedev/groundwork/idempotency";
|
|
6
|
+
*
|
|
7
|
+
* const idempotency = createIdempotency({ db, table: idempotencyKeys, secret });
|
|
8
|
+
*
|
|
9
|
+
* export async function POST(request: Request) {
|
|
10
|
+
* return idempotency.handle(request, { scope: `user:${user.id}` }, async () => {
|
|
11
|
+
* const order = await createOrder(await request.json());
|
|
12
|
+
* return Response.json(order, { status: 201 });
|
|
13
|
+
* });
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* // Anything that isn't an HTTP handler, such as a webhook event:
|
|
17
|
+
* const result = await idempotency.run({ scope: "stripe", key: event.id }, () => fulfil(event));
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @module
|
|
21
|
+
*/
|
|
22
|
+
export { IDEMPOTENCY_KEY_HEADER, parseIdempotencyKey, REPLAYED_HEADER, } from "./http.js";
|
|
23
|
+
export { createIdempotency } from "./idempotency.js";
|
|
24
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/idempotency/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EACL,sBAAsB,EAEtB,mBAAmB,EACnB,eAAe,GAChB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,iBAAiB,EAA2B,MAAM,kBAAkB,CAAC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How keys and fingerprints are hashed. Both are part of the storage format: changing either
|
|
3
|
+
* makes every stored key unrecognisable, so retries within the TTL would run again.
|
|
4
|
+
*/
|
|
5
|
+
export interface KeyHasher {
|
|
6
|
+
/** The stored `key`. `http` and `run` keys never collide, even with the same scope and key. */
|
|
7
|
+
storageKey(kind: "http" | "run", scope: string, key: string): string;
|
|
8
|
+
/** The stored `fingerprint` of what a key was used for. */
|
|
9
|
+
fingerprint(parts: readonly (string | Uint8Array)[]): string;
|
|
10
|
+
}
|
|
11
|
+
/** `subkey` is read on each use, so a lazily resolved secret is resolved on the first claim. */
|
|
12
|
+
export declare function createKeyHasher(subkey: () => Uint8Array): KeyHasher;
|
|
13
|
+
//# sourceMappingURL=keys.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../../src/idempotency/keys.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,+FAA+F;IAC/F,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;IACrE,2DAA2D;IAC3D,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,GAAG,UAAU,CAAC,EAAE,GAAG,MAAM,CAAC;CAC9D;AAED,gGAAgG;AAChG,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,UAAU,GAAG,SAAS,CAOnE"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { hmacSha256Parts } from "../internal/crypto.js";
|
|
2
|
+
/** `subkey` is read on each use, so a lazily resolved secret is resolved on the first claim. */
|
|
3
|
+
export function createKeyHasher(subkey) {
|
|
4
|
+
return {
|
|
5
|
+
storageKey: (kind, scope, key) => hmacSha256Parts(subkey(), [kind, scope, key]).toString("base64url"),
|
|
6
|
+
fingerprint: (parts) => hmacSha256Parts(subkey(), ["fingerprint", ...parts]).toString("base64url"),
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=keys.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keys.js","sourceRoot":"","sources":["../../src/idempotency/keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAaxD,gGAAgG;AAChG,MAAM,UAAU,eAAe,CAAC,MAAwB;IACtD,OAAO;QACL,UAAU,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE,CAC/B,eAAe,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC;QACrE,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CACrB,eAAe,CAAC,MAAM,EAAE,EAAE,CAAC,aAAa,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC;KAC7E,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { Duration } from "../internal/duration.ts";
|
|
2
|
+
/**
|
|
3
|
+
* What `T` becomes after a trip through JSON: `Date` becomes `string`, properties that hold
|
|
4
|
+
* functions, symbols or `undefined` disappear (in arrays they become `null`), and objects with
|
|
5
|
+
* `toJSON()` become what it returns. `run()` returns this type, because a replayed result is read
|
|
6
|
+
* back from JSON.
|
|
7
|
+
*/
|
|
8
|
+
export type Jsonify<T> = unknown extends T ? unknown : T extends {
|
|
9
|
+
toJSON(...args: never[]): infer J;
|
|
10
|
+
} ? Jsonify<J> : T extends string | number | boolean | null ? T : T extends bigint ? never : T extends Dropped ? undefined : T extends readonly unknown[] ? {
|
|
11
|
+
-readonly [K in keyof T]: JsonifyItem<T[K]>;
|
|
12
|
+
} : T extends object ? JsonObject<T> : never;
|
|
13
|
+
type Dropped = undefined | void | symbol | ((...args: never[]) => unknown);
|
|
14
|
+
/** In arrays, values JSON can't hold become `null`. Distributes over unions. */
|
|
15
|
+
type JsonifyItem<V> = V extends Dropped ? null : Jsonify<V>;
|
|
16
|
+
/** Keys whose value can be dropped become optional; keys that are always dropped disappear. */
|
|
17
|
+
type JsonObject<T> = Simplify<{
|
|
18
|
+
-readonly [K in keyof T as K extends string ? [Exclude<T[K], Dropped>] extends [never] ? never : [Extract<T[K], Dropped>] extends [never] ? K : never : never]: Jsonify<T[K]>;
|
|
19
|
+
} & {
|
|
20
|
+
-readonly [K in keyof T as K extends string ? [Exclude<T[K], Dropped>] extends [never] ? never : [Extract<T[K], Dropped>] extends [never] ? never : K : never]?: Jsonify<Exclude<T[K], Dropped>>;
|
|
21
|
+
}>;
|
|
22
|
+
type Simplify<T> = {
|
|
23
|
+
[K in keyof T]: T[K];
|
|
24
|
+
} & {};
|
|
25
|
+
export interface HandleOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Whose keys these are, such as `` `apikey:${key.id}` `` or `` `user:${user.id}` ``. Keys never
|
|
28
|
+
* match across scopes, so one client can't replay another's response.
|
|
29
|
+
*/
|
|
30
|
+
readonly scope: string;
|
|
31
|
+
/** Reject requests without an `Idempotency-Key` header (400). Defaults to `false`: they run unprotected. */
|
|
32
|
+
readonly required?: boolean | undefined;
|
|
33
|
+
/** How long a completed response is replayed. Defaults to the module's `ttl`. */
|
|
34
|
+
readonly ttl?: Duration | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* What identifies the request, instead of its method, path and body. Pass it when you've already
|
|
37
|
+
* read the body, for example the validated input as JSON.
|
|
38
|
+
*/
|
|
39
|
+
readonly fingerprint?: string | Uint8Array | undefined;
|
|
40
|
+
}
|
|
41
|
+
export interface RunInput {
|
|
42
|
+
/** Whose key it is, such as `"stripe"` for webhook event ids or `` `user:${id}` ``. */
|
|
43
|
+
readonly scope: string;
|
|
44
|
+
/** The idempotency key: a webhook event id, a client-supplied key… 1 to 255 characters. */
|
|
45
|
+
readonly key: string;
|
|
46
|
+
/**
|
|
47
|
+
* What the key was first used for. When given, a later call with the same key and a different
|
|
48
|
+
* fingerprint gets `{ ok: false, reason: "mismatch" }`. Defaults to none: any call replays.
|
|
49
|
+
*/
|
|
50
|
+
readonly fingerprint?: string | Uint8Array | undefined;
|
|
51
|
+
/** How long the result is replayed. Defaults to the module's `ttl`. */
|
|
52
|
+
readonly ttl?: Duration | undefined;
|
|
53
|
+
}
|
|
54
|
+
export type RunResult<T> = {
|
|
55
|
+
readonly ok: true;
|
|
56
|
+
/** The function's result, as stored: the same value on the first call and every replay. */
|
|
57
|
+
readonly value: T;
|
|
58
|
+
/** `true` when this is a stored result and the function did not run. */
|
|
59
|
+
readonly replayed: boolean;
|
|
60
|
+
} | {
|
|
61
|
+
readonly ok: false;
|
|
62
|
+
/**
|
|
63
|
+
* - `mismatch`: the key was already used with a different fingerprint.
|
|
64
|
+
* - `in_progress`: the first call with this key is still running.
|
|
65
|
+
*/
|
|
66
|
+
readonly reason: "mismatch" | "in_progress";
|
|
67
|
+
};
|
|
68
|
+
export interface Idempotency {
|
|
69
|
+
/**
|
|
70
|
+
* Makes an HTTP handler safe to retry, following draft-ietf-httpapi-idempotency-key-header:
|
|
71
|
+
*
|
|
72
|
+
* - no `Idempotency-Key`: runs `handler` (or 400 when `required`);
|
|
73
|
+
* - a key seen for the first time: runs `handler` and stores a 2xx or 3xx response;
|
|
74
|
+
* - the same key and request again: replays the stored response with `Idempotent-Replayed: true`;
|
|
75
|
+
* - the same key with a different request: 422;
|
|
76
|
+
* - the same key while the first request is still running: 409.
|
|
77
|
+
*
|
|
78
|
+
* Errors (4xx, 5xx or a throw) are not stored, so the client can retry with the same key. The
|
|
79
|
+
* request's body is read from a clone, so `handler` can still read it.
|
|
80
|
+
*/
|
|
81
|
+
handle(request: Request, options: HandleOptions, handler: () => Response | Promise<Response>): Promise<Response>;
|
|
82
|
+
/**
|
|
83
|
+
* Runs `fn` at most once per scope and key, and returns its result again on every later call.
|
|
84
|
+
* For webhooks, server actions and anything else that isn't an HTTP handler, or to store only
|
|
85
|
+
* part of a response. If `fn` throws, nothing is stored and the next call runs it again.
|
|
86
|
+
*/
|
|
87
|
+
run<T>(input: RunInput, fn: () => T | Promise<T>): Promise<RunResult<Jsonify<Awaited<T>>>>;
|
|
88
|
+
/** Deletes expired keys. Run it every hour or so; returns how many rows it deleted. */
|
|
89
|
+
cleanup(): Promise<number>;
|
|
90
|
+
}
|
|
91
|
+
export {};
|
|
92
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/idempotency/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAExD;;;;;GAKG;AACH,MAAM,MAAM,OAAO,CAAC,CAAC,IAAI,OAAO,SAAS,CAAC,GACtC,OAAO,GACP,CAAC,SAAS;IAAE,MAAM,CAAC,GAAG,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,CAAC,CAAA;CAAE,GAC7C,OAAO,CAAC,CAAC,CAAC,GACV,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GACxC,CAAC,GACD,CAAC,SAAS,MAAM,GACd,KAAK,GACL,CAAC,SAAS,OAAO,GACf,SAAS,GACT,CAAC,S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AO,EAChB,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,GAC1C,OAAO,CAAC,QAAQ,CAAC,CAAC;IACrB;;;;OAIG;IACH,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3F,uFAAuF;IACvF,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC5B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/idempotency/types.ts"],"names":[],"mappings":""}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { type ApiKeyAuditAction } from "./api-keys/audit.ts";
|
|
2
|
+
import type { ApiKeyEvent, ApiKeyRateLimit, ApiKeys } from "./api-keys/types.ts";
|
|
3
|
+
import type { RedactRule } from "./audit/json.ts";
|
|
4
|
+
import type { AuditLog } from "./audit/types.ts";
|
|
5
|
+
import type { Idempotency } from "./idempotency/types.ts";
|
|
6
|
+
import type { Clock } from "./internal/clock.ts";
|
|
7
|
+
import { type SecretSource } from "./internal/crypto.ts";
|
|
8
|
+
import type { GroundworkDatabase } from "./internal/db.ts";
|
|
9
|
+
import type { Duration } from "./internal/duration.ts";
|
|
10
|
+
import type { Logger } from "./internal/logger.ts";
|
|
11
|
+
import type { Jobs } from "./jobs/types.ts";
|
|
12
|
+
import type { OnError, RateLimiter, RateLimitStore } from "./rate-limit/types.ts";
|
|
13
|
+
import type { ApiKeysTable } from "./schema/api-keys.ts";
|
|
14
|
+
import type { AuditLogTable } from "./schema/audit-log.ts";
|
|
15
|
+
import type { IdempotencyKeysTable } from "./schema/idempotency-keys.ts";
|
|
16
|
+
import type { JobSchedulesTable, JobsTable } from "./schema/jobs.ts";
|
|
17
|
+
import type { RateLimitsTable } from "./schema/rate-limits.ts";
|
|
18
|
+
export type { Clock } from "./internal/clock.ts";
|
|
19
|
+
export type { Secret, SecretSource } from "./internal/crypto.ts";
|
|
20
|
+
export type { GroundworkDatabase } from "./internal/db.ts";
|
|
21
|
+
export type { Duration, DurationUnit } from "./internal/duration.ts";
|
|
22
|
+
export { GroundworkError, type GroundworkErrorCode, isGroundworkError } from "./internal/errors.ts";
|
|
23
|
+
export { type ContextFirstLogger, type LogContext, type Logger, pinoLogger, } from "./internal/logger.ts";
|
|
24
|
+
export interface GroundworkOptions<TAuditAction extends string = never, TAuditEntity extends string = string, TScopes extends Record<string, string> = Record<never, string>> {
|
|
25
|
+
/** Your Drizzle Postgres database, from any driver. */
|
|
26
|
+
readonly db: GroundworkDatabase;
|
|
27
|
+
/**
|
|
28
|
+
* Your groundwork tables, usually `import * as tables from "./db/schema/groundwork"`.
|
|
29
|
+
* Modules whose table is missing throw when you first use them.
|
|
30
|
+
*/
|
|
31
|
+
readonly tables: {
|
|
32
|
+
readonly rateLimits?: RateLimitsTable | undefined;
|
|
33
|
+
readonly auditLog?: AuditLogTable | undefined;
|
|
34
|
+
readonly apiKeys?: ApiKeysTable | undefined;
|
|
35
|
+
readonly jobs?: JobsTable | undefined;
|
|
36
|
+
readonly jobSchedules?: JobSchedulesTable | undefined;
|
|
37
|
+
readonly idempotencyKeys?: IdempotencyKeysTable | undefined;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* At least 32 bytes. Changing it invalidates every API key and resets every rate limit. Reusing
|
|
41
|
+
* a secret the app already has (such as `BETTER_AUTH_SECRET`) is safe: groundwork only uses keys
|
|
42
|
+
* derived from it with HKDF, never the secret itself.
|
|
43
|
+
*
|
|
44
|
+
* Pass a function to read it on first use instead, for example when the environment isn't set
|
|
45
|
+
* during `next build`, or in a worker that only runs jobs: `secret: () => env.GROUNDWORK_SECRET`.
|
|
46
|
+
*/
|
|
47
|
+
readonly secret: SecretSource;
|
|
48
|
+
/** Defaults to `console` (warnings and errors only). */
|
|
49
|
+
readonly logger?: Logger | undefined;
|
|
50
|
+
/** Defaults to each store's own clock. Inject one in tests. */
|
|
51
|
+
readonly clock?: Clock | undefined;
|
|
52
|
+
readonly rateLimit?: {
|
|
53
|
+
/** Defaults to `"memory"`. */
|
|
54
|
+
readonly onError?: OnError | undefined;
|
|
55
|
+
/** Defaults to `"1s"`. */
|
|
56
|
+
readonly timeout?: Duration | false | undefined;
|
|
57
|
+
readonly memory?: {
|
|
58
|
+
readonly maxKeys?: number | undefined;
|
|
59
|
+
} | undefined;
|
|
60
|
+
/** Another store, such as `redisStore()`, instead of the Postgres table. */
|
|
61
|
+
readonly store?: RateLimitStore | undefined;
|
|
62
|
+
} | undefined;
|
|
63
|
+
readonly audit?: {
|
|
64
|
+
/** Every action your app records. `gw.audit` is typed from this list, plus `api_key.*`. */
|
|
65
|
+
readonly actions: readonly TAuditAction[];
|
|
66
|
+
/** Entity types. When given, `entity.type` is typed and checked too (plus `"api_key"`). */
|
|
67
|
+
readonly entityTypes?: readonly TAuditEntity[] | undefined;
|
|
68
|
+
/** Keys to redact in `changes` and `metadata`, on top of `DEFAULT_REDACT`. */
|
|
69
|
+
readonly redact?: readonly RedactRule[] | undefined;
|
|
70
|
+
/** `false` to use only your own `redact` rules. */
|
|
71
|
+
readonly redactDefaults?: boolean | undefined;
|
|
72
|
+
} | undefined;
|
|
73
|
+
readonly apiKeys?: {
|
|
74
|
+
/** The start of every key, such as `"vnt"` for `vnt_…`. */
|
|
75
|
+
readonly namespace: string;
|
|
76
|
+
/** Every scope your API knows, with a description. `gw.apiKeys` is typed from it. */
|
|
77
|
+
readonly scopes: TScopes;
|
|
78
|
+
/** Append a CRC32 checksum to new keys. Defaults to `true`. */
|
|
79
|
+
readonly checksum?: boolean | undefined;
|
|
80
|
+
/** The limit new keys get by default: 60 per minute. `null` for none. Uses `gw.rateLimit`. */
|
|
81
|
+
readonly defaultRateLimit?: ApiKeyRateLimit | null | undefined;
|
|
82
|
+
/** The hash an older system stored for a key, so its keys keep working. See the API-key docs. */
|
|
83
|
+
readonly legacyHash?: ((key: string) => string) | undefined;
|
|
84
|
+
/** Called after every change to a key, after the audit entry is written. */
|
|
85
|
+
readonly onEvent?: ((event: ApiKeyEvent<keyof TScopes & string>) => void | Promise<void>) | undefined;
|
|
86
|
+
/** Receives background writes, such as Next.js `after` or `ctx.waitUntil`. */
|
|
87
|
+
readonly waitUntil?: ((promise: Promise<unknown>) => void) | undefined;
|
|
88
|
+
} | undefined;
|
|
89
|
+
readonly jobs?: {
|
|
90
|
+
/** How long a claimed job is reserved; workers renew it while the job runs. Defaults to `"1m"`. */
|
|
91
|
+
readonly lease?: Duration | undefined;
|
|
92
|
+
/** Identifies this worker in `locked_by`. */
|
|
93
|
+
readonly workerId?: string | undefined;
|
|
94
|
+
/**
|
|
95
|
+
* Schedules `gw.rateLimit.cleanup()` every hour when rate limiting is set up. Defaults to
|
|
96
|
+
* `true`.
|
|
97
|
+
*/
|
|
98
|
+
readonly rateLimitCleanup?: boolean | undefined;
|
|
99
|
+
/**
|
|
100
|
+
* Schedules `gw.idempotency.cleanup()` every hour when the idempotency table is set up.
|
|
101
|
+
* Defaults to `true`.
|
|
102
|
+
*/
|
|
103
|
+
readonly idempotencyCleanup?: boolean | undefined;
|
|
104
|
+
} | undefined;
|
|
105
|
+
readonly idempotency?: {
|
|
106
|
+
/** How long a completed response is replayed. Defaults to `"24h"`. */
|
|
107
|
+
readonly ttl?: Duration | undefined;
|
|
108
|
+
/** How soon a crashed request frees its key; renewed while the request runs. Defaults to `"30s"`. */
|
|
109
|
+
readonly lease?: Duration | undefined;
|
|
110
|
+
} | undefined;
|
|
111
|
+
}
|
|
112
|
+
export interface Groundwork<TAuditAction extends string = never, TAuditEntity extends string = string, TScope extends string = never> {
|
|
113
|
+
readonly rateLimit: RateLimiter;
|
|
114
|
+
/** Also accepts groundwork's own `api_key.*` actions, which API-key changes record. */
|
|
115
|
+
readonly audit: AuditLog<TAuditAction | ApiKeyAuditAction, TAuditEntity | "api_key">;
|
|
116
|
+
readonly apiKeys: ApiKeys<TScope>;
|
|
117
|
+
readonly jobs: Jobs;
|
|
118
|
+
readonly idempotency: Idempotency;
|
|
119
|
+
}
|
|
120
|
+
/** Wires every module to one database, one secret, one logger and one clock. */
|
|
121
|
+
export declare function createGroundwork<const TAuditAction extends string = never, const TAuditEntity extends string = string, const TScopes extends Record<string, string> = Record<never, string>>(options: GroundworkOptions<TAuditAction, TAuditEntity, TScopes>): Groundwork<TAuditAction, TAuditEntity, keyof TScopes & string>;
|
|
122
|
+
//# sourceMappingURL=index.d.ts.map
|