-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathissue-184-idempotency.patch
More file actions
683 lines (671 loc) · 27.3 KB
/
Copy pathissue-184-idempotency.patch
File metadata and controls
683 lines (671 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
diff --git a/apps/access-api/prisma/migrations/20260724090000_add_idempotency_key/migration.sql b/apps/access-api/prisma/migrations/20260724090000_add_idempotency_key/migration.sql
new file mode 100644
index 0000000..3835cbb
--- /dev/null
+++ b/apps/access-api/prisma/migrations/20260724090000_add_idempotency_key/migration.sql
@@ -0,0 +1,35 @@
+-- Additive new table: safe to apply directly against a live database with a
+-- single `migrate deploy`. No existing table or column is touched, so there
+-- is no dual-write/backfill phase to sequence — see CONTRIBUTING.md >
+-- "Database Migrations: Direct vs. Expand/Contract" for why this qualifies
+-- as the simple, direct case.
+
+-- CreateEnum
+CREATE TYPE "IdempotencyKeyStatus" AS ENUM ('pending', 'completed');
+
+-- CreateTable
+CREATE TABLE "IdempotencyKey" (
+ "id" TEXT NOT NULL,
+ "key" TEXT NOT NULL,
+ "route" TEXT NOT NULL,
+ "requestHash" TEXT NOT NULL,
+ "status" "IdempotencyKeyStatus" NOT NULL DEFAULT 'pending',
+ "responseStatus" INTEGER,
+ "responseBody" JSONB,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ "expiresAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "IdempotencyKey_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+-- Enforces "same key + route = single outcome" at the DB level, which is
+-- also what we rely on to resolve the race between two concurrent retries
+-- that both miss the initial SELECT: the loser's INSERT fails P2002 and is
+-- told to treat the request as already in-flight rather than double-write.
+CREATE UNIQUE INDEX "IdempotencyKey_key_route_key" ON "IdempotencyKey"("key", "route");
+
+-- CreateIndex
+-- Serves the periodic cleanup job's `WHERE expiresAt < now()` sweep.
+CREATE INDEX "IdempotencyKey_expiresAt_idx" ON "IdempotencyKey"("expiresAt");
diff --git a/apps/access-api/prisma/schema.prisma b/apps/access-api/prisma/schema.prisma
index d38f46b..2eb8418 100644
--- a/apps/access-api/prisma/schema.prisma
+++ b/apps/access-api/prisma/schema.prisma
@@ -389,6 +389,44 @@ model OutboxEvent {
@@index([correlationId])
}
+// --- Client-Facing Request Idempotency (Issue #184) ---
+//
+// Guards mutating /v1 routes (role assignment, policy changes, resource
+// changes) against duplicate execution when a client retries a request
+// after a successful-but-unacknowledged response. This is distinct from
+// OutboxEvent/ProcessedEvent, which guarantee delivery of *outbound*
+// integration events and dedupe *inbound* on-chain events respectively —
+// IdempotencyKey dedupes the *inbound* HTTP mutation itself.
+//
+// requestHash is a hash of the normalised request body, so replaying the
+// same key with a different payload is detectable and rejected with 409
+// rather than silently returning a stale cached response.
+model IdempotencyKey {
+ id String @id @default(uuid())
+ key String // client-supplied Idempotency-Key header value
+ route String // "<METHOD> <route pattern>", e.g. "POST /v1/communities/:communityId/members/:wallet/roles"
+ requestHash String // sha256 of the normalised (stable-sorted) request body
+ status IdempotencyKeyStatus @default(pending)
+ responseStatus Int?
+ responseBody Json?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ // TTL cleanup boundary — rows past this point are safe to purge since the
+ // client is expected to have either received a response or given up.
+ expiresAt DateTime
+
+ // One outcome per (key, route): the same Idempotency-Key is allowed to be
+ // reused across different routes (e.g. a client-generated UUID reused per
+ // logical operation), but must be unique per route.
+ @@unique([key, route])
+ @@index([expiresAt])
+}
+
+enum IdempotencyKeyStatus {
+ pending
+ completed
+}
+
// --- Chain Indexer Reorg Safety & Idempotency ---
model ProcessedEvent {
diff --git a/apps/access-api/src/lib/idempotency.test.ts b/apps/access-api/src/lib/idempotency.test.ts
new file mode 100644
index 0000000..3503223
--- /dev/null
+++ b/apps/access-api/src/lib/idempotency.test.ts
@@ -0,0 +1,232 @@
+/**
+ * idempotency.test.ts
+ *
+ * Unit tests for the Idempotency-Key middleware (issue #184):
+ * - No header → passthrough, no dedup
+ * - Same key + same payload replayed after completion → cached response,
+ * no second call to the wrapped handler / no second mutation
+ * - Same key + different payload → 409 Conflict
+ * - Concurrent duplicate insert (unique constraint race) → 409 Conflict
+ * - 5xx responses drop the pending row instead of caching the failure
+ *
+ * A hand-rolled Prisma mock is used (matching the style of
+ * outboxService.test.ts) rather than a real Postgres instance, since the
+ * behaviour under test is the middleware's control flow, not Postgres
+ * locking semantics.
+ */
+import Fastify, { FastifyInstance } from "fastify";
+import {
+ createIdempotencyPreHandler,
+ createIdempotencyOnSend,
+ hashRequestBody,
+} from "./idempotency";
+
+function makeDb() {
+ const rows = new Map<string, any>();
+ let idCounter = 0;
+
+ const db: any = {
+ idempotencyKey: {
+ findUnique: jest.fn(async ({ where }: any) => {
+ const { key, route } = where.key_route;
+ return rows.get(`${key}::${route}`) ?? null;
+ }),
+ create: jest.fn(async ({ data }: any) => {
+ const compositeKey = `${data.key}::${data.route}`;
+ if (rows.has(compositeKey)) {
+ const err: any = new Error("Unique constraint failed");
+ err.code = "P2002";
+ throw err;
+ }
+ idCounter++;
+ const record = {
+ id: `idem-${idCounter}`,
+ ...data,
+ responseStatus: null,
+ responseBody: null,
+ };
+ rows.set(compositeKey, record);
+ return record;
+ }),
+ update: jest.fn(async ({ where, data }: any) => {
+ const record = [...rows.values()].find((r) => r.id === where.id);
+ if (!record) throw new Error("not found");
+ Object.assign(record, data);
+ return record;
+ }),
+ delete: jest.fn(async ({ where }: any) => {
+ for (const [k, v] of rows.entries()) {
+ if (v.id === where.id) rows.delete(k);
+ }
+ }),
+ },
+ };
+
+ return { db, rows };
+}
+
+/** Builds a minimal Fastify app with one mutating route wrapping a spy. */
+function buildApp(db: any, handlerSpy: jest.Mock) {
+ const app = Fastify();
+ const idempotencyPreHandler = createIdempotencyPreHandler(db);
+ const idempotencyOnSend = createIdempotencyOnSend(db);
+
+ app.post(
+ "/v1/communities/:communityId/members/:wallet/roles",
+ { preHandler: [idempotencyPreHandler], onSend: [idempotencyOnSend] },
+ async (request, reply) => {
+ handlerSpy(request.body);
+ return reply.status(200).send({ assigned: true, role: "contributor" });
+ },
+ );
+
+ app.post(
+ "/v1/flaky",
+ { preHandler: [idempotencyPreHandler], onSend: [idempotencyOnSend] },
+ async (_request, reply) => {
+ handlerSpy();
+ return reply.status(500).send({ error: "boom" });
+ },
+ );
+
+ return app;
+}
+
+describe("idempotency middleware", () => {
+ let app: FastifyInstance;
+ let handlerSpy: jest.Mock;
+ let db: ReturnType<typeof makeDb>["db"];
+
+ beforeEach(() => {
+ handlerSpy = jest.fn();
+ ({ db } = makeDb());
+ app = buildApp(db, handlerSpy);
+ });
+
+ afterEach(async () => {
+ await app.close();
+ });
+
+ it("passes requests through untouched when no Idempotency-Key header is sent", async () => {
+ const res = await app.inject({
+ method: "POST",
+ url: "/v1/communities/community-1/members/0xabc/roles",
+ payload: { role: "contributor" },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(handlerSpy).toHaveBeenCalledTimes(1);
+ expect(db.idempotencyKey.create).not.toHaveBeenCalled();
+ });
+
+ it("executes the mutation once and returns the identical cached response on retry", async () => {
+ const payload = { role: "contributor" };
+ const headers = { "idempotency-key": "retry-key-1" };
+
+ const first = await app.inject({
+ method: "POST",
+ url: "/v1/communities/community-1/members/0xabc/roles",
+ headers,
+ payload,
+ });
+ expect(first.statusCode).toBe(200);
+ expect(handlerSpy).toHaveBeenCalledTimes(1);
+
+ // Simulate a client retry after a successful-but-unacknowledged response.
+ const second = await app.inject({
+ method: "POST",
+ url: "/v1/communities/community-1/members/0xabc/roles",
+ headers,
+ payload,
+ });
+
+ expect(second.statusCode).toBe(first.statusCode);
+ expect(second.json()).toEqual(first.json());
+ // The handler (and therefore the underlying mutation / outbox event)
+ // must only have run once.
+ expect(handlerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns 409 when the same key is reused with a different payload", async () => {
+ const headers = { "idempotency-key": "retry-key-2" };
+
+ const first = await app.inject({
+ method: "POST",
+ url: "/v1/communities/community-1/members/0xabc/roles",
+ headers,
+ payload: { role: "contributor" },
+ });
+ expect(first.statusCode).toBe(200);
+
+ const second = await app.inject({
+ method: "POST",
+ url: "/v1/communities/community-1/members/0xabc/roles",
+ headers,
+ payload: { role: "admin" },
+ });
+
+ expect(second.statusCode).toBe(409);
+ expect(handlerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns 409 for a genuinely concurrent duplicate (unique constraint race)", async () => {
+ const headers = { "idempotency-key": "retry-key-3" };
+ const payload = { role: "contributor" };
+
+ const [first, second] = await Promise.all([
+ app.inject({
+ method: "POST",
+ url: "/v1/communities/community-1/members/0xabc/roles",
+ headers,
+ payload,
+ }),
+ app.inject({
+ method: "POST",
+ url: "/v1/communities/community-1/members/0xabc/roles",
+ headers,
+ payload,
+ }),
+ ]);
+
+ const statuses = [first.statusCode, second.statusCode].sort();
+ // Exactly one request succeeds; the other is told to back off.
+ expect(statuses).toEqual([200, 409]);
+ expect(handlerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not cache a 5xx response, allowing a genuine re-attempt", async () => {
+ const headers = { "idempotency-key": "retry-key-4" };
+
+ const first = await app.inject({
+ method: "POST",
+ url: "/v1/flaky",
+ headers,
+ payload: {},
+ });
+ expect(first.statusCode).toBe(500);
+ expect(handlerSpy).toHaveBeenCalledTimes(1);
+
+ const second = await app.inject({
+ method: "POST",
+ url: "/v1/flaky",
+ headers,
+ payload: {},
+ });
+ expect(second.statusCode).toBe(500);
+ // Handler re-runs because the failed attempt's pending row was dropped.
+ expect(handlerSpy).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("hashRequestBody", () => {
+ it("is stable regardless of key ordering", () => {
+ const a = hashRequestBody({ role: "admin", wallet: "0xabc" });
+ const b = hashRequestBody({ wallet: "0xabc", role: "admin" });
+ expect(a).toBe(b);
+ });
+
+ it("differs for different payloads", () => {
+ const a = hashRequestBody({ role: "admin" });
+ const b = hashRequestBody({ role: "contributor" });
+ expect(a).not.toBe(b);
+ });
+});
diff --git a/apps/access-api/src/lib/idempotency.ts b/apps/access-api/src/lib/idempotency.ts
new file mode 100644
index 0000000..fbffa8d
--- /dev/null
+++ b/apps/access-api/src/lib/idempotency.ts
@@ -0,0 +1,224 @@
+/**
+ * idempotency.ts
+ *
+ * Client-facing request idempotency for mutating /v1 routes (issue #184).
+ *
+ * The outbox pattern (see services/outboxService.ts) already guarantees no
+ * *outbound* integration event is lost. It says nothing about the *inbound*
+ * HTTP request: a client that retries a POST/PATCH/DELETE after a
+ * successful-but-unacknowledged response (a very common pattern for
+ * webhook-driven integrations, e.g. Discord bots reacting to a timeout)
+ * would otherwise re-execute the mutation and emit a second outbox event.
+ *
+ * Usage: attach both hooks to a route's options —
+ *
+ * app.post(
+ * '/v1/communities/:communityId/members/:wallet/roles',
+ * {
+ * schema: assignMemberRoleSchema,
+ * preHandler: [authenticateApiKey, idempotencyPreHandler],
+ * onSend: [idempotencyOnSend],
+ * },
+ * handler,
+ * );
+ *
+ * Design:
+ * - The Idempotency-Key header is optional. Requests without it behave
+ * exactly as before — this is additive, not a breaking change.
+ * - When present, the (key, route) pair is looked up in the IdempotencyKey
+ * table. A hit with a matching requestHash short-circuits straight to
+ * the cached response. A hit with a different requestHash is a 409 —
+ * the same key was reused for a different logical request. A miss
+ * inserts a "pending" row (unique on (key, route)) and lets the handler
+ * run; onSend then fills in the response and flips it to "completed".
+ * - The unique constraint on (key, route) is what resolves the race
+ * between two truly concurrent retries that both miss the initial
+ * SELECT: the loser's INSERT fails with P2002 and is told the request
+ * is already in flight (409) instead of double-executing the mutation.
+ * - This does not wrap the domain mutation's own Prisma $transaction —
+ * service methods each manage their own transaction internally (see
+ * memberService.ts, resourceService.ts). Instead the *pending* row is
+ * written before the handler runs and the *completed* row is written
+ * in onSend, once the mutation (and its outbox write) has already
+ * committed. A crash between those two points simply leaves a stale
+ * "pending" row, which cleanupExpiredIdempotencyKeys reaps via TTL —
+ * the retried request then re-executes exactly once, which is safe
+ * because the original attempt never committed a response either.
+ */
+import crypto from "crypto";
+import type { FastifyReply, FastifyRequest } from "fastify";
+import type { PrismaClient } from "@prisma/client";
+import { conflict } from "../errors";
+
+const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000; // 24h
+
+declare module "fastify" {
+ interface FastifyRequest {
+ idempotencyRecordId?: string;
+ }
+}
+
+/** Deterministic stringify so key ordering in the body never changes the hash. */
+function stableStringify(value: unknown): string {
+ if (value === null || typeof value !== "object") {
+ return JSON.stringify(value ?? null);
+ }
+ if (Array.isArray(value)) {
+ return `[${value.map(stableStringify).join(",")}]`;
+ }
+ const keys = Object.keys(value as Record<string, unknown>).sort();
+ return `{${keys
+ .map(
+ (k) => `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[k])}`,
+ )
+ .join(",")}}`;
+}
+
+export function hashRequestBody(body: unknown): string {
+ return crypto.createHash("sha256").update(stableStringify(body ?? {})).digest("hex");
+}
+
+/** "<METHOD> <route pattern>", e.g. "POST /v1/communities/:communityId/members/:wallet/roles" */
+export function routeIdentifier(request: FastifyRequest): string {
+ const pattern =
+ (request as any).routeOptions?.url ??
+ (request as any).routerPath ??
+ request.url.split("?")[0];
+ return `${request.method} ${pattern}`;
+}
+
+function getIdempotencyKeyHeader(request: FastifyRequest): string | undefined {
+ const header = request.headers["idempotency-key"];
+ const value = Array.isArray(header) ? header[0] : header;
+ return value && value.trim() ? value.trim() : undefined;
+}
+
+/**
+ * preHandler: resolves an Idempotency-Key header against prior outcomes for
+ * this route before the mutation runs.
+ */
+export function createIdempotencyPreHandler(prisma: PrismaClient) {
+ return async function idempotencyPreHandler(
+ request: FastifyRequest,
+ reply: FastifyReply,
+ ): Promise<void> {
+ const key = getIdempotencyKeyHeader(request);
+ if (!key) return; // Idempotency-Key is opt-in; no header means no dedup.
+
+ const route = routeIdentifier(request);
+ const requestHash = hashRequestBody(request.body);
+
+ const existing = await (prisma as any).idempotencyKey.findUnique({
+ where: { key_route: { key, route } },
+ });
+
+ if (existing) {
+ if (existing.requestHash !== requestHash) {
+ await reply
+ .status(409)
+ .send(
+ conflict(
+ "This Idempotency-Key was already used with a different request payload",
+ ),
+ );
+ return;
+ }
+
+ if (existing.status === "completed") {
+ await reply.status(existing.responseStatus ?? 200).send(existing.responseBody ?? {});
+ return;
+ }
+
+ // Same key, same payload, but the original request hasn't finished
+ // (still "pending") — this is a genuinely concurrent retry racing the
+ // first attempt, not the "retry after timeout" case. Tell the caller
+ // to back off rather than let two copies of the mutation run at once.
+ await reply
+ .status(409)
+ .send(conflict("A request with this Idempotency-Key is already in progress"));
+ return;
+ }
+
+ try {
+ const created = await (prisma as any).idempotencyKey.create({
+ data: {
+ key,
+ route,
+ requestHash,
+ status: "pending",
+ expiresAt: new Date(Date.now() + DEFAULT_TTL_MS),
+ },
+ });
+ request.idempotencyRecordId = created.id;
+ } catch (err: any) {
+ // Unique constraint race: another concurrent request won the insert.
+ if (err?.code === "P2002") {
+ await reply
+ .status(409)
+ .send(conflict("A request with this Idempotency-Key is already in progress"));
+ return;
+ }
+ throw err;
+ }
+ };
+}
+
+/**
+ * onSend: records the mutation's outcome against the pending row created by
+ * idempotencyPreHandler, so subsequent replays of the same key return the
+ * identical response instead of re-executing.
+ */
+export function createIdempotencyOnSend(prisma: PrismaClient) {
+ return async function idempotencyOnSend(
+ request: FastifyRequest,
+ reply: FastifyReply,
+ payload: unknown,
+ ): Promise<unknown> {
+ const recordId = request.idempotencyRecordId;
+ if (!recordId) return payload;
+
+ // 5xx responses mean the mutation may not have committed at all (or
+ // failed for a transient reason) — drop the pending row so a retry with
+ // the same key is free to actually re-attempt the mutation instead of
+ // being stuck behind a dead "pending" record until it expires.
+ if (reply.statusCode >= 500) {
+ await (prisma as any).idempotencyKey.delete({ where: { id: recordId } }).catch(() => {});
+ return payload;
+ }
+
+ let responseBody: unknown = payload;
+ if (typeof payload === "string") {
+ try {
+ responseBody = JSON.parse(payload);
+ } catch {
+ responseBody = payload;
+ }
+ }
+
+ await (prisma as any).idempotencyKey
+ .update({
+ where: { id: recordId },
+ data: {
+ status: "completed",
+ responseStatus: reply.statusCode,
+ responseBody: responseBody as any,
+ },
+ })
+ .catch(() => {});
+
+ return payload;
+ };
+}
+
+/**
+ * Deletes expired IdempotencyKey rows. Intended to be run on a schedule
+ * alongside the existing background workers (see src/workers/) — e.g. a
+ * periodic call from the same process that runs outboxWorker, or a small
+ * standalone cron entrypoint.
+ */
+export async function cleanupExpiredIdempotencyKeys(prisma: PrismaClient): Promise<number> {
+ const result = await (prisma as any).idempotencyKey.deleteMany({
+ where: { expiresAt: { lt: new Date() } },
+ });
+ return result.count;
+}
diff --git a/apps/access-api/src/routes.ts b/apps/access-api/src/routes.ts
index 1b86ad2..1033cac 100644
--- a/apps/access-api/src/routes.ts
+++ b/apps/access-api/src/routes.ts
@@ -62,6 +62,10 @@ import {
authenticateSessionOrApiKey,
verifySiweSignature,
} from "./lib/auth/auth";
+import {
+ createIdempotencyPreHandler,
+ createIdempotencyOnSend,
+} from "./lib/idempotency";
import crypto from "crypto";
function getRequesterWallet(request: FastifyRequest): string {
@@ -114,6 +118,12 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
const moderationService = getModerationService(prisma);
const resourceService = getResourceService(prisma);
+ // Idempotency-Key support for mutating routes (issue #184). Opt-in per
+ // request via the `Idempotency-Key` header; applied to role assignment,
+ // policy (access override), and resource mutation routes below.
+ const idempotencyPreHandler = createIdempotencyPreHandler(prisma);
+ const idempotencyOnSend = createIdempotencyOnSend(prisma);
+
// --- SIWE Authentication Routes ---
// Generate a SIWE nonce
@@ -397,7 +407,7 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
);
// POST /v1/communities/:communityId/members/:wallet/roles — assign a role to a member
- app.post('/v1/communities/:communityId/members/:wallet/roles', { schema: assignMemberRoleSchema, preHandler: [authenticateApiKey] }, async (request: FastifyRequest, reply: FastifyReply) => {
+ app.post('/v1/communities/:communityId/members/:wallet/roles', { schema: assignMemberRoleSchema, preHandler: [authenticateApiKey, idempotencyPreHandler], onSend: [idempotencyOnSend] }, async (request: FastifyRequest, reply: FastifyReply) => {
const { communityId, wallet } = request.params as { communityId: string; wallet: string };
const body = request.body as { role?: string };
const role = body?.role ?? '';
@@ -430,7 +440,7 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
});
// DELETE /v1/communities/:communityId/members/:wallet/roles/:role — remove an assigned role
- app.delete('/v1/communities/:communityId/members/:wallet/roles/:role', { schema: removeMemberRoleSchema, preHandler: [authenticateApiKey] }, async (request: FastifyRequest, reply: FastifyReply) => {
+ app.delete('/v1/communities/:communityId/members/:wallet/roles/:role', { schema: removeMemberRoleSchema, preHandler: [authenticateApiKey, idempotencyPreHandler], onSend: [idempotencyOnSend] }, async (request: FastifyRequest, reply: FastifyReply) => {
const { communityId, wallet, role } = request.params as { communityId: string; wallet: string; role: string };
const requesterWallet = getRequesterWallet(request);
@@ -463,7 +473,11 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
// POST /v1/communities/:communityId/members/:wallet/badges — assign a badge to a member
app.post(
"/v1/communities/:communityId/members/:wallet/badges",
- { schema: assignBadgeSchema, preHandler: [authenticateApiKey] },
+ {
+ schema: assignBadgeSchema,
+ preHandler: [authenticateApiKey, idempotencyPreHandler],
+ onSend: [idempotencyOnSend],
+ },
async (request: FastifyRequest, reply: FastifyReply) => {
const { communityId, wallet } = request.params as {
communityId: string;
@@ -569,7 +583,11 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
// DELETE /v1/communities/:communityId/members/:wallet/badges/:badgeId — revoke a badge
app.delete(
"/v1/communities/:communityId/members/:wallet/badges/:badgeId",
- { schema: revokeBadgeSchema, preHandler: [authenticateApiKey] },
+ {
+ schema: revokeBadgeSchema,
+ preHandler: [authenticateApiKey, idempotencyPreHandler],
+ onSend: [idempotencyOnSend],
+ },
async (request: FastifyRequest, reply: FastifyReply) => {
const { communityId, wallet, badgeId } = request.params as {
communityId: string;
@@ -622,7 +640,11 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
// POST /v1/communities/:communityId/overrides — create or update an access override for a wallet/resource
app.post(
"/v1/communities/:communityId/overrides",
- { schema: createAccessOverrideSchema, preHandler: [authenticateApiKey] },
+ {
+ schema: createAccessOverrideSchema,
+ preHandler: [authenticateApiKey, idempotencyPreHandler],
+ onSend: [idempotencyOnSend],
+ },
async (request: FastifyRequest, reply: FastifyReply) => {
const { communityId } = request.params as { communityId: string };
const body = request.body as {
@@ -682,7 +704,11 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
// DELETE /v1/communities/:communityId/overrides/:wallet/:resource — revoke an access override
app.delete(
"/v1/communities/:communityId/overrides/:wallet/:resource",
- { schema: revokeAccessOverrideSchema, preHandler: [authenticateApiKey] },
+ {
+ schema: revokeAccessOverrideSchema,
+ preHandler: [authenticateApiKey, idempotencyPreHandler],
+ onSend: [idempotencyOnSend],
+ },
async (request: FastifyRequest, reply: FastifyReply) => {
const { communityId, wallet, resource } = request.params as {
communityId: string;
@@ -946,7 +972,7 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
// --- Resource Routes ---
- app.post('/v1/communities/:communityId/resources', { schema: createResourceSchema, preHandler: [authenticateApiKey] }, async (request: FastifyRequest, reply: FastifyReply) => {
+ app.post('/v1/communities/:communityId/resources', { schema: createResourceSchema, preHandler: [authenticateApiKey, idempotencyPreHandler], onSend: [idempotencyOnSend] }, async (request: FastifyRequest, reply: FastifyReply) => {
const { communityId } = request.params as { communityId: string };
const body = request.body as { resourceId: string; name: string; metadata?: any };
const requesterWallet = getRequesterWallet(request);
@@ -967,7 +993,7 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
}
});
- app.patch('/v1/communities/:communityId/resources/:resourceId', { schema: updateResourceSchema, preHandler: [authenticateApiKey] }, async (request: FastifyRequest, reply: FastifyReply) => {
+ app.patch('/v1/communities/:communityId/resources/:resourceId', { schema: updateResourceSchema, preHandler: [authenticateApiKey, idempotencyPreHandler], onSend: [idempotencyOnSend] }, async (request: FastifyRequest, reply: FastifyReply) => {
const { communityId, resourceId } = request.params as { communityId: string; resourceId: string };
const body = request.body as { name?: string; metadata?: any };
const requesterWallet = getRequesterWallet(request);
@@ -988,7 +1014,7 @@ export async function registerRoutes(app: FastifyInstance): Promise<void> {
}
});
- app.delete('/v1/communities/:communityId/resources/:resourceId', { schema: archiveResourceSchema, preHandler: [authenticateApiKey] }, async (request: FastifyRequest, reply: FastifyReply) => {
+ app.delete('/v1/communities/:communityId/resources/:resourceId', { schema: archiveResourceSchema, preHandler: [authenticateApiKey, idempotencyPreHandler], onSend: [idempotencyOnSend] }, async (request: FastifyRequest, reply: FastifyReply) => {
const { communityId, resourceId } = request.params as { communityId: string; resourceId: string };
const requesterWallet = getRequesterWallet(request);
try {