Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
@@ -0,0 +1,171 @@
|
||||
import { CatalogError, foundationErrors, type JsonValue } from "./errors.js";
|
||||
|
||||
export type IdempotencyResponse = {
|
||||
status: number;
|
||||
body?: JsonValue;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
export type IdempotencyClient = {
|
||||
idempotencyKey: {
|
||||
findUnique(args: { where: { idempotency_key_scope_key: { scope: string; key: string } } }): Promise<{
|
||||
requestHash: string;
|
||||
responseStatus: number;
|
||||
responseBody: JsonValue | null;
|
||||
responseHeaders: Record<string, string> | null;
|
||||
expiresAt?: Date | null;
|
||||
} | null>;
|
||||
create(args: {
|
||||
data: {
|
||||
scope: string;
|
||||
key: string;
|
||||
requestHash: string;
|
||||
responseStatus: number;
|
||||
responseBody?: JsonValue | null;
|
||||
responseHeaders?: Record<string, string> | null;
|
||||
expiresAt?: Date | null;
|
||||
};
|
||||
}): Promise<unknown>;
|
||||
update(args: {
|
||||
where: { idempotency_key_scope_key: { scope: string; key: string } };
|
||||
data: {
|
||||
responseStatus: number;
|
||||
responseBody?: JsonValue | null;
|
||||
responseHeaders?: Record<string, string> | null;
|
||||
expiresAt?: Date | null;
|
||||
};
|
||||
}): Promise<unknown>;
|
||||
deleteMany?(args?: { where?: { scope?: string; key?: string; expiresAt?: { lte?: Date } } }): Promise<unknown>;
|
||||
};
|
||||
};
|
||||
|
||||
const idempotencyLockTails = new Map<string, Promise<void>>();
|
||||
|
||||
export async function withIdempotency(
|
||||
input: { scope?: string; key?: string | null; fingerprint: JsonValue; expiresAt?: Date | null },
|
||||
client: IdempotencyClient,
|
||||
operation: () => Promise<IdempotencyResponse>,
|
||||
): Promise<IdempotencyResponse & { replayed: boolean }> {
|
||||
const key = input.key?.trim();
|
||||
if (!key) return { ...(await operation()), replayed: false };
|
||||
|
||||
const scope = input.scope ?? "default";
|
||||
return runWithIdempotencyLock(`${scope}:${key}`, async () => runIdempotencyOperation({ ...input, scope, key }, client, operation));
|
||||
}
|
||||
|
||||
async function runIdempotencyOperation(
|
||||
input: { scope: string; key: string; fingerprint: JsonValue; expiresAt?: Date | null },
|
||||
client: IdempotencyClient,
|
||||
operation: () => Promise<IdempotencyResponse>,
|
||||
): Promise<IdempotencyResponse & { replayed: boolean }> {
|
||||
const { scope, key } = input;
|
||||
const requestHash = stableStringify(input.fingerprint);
|
||||
const existing = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope, key } } });
|
||||
|
||||
if (existing) {
|
||||
return replayExistingIdempotencyResponse(existing, requestHash);
|
||||
}
|
||||
|
||||
try {
|
||||
await client.idempotencyKey.create({
|
||||
data: {
|
||||
scope,
|
||||
key,
|
||||
requestHash,
|
||||
responseStatus: 0,
|
||||
responseBody: null,
|
||||
responseHeaders: null,
|
||||
expiresAt: input.expiresAt ?? null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isUniqueConstraintError(error)) {
|
||||
throw error;
|
||||
}
|
||||
const reserved = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope, key } } });
|
||||
if (reserved) {
|
||||
return replayExistingIdempotencyResponse(reserved, requestHash);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await operation();
|
||||
await client.idempotencyKey.update({
|
||||
where: { idempotency_key_scope_key: { scope, key } },
|
||||
data: {
|
||||
responseStatus: response.status,
|
||||
responseBody: response.body ?? null,
|
||||
responseHeaders: response.headers ?? null,
|
||||
expiresAt: input.expiresAt ?? null,
|
||||
},
|
||||
});
|
||||
return { ...response, replayed: false };
|
||||
} catch (error) {
|
||||
await client.idempotencyKey.deleteMany?.({ where: { scope, key } });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function replayExistingIdempotencyResponse(
|
||||
existing: {
|
||||
requestHash: string;
|
||||
responseStatus: number;
|
||||
responseBody: JsonValue | null;
|
||||
responseHeaders: Record<string, string> | null;
|
||||
},
|
||||
requestHash: string,
|
||||
): IdempotencyResponse & { replayed: true } {
|
||||
if (existing.requestHash !== requestHash) {
|
||||
throw new CatalogError(foundationErrors.idempotencyConflict);
|
||||
}
|
||||
if (existing.responseStatus <= 0) {
|
||||
throw new CatalogError(foundationErrors.idempotencyInProgress);
|
||||
}
|
||||
return {
|
||||
status: existing.responseStatus,
|
||||
body: existing.responseBody ?? undefined,
|
||||
headers: existing.responseHeaders ?? undefined,
|
||||
replayed: true,
|
||||
};
|
||||
}
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
return Boolean(
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
("code" in error ? (error as { code?: unknown }).code === "P2002" : false),
|
||||
);
|
||||
}
|
||||
|
||||
async function runWithIdempotencyLock<T>(lockKey: string, task: () => Promise<T>): Promise<T> {
|
||||
const previousTail = idempotencyLockTails.get(lockKey) ?? Promise.resolve();
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const nextTail = previousTail.catch(() => undefined).then(() => gate);
|
||||
|
||||
idempotencyLockTails.set(lockKey, nextTail);
|
||||
await previousTail.catch(() => undefined);
|
||||
|
||||
try {
|
||||
return await task();
|
||||
} finally {
|
||||
release();
|
||||
if (idempotencyLockTails.get(lockKey) === nextTail) {
|
||||
idempotencyLockTails.delete(lockKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stableStringify(value: JsonValue): string {
|
||||
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
||||
if (value && typeof value === "object") {
|
||||
return `{${Object.entries(value)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`)
|
||||
.join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
Reference in new issue
Block a user