Files
kivvi/apps/web/lib/api-idempotency.ts
GandClaude Opus 5 afbe985e53 chore: add a formatter (#64)
* chore: add a formatter, matching the style this repo already writes

singleQuote=false was chosen by counting this repo's own
imports, not by fleet decree. The fleet is genuinely split and the two repos
that already had a .prettierrc disagreed with each other, so there was no
standard to restore. Quote style does not cross repo boundaries; having a
gate does.

Markdown is ignored for now — prettier rewraps prose, which would bury the
real diff.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* style: format with prettier (759 files)

Mechanical. No behaviour change. This SHA is listed in
.git-blame-ignore-revs so `git blame` skips it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: teach git blame to skip the reformat

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(ci): resolve the lockfile with the pnpm major CI runs

The previous commit regenerated pnpm-lock.yaml with local pnpm 11, which
re-resolved the `github:catomean/ai-forms` shorthand from a codeload tarball
to git+ssh. CI runs pnpm 9, which cannot read that entry — and could not fetch
over SSH even if it could, having no key. The lockfile was valid on the machine
that wrote it and broken everywhere else.

Resolved with pnpm 9 instead. The rollout script now derives the major from
packageManager/PNPM_VERSION and refuses any lockfile that gains an ssh-form
resolution.

* fix(ci): resolve ai-forms over https, not ssh

pnpm records whichever transport it could use when the lockfile was written.
This laptop has an SSH key, so pnpm wrote git+ssh; CI has none and the install
died on 'Permission denied (publickey)'. Resolving with GIT_SSH_COMMAND=/bin/false
reproduces CI's capabilities and yields git+https, which needs no credentials
for a public repo.

* fix(ci): keep the lockfile byte-identical apart from the pin

kivvi already depended on prettier, so this PR is script wiring, not a new
dependency — and it should not have rewritten the lockfile at all.

Regenerating it re-resolved the `github:catomean/ai-forms` shorthand three
different ways, none of which CI could use: git+ssh (no key on the runner),
then git+https (fetches, but pnpm's virtual-store path for a git dep failed to
import). Only main's original codeload tarball works. The resolution recorded
in a lockfile depends on what the machine writing it could reach, which makes
'it resolved fine locally' worth nothing.

So: restore main's lockfile and change only the specifier, which is what
--frozen-lockfile actually compares, and format with 3.8.0 — the version this
repo's own lockfile already pinned — rather than dragging it to the fleet's
3.9.6 and reformatting against a version it does not install.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 10:31:23 +00:00

78 lines
2.3 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import {
claimIdempotencyKey,
completeIdempotencyKey,
releaseIdempotencyKey,
} from "@kivvi/core/src/domain/idempotency";
import { db } from "./db";
/**
* Wrap an authenticated `/api/v1` write handler with idempotency keyed on the
* `Idempotency-Key` request header. Opt-in: with no header the handler runs
* unchanged.
*
* - New key → claim, run handler, store the response, return it.
* - Replay → return the stored response verbatim (handler never re-runs), so a
* retried Payrexx webhook can't create a duplicate invoice/payment.
* - Pending → 409 (a concurrent retry is mid-flight).
* - Error/5xx → release the claim so the client can safely retry.
*/
export async function withIdempotency(
request: NextRequest,
companyId: string,
handler: () => Promise<NextResponse>,
): Promise<NextResponse> {
const key = request.headers.get("idempotency-key")?.trim();
if (!key) return handler();
const path = new URL(request.url).pathname;
const claim = await claimIdempotencyKey(db, companyId, key, request.method, path);
if (claim.outcome === "replay") {
return NextResponse.json(claim.responseBody, {
status: claim.responseStatus,
headers: { "Idempotent-Replayed": "true" },
});
}
if (claim.outcome === "in_progress") {
return NextResponse.json(
{
success: false,
error: "A request with this Idempotency-Key is already being processed.",
},
{ status: 409 },
);
}
// outcome === "claimed" — we own it. Run the handler, persist the response.
let response: NextResponse;
try {
response = await handler();
} catch (err) {
// Transient/unknown failure — release so the client can retry.
await releaseIdempotencyKey(db, companyId, key);
throw err;
}
if (response.status >= 500) {
// Don't cache server errors; let the client retry.
await releaseIdempotencyKey(db, companyId, key);
return response;
}
// Deterministic outcome (2xx/4xx) — store the exact body + status for replay.
const bodyText = await response.clone().text();
let body: unknown = null;
if (bodyText) {
try {
body = JSON.parse(bodyText);
} catch {
body = bodyText;
}
}
await completeIdempotencyKey(db, companyId, key, response.status, body);
return response;
}