Files
0pt/lib/orders-store.ts
T
adminandClaude Opus 5 db868f4bdf
CI (SIAX Cloud) / security (push) Successful in 14s
Security Scan (SIAX Cloud) / security (push) Successful in 21s
CI (SIAX Cloud) / security (pull_request) Successful in 15s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 15s
CI (SIAX Cloud) / quality (push) Successful in 44s
CI (SIAX Cloud) / integration (push) Successful in 45s
CI (SIAX Cloud) / integration (pull_request) Successful in 27s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m45s
fix(prod): close legacy storage fallbacks in orders/subscriptions/blobs
The `resolveStoreMode` kill switch (Master-DoD §3/§10) covered the newer
`src/repositories/*` stores but not two older paths, both of which are
live production execution paths today.

1. LEGACY NEXT.JS STORES. `lib/orders-store.ts` and
   `lib/subscriptions-store.ts` predate `src/platform/dependency-mode.ts`
   and called `getSql()` directly, silently falling back to module-global
   `Map`s when no database is configured. For orders, payments and
   subscriptions that is not a degraded mode, it is invisible loss of
   money-bearing state: the API returns 201 and the row evaporates on the
   next restart or on any other replica. The live 0pt deployment
   (Coolify app 54) runs NODE_ENV=production with DATABASE_URL,
   POSTGRES_URL and POSTGRES_PRISMA_URL all unset — so this is the
   behavior in production right now, across 7 API routes.

   These now go through `getSqlForDurableStore()`, which reuses the SAME
   `resolveStoreMode` decision every `src/repositories/*` store already
   uses rather than re-implementing a second production check. The reuse
   is load-bearing: `isProductionRuntime` deliberately exempts
   `NEXT_PHASE=phase-production-build`, because `next build` runs
   page-data collection under NODE_ENV=production while serving nothing.
   A naive `process.env.NODE_ENV === "production"` test here would have
   failed the BUILD instead of protecting a request path.

2. LOCALBLOBSTORE. It writes document bytes to a container-local disk
   while `document-capture-service` registers an artifact pointer
   claiming the bytes are stored — durable object storage silently
   swapped for ephemeral disk. It is the default blob store for both the
   capture and extraction services. In production it now raises
   DEPENDENCY_UNAVAILABLE (capability blocked: no ST0RE bytes path
   exists yet) instead of fabricating success. Asserted per-operation,
   not in the constructor, so merely wiring the services is not fatal —
   only actually persisting or reading bytes is.

Evidence: full suite 956 passed / 184 skipped, typecheck clean,
dependency-cruiser 0 errors, lint identical to main's pre-existing
baseline (17 problems, none in changed files). Both guards asserted in
both directions and mutation-tested: bypassing resolveStoreMode -> 2
failed; dropping the write assert -> 2 failed; dropping the read assert
-> 1 failed; all restored -> 8 passed. 7 non-test call sites.

DEPLOYMENT NOTE: merging changes no runtime (no Gitea webhook exists on
any repo; deploys are manual). Deploying this build REQUIRES
provisioning DATABASE_URL for 0pt first, or the order/subscription
routes will correctly return DEPENDENCY_UNAVAILABLE instead of silently
accepting orders into memory. That provisioning is a Simon action.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 17:38:51 +02:00

205 lines
8.2 KiB
TypeScript

import { getSqlForDurableStore } from "@/lib/db";
import { computeEstimate, type EntityType, type Frequency } from "@/lib/data";
import { serviceById } from "@/lib/services";
export interface OrderConfig {
markets?: string[];
type?: EntityType;
fieldIds?: string[];
enrichmentIds?: string[];
volume?: number;
frequency?: Frequency;
confidence?: number;
formats?: string[];
service_type?: string;
}
export interface Order {
order_id: string;
flow: string;
status: string;
config: OrderConfig;
total_ore: number;
deposit_ore: number;
balance_ore: number;
est_days: number;
est_confidence: number;
created_at: string;
}
// Non-durable fallback used only until a database is provisioned.
const mem = new Map<string, Order>();
// idempotency_key -> order_id, mirroring the Postgres unique index added by
// sql/006_orders_idempotency.sql for the in-memory fallback path.
const memIdempotencyIndex = new Map<string, string>();
/**
* Thrown by {@link createOrder} when a caller reuses an `Idempotency-Key`
* for a semantically different request (different `flow` and/or `config`)
* than the one that key was first used with. A route handler should map
* this to HTTP 409 -- silently returning either order would be wrong (the
* caller asked for the SAME operation to be safely retried, not for two
* different operations to collapse into one).
*/
export class IdempotencyKeyConflictError extends Error {
constructor(public readonly idempotencyKey: string) {
super(`Idempotency-Key "${idempotencyKey}" was already used to create a different order (different flow/config)`);
this.name = "IdempotencyKeyConflictError";
}
}
/** Postgres error code 23505 = unique_violation (postgres.js surfaces it as `.code`). */
function isUniqueViolation(err: unknown): boolean {
return typeof err === "object" && err !== null && (err as { code?: unknown }).code === "23505";
}
function sameSubmission(a: Order, flow: string, config: OrderConfig): boolean {
return a.flow === flow && JSON.stringify(a.config) === JSON.stringify(config);
}
export async function findOrderByIdempotencyKey(key: string): Promise<Order | null> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
SELECT order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
FROM orders WHERE idempotency_key = ${key} LIMIT 1`;
return rows[0] ? coerceOrder(rows[0]) : null;
}
const id = memIdempotencyIndex.get(key);
return id ? mem.get(id) ?? null : null;
}
// postgres.js (pinned v3.4.9) returns bigint (total_ore/deposit_ore/balance_ore)
// and numeric (est_confidence) columns as strings by default, not JS numbers.
// Coerce only these four fields on rows read back from SQL -- not the shared
// `sql` client's global type map, which would silently affect every other
// table's bigint/numeric columns too (e.g. jobs.pct, deliveries.avg_confidence).
function coerceOrder(row: Order): Order {
return {
...row,
total_ore: Number(row.total_ore),
deposit_ore: Number(row.deposit_ore),
balance_ore: Number(row.balance_ore),
est_confidence: Number(row.est_confidence),
};
}
function estimateFor(config: OrderConfig) {
return computeEstimate({
markets: config.markets ?? [],
type: config.type ?? "Bolag",
fieldIds: config.fieldIds ?? [],
enrichmentIds: config.enrichmentIds ?? [],
volume: config.volume ?? 1000,
frequency: config.frequency ?? "Engångs",
confidence: config.confidence ?? 92,
serviceMult: serviceById(config.service_type ?? "")?.mult ?? 1,
});
}
export interface CreateOrderResult {
order: Order;
/** True when this call returned a PRE-EXISTING order (a safe retry under the same Idempotency-Key), not a newly created one. */
replayed: boolean;
}
/**
* P014: `idempotencyKey` is optional -- a caller that omits it (or the
* pre-P014 call shape) behaves exactly as before, creating a fresh row every
* call. When supplied (the `Idempotency-Key` header convention, see
* sql/006_orders_idempotency.sql), a retry with the SAME key returns the
* original order unchanged (`replayed: true`) instead of creating a
* duplicate; a retry with the same key but a DIFFERENT flow/config throws
* {@link IdempotencyKeyConflictError} rather than silently picking one.
*
* The Postgres path checks-then-inserts, which has a real (if narrow) race
* window between two concurrent requests carrying the same fresh key -- the
* UNIQUE INDEX from sql/006 is the actual source of truth, and a
* unique-violation on INSERT is caught and re-resolved the same way a
* pre-existing row would be, rather than surfacing a raw DB error.
*/
export async function createOrder(flow: string, config: OrderConfig, idempotencyKey?: string): Promise<CreateOrderResult> {
const key = idempotencyKey?.trim() || undefined;
if (key) {
const existing = await findOrderByIdempotencyKey(key);
if (existing) {
if (sameSubmission(existing, flow, config)) return { order: existing, replayed: true };
throw new IdempotencyKeyConflictError(key);
}
}
const est = estimateFor(config);
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
try {
const [row] = await sql<{ order_id: string; created_at: string }[]>`
INSERT INTO orders (flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, idempotency_key)
VALUES (${flow}, 'draft', ${sql.json(config as Parameters<typeof sql.json>[0])}, ${est.price * 100}, ${est.deposit * 100},
${est.remainder * 100}, ${est.timelineDays}, ${est.estConfidence / 100}, ${key ?? null})
RETURNING order_id, created_at`;
return {
order: {
order_id: row.order_id, flow, status: "draft", config,
total_ore: est.price * 100, deposit_ore: est.deposit * 100, balance_ore: est.remainder * 100,
est_days: est.timelineDays, est_confidence: est.estConfidence / 100, created_at: row.created_at,
},
replayed: false,
};
} catch (err) {
if (key && isUniqueViolation(err)) {
const raced = await findOrderByIdempotencyKey(key);
if (raced) {
if (sameSubmission(raced, flow, config)) return { order: raced, replayed: true };
throw new IdempotencyKeyConflictError(key);
}
}
throw err;
}
}
const id = (globalThis.crypto?.randomUUID?.() ?? `SX-${Math.floor(1000 + Math.random() * 9000)}`);
const order: Order = {
order_id: id, flow, status: "draft", config,
total_ore: est.price * 100, deposit_ore: est.deposit * 100, balance_ore: est.remainder * 100,
est_days: est.timelineDays, est_confidence: est.estConfidence / 100, created_at: new Date().toISOString(),
};
mem.set(id, order);
if (key) memIdempotencyIndex.set(key, id);
return { order, replayed: false };
}
export async function getOrder(id: string): Promise<Order | null> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
SELECT order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
FROM orders WHERE order_id::text = ${id} LIMIT 1`;
return rows[0] ? coerceOrder(rows[0]) : null;
}
return mem.get(id) ?? null;
}
export async function listOrders(): Promise<Order[]> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
SELECT order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
FROM orders ORDER BY created_at DESC LIMIT 100`;
return rows.map(coerceOrder);
}
return [...mem.values()].sort((a, b) => b.created_at.localeCompare(a.created_at));
}
export async function setStatus(id: string, status: string): Promise<Order | null> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
UPDATE orders SET status = ${status}, updated_at = now() WHERE order_id::text = ${id}
RETURNING order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at`;
return rows[0] ? coerceOrder(rows[0]) : null;
}
const o = mem.get(id);
if (o) { o.status = status; mem.set(id, o); }
return o ?? null;
}