@tokenoftrust/storefront-runner 6.11.3 → 6.11.4

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.
@@ -6,6 +6,7 @@ import { admissionBindsOrder, currentCartEvent, readCommerceAdmission } from "..
6
6
  import { FulfillmentService } from "./fulfillmentService.js";
7
7
  import { fulfillmentDbFromQueryable } from "./store.js";
8
8
  import { dispatchCommerceDeliveries } from "./commerceRuntime.js";
9
+ import { ORDER_DECREMENT_SOURCE, recordMirrorInventoryChanged } from "../inventory/mirrorStock.js";
9
10
  const UNKNOWN: CommerceEvidence = { verification: "UNKNOWN", tax: "UNKNOWN", risk: "UNKNOWN", stock: "UNKNOWN" };
10
11
 
11
12
  export async function projectCommerceOrder(
@@ -55,7 +56,8 @@ export async function projectCommerceOrder(
55
56
  {
56
57
  sql: `UPDATE scrappy_allocations SET order_id=?,state='confirmed'
57
58
  WHERE tenant_id=? AND stage=? AND order_id=? AND state='reserved'
58
- AND EXISTS(SELECT 1 FROM commerce_admission_snapshots WHERE tenant_id=? AND stage=? AND authorization_id=? AND linked_order_id=?)`,
59
+ AND EXISTS(SELECT 1 FROM commerce_admission_snapshots WHERE tenant_id=? AND stage=? AND authorization_id=? AND linked_order_id=?)
60
+ RETURNING sku, location_id`,
59
61
  params: [
60
62
  input.orderId,
61
63
  input.tenantId,
@@ -83,6 +85,52 @@ export async function projectCommerceOrder(
83
85
  },
84
86
  ]);
85
87
  trusted = Boolean(results[0]?.results.length);
88
+ const confirmedAllocations = results[1]?.results ?? [];
89
+ for (const row of confirmedAllocations) {
90
+ const sku = typeof row.sku === "string" ? row.sku : "";
91
+ const locationId = typeof row.location_id === "string" && row.location_id ? row.location_id : "unspecified";
92
+ if (!sku) continue;
93
+ const stat = await db.first<{ ledger_sum: number; ledger_count: number; confirmed_sum: number }>(
94
+ `SELECT
95
+ (SELECT COALESCE(SUM(quantity_delta), 0) FROM commerce_inventory_movements
96
+ WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_sum,
97
+ (SELECT COUNT(*) FROM commerce_inventory_movements
98
+ WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_count,
99
+ (SELECT COALESCE(SUM(quantity), 0) FROM scrappy_allocations
100
+ WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed') AS confirmed_sum`,
101
+ input.tenantId,
102
+ input.stage,
103
+ sku,
104
+ locationId,
105
+ input.tenantId,
106
+ input.stage,
107
+ sku,
108
+ locationId,
109
+ input.tenantId,
110
+ input.stage,
111
+ sku,
112
+ locationId,
113
+ );
114
+ const balance = Number(stat?.ledger_count ?? 0) > 0 ? Number(stat?.ledger_sum ?? 0) - Number(stat?.confirmed_sum ?? 0) : 0;
115
+ await recordMirrorInventoryChanged(db, {
116
+ tenantId: input.tenantId,
117
+ stage: input.stage,
118
+ source: ORDER_DECREMENT_SOURCE,
119
+ sourceEventId: input.orderId,
120
+ sku,
121
+ locationId,
122
+ balance,
123
+ asOf: input.now,
124
+ notify: dispatchCommerceDeliveries,
125
+ gate: {
126
+ sql: `EXISTS (
127
+ SELECT 1 FROM scrappy_allocations
128
+ WHERE tenant_id = ? AND stage = ? AND order_id = ? AND sku = ? AND location_id = ? AND state = 'confirmed'
129
+ )`,
130
+ params: [input.tenantId, input.stage, input.orderId, sku, locationId],
131
+ },
132
+ });
133
+ }
86
134
  }
87
135
  const evidence = trusted && admission ? admission.evidence : UNKNOWN;
88
136
  const service = new FulfillmentService(fulfillmentDbFromQueryable(db), {
@@ -25,6 +25,7 @@ import {
25
25
  type SqlCondition,
26
26
  } from "../../inventory/mirrorStock.js";
27
27
  import { checkIdempotency, computeBodyHash } from "./orders/idempotency.js";
28
+ import { emitInventoryChanged } from "../webhooks/emit.js";
28
29
 
29
30
  export const INVENTORY_WRITE_SCOPE = "inventory:write";
30
31
  export const INVENTORY_AUDIT_EVENT = "inventory.corrected";
@@ -201,11 +202,12 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
201
202
  const asOf = request.now();
202
203
  const receiptId = `app.${(await hex(`${actor.installId}\n${key}`)).slice(0, 48)}`;
203
204
  const actorId = `app:${actor.installId}`;
205
+ const source = await appSource(actor.appId);
204
206
  const movement = guardedCorrectionStatement(
205
207
  {
206
208
  tenantId: actor.tenantId,
207
209
  stage: actor.stage,
208
- source: await appSource(actor.appId),
210
+ source,
209
211
  sourceEventId: receiptId,
210
212
  sku,
211
213
  locationId: delta.locationId,
@@ -248,7 +250,21 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
248
250
  },
249
251
  ]);
250
252
  if ((changes[0] ?? 0) === 1 && (changes[2] ?? 0) === 1) {
251
- return (await priorAnswer(db, actor.installId, key, bodyHash)) ?? inventoryRefusal("unavailable");
253
+ const answer = await priorAnswer(db, actor.installId, key, bodyHash);
254
+ if (!answer) return inventoryRefusal("unavailable");
255
+ if ("receiptId" in answer.body) {
256
+ await emitInventoryChanged(db, {
257
+ tenantId: actor.tenantId,
258
+ stage: actor.stage,
259
+ source,
260
+ sourceEventId: receiptId,
261
+ sku: answer.body.sku,
262
+ locationId: answer.body.locationId,
263
+ balance: answer.body.balance,
264
+ asOf: answer.body.asOf,
265
+ });
266
+ }
267
+ return answer;
252
268
  }
253
269
  return classifyRefused(db, actor, delta, key, bodyHash);
254
270
  }
@@ -1,19 +1,25 @@
1
1
  /**
2
2
  * Payload admission for the commerce topics the single commerce emitter writes:
3
- * `fulfillment.assignment.created`, `fulfillment.assignment.updated` and `order.fulfilled`.
3
+ * `fulfillment.assignment.created`, `fulfillment.assignment.updated`, `order.fulfilled`
4
+ * and `inventory.changed`.
4
5
  *
5
- * Each topic has a closed key set (`asyncapi.yaml` `FulfillmentAssignmentData` and `OrderData`)
6
- * and every payload also passes the private-identity check. Both run when the event row is
7
- * written and again before the delivery engine signs and POSTs it.
6
+ * Each topic has a closed key set (`asyncapi.yaml` `FulfillmentAssignmentData`, `OrderData`
7
+ * and `InventoryChangedData`) and every payload also passes the private-identity check. Both
8
+ * run when the event row is written and again before the delivery engine signs and POSTs it.
8
9
  */
9
10
  import type { WebhookTopic } from "./deliveryStore.js";
10
11
 
11
- export type CommerceTopic = "fulfillment.assignment.created" | "fulfillment.assignment.updated" | "order.fulfilled";
12
+ export type CommerceTopic =
13
+ | "fulfillment.assignment.created"
14
+ | "fulfillment.assignment.updated"
15
+ | "order.fulfilled"
16
+ | "inventory.changed";
12
17
 
13
18
  export const COMMERCE_TOPICS: readonly CommerceTopic[] = [
14
19
  "fulfillment.assignment.created",
15
20
  "fulfillment.assignment.updated",
16
21
  "order.fulfilled",
22
+ "inventory.changed",
17
23
  ];
18
24
 
19
25
  /** Keys that identify a person or an address. None may appear at any depth of a commerce payload. */
@@ -42,6 +48,8 @@ const ASSIGNMENT_KEYS = ["assignmentId", "orderId", "stage", "state", "eventVers
42
48
  const ASSIGNMENT_STATES = new Set(["active", "held", "cancelled"]);
43
49
  const ORDER_DATA_KEYS = new Set(["id", "status", "currency", "customerHash", "subtotal", "total", "lineItems"]);
44
50
  const LINE_ITEM_KEYS = new Set(["sku", "handle", "quantity", "lineTotal"]);
51
+ export const INVENTORY_CHANGED_KEYS = ["sku", "locationId", "balance", "asOf"] as const;
52
+ const LOCATION_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
45
53
 
46
54
  export function isCommerceTopic(topic: WebhookTopic): topic is CommerceTopic {
47
55
  return (COMMERCE_TOPICS as readonly string[]).includes(topic);
@@ -94,8 +102,22 @@ function orderFulfilledAdmissible(payload: Record<string, unknown>): boolean {
94
102
  );
95
103
  }
96
104
 
105
+ export function inventoryChangedAdmissible(payload: unknown): boolean {
106
+ if (!isRecord(payload) || commercePayloadHasPrivateIdentity(payload)) return false;
107
+ const keys = Object.keys(payload);
108
+ if (keys.length !== INVENTORY_CHANGED_KEYS.length || !INVENTORY_CHANGED_KEYS.every((key) => keys.includes(key))) {
109
+ return false;
110
+ }
111
+ if (!nonEmptyString(payload.sku) || payload.sku.trim() !== payload.sku) return false;
112
+ if (typeof payload.locationId !== "string" || !LOCATION_ID_RE.test(payload.locationId)) return false;
113
+ if (!Number.isSafeInteger(payload.balance)) return false;
114
+ return typeof payload.asOf === "string" && Number.isFinite(Date.parse(payload.asOf));
115
+ }
116
+
97
117
  /** True when `payload` is exactly the closed shape `topic` allows and carries no private identity. */
98
118
  export function commercePayloadAdmissible(topic: CommerceTopic, payload: unknown): boolean {
99
119
  if (!isRecord(payload) || commercePayloadHasPrivateIdentity(payload)) return false;
100
- return topic === "order.fulfilled" ? orderFulfilledAdmissible(payload) : assignmentAdmissible(topic, payload);
120
+ if (topic === "order.fulfilled") return orderFulfilledAdmissible(payload);
121
+ if (topic === "inventory.changed") return inventoryChangedAdmissible(payload);
122
+ return assignmentAdmissible(topic, payload);
101
123
  }
@@ -742,7 +742,8 @@ export function commerceEventStatements(input: {
742
742
  SELECT ?, ?, i.install_id, i.tenant_id, ?, 'pending', 0, ?, ?
743
743
  FROM app_installs AS i
744
744
  WHERE i.install_id = ? AND ${ELIGIBLE_INSTALL_CONDITION}
745
- AND EXISTS (SELECT 1 FROM webhook_events WHERE id = ? AND tenant_id = ? AND topic = ?)`,
745
+ AND EXISTS (SELECT 1 FROM webhook_events WHERE id = ? AND tenant_id = ? AND topic = ?)
746
+ AND NOT EXISTS (SELECT 1 FROM webhook_deliveries WHERE event_id = ? AND install_id = ?)`,
746
747
  params: [
747
748
  target.deliveryId,
748
749
  input.eventId,
@@ -755,6 +756,8 @@ export function commerceEventStatements(input: {
755
756
  input.eventId,
756
757
  input.tenantId,
757
758
  input.topic,
759
+ input.eventId,
760
+ target.installId,
758
761
  ],
759
762
  });
760
763
  }
@@ -45,16 +45,29 @@
45
45
  * needing customer identity must use the per-(tenant, app-install) opaque
46
46
  * hash, never a raw identifier.
47
47
  */
48
- import { WebhookDeliveryStore, type WebhookTopic } from "./deliveryStore.js";
48
+ import {
49
+ COMMERCE_DELIVERY_GRACE_MS,
50
+ CommercePayloadRefused,
51
+ WebhookDeliveryStore,
52
+ commerceEventStatements,
53
+ commerceTargetsQuery,
54
+ type CommerceEventStatement,
55
+ type WebhookTopic,
56
+ } from "./deliveryStore.js";
57
+ import { commercePayloadAdmissible, isCommerceTopic } from "./commercePayloads.js";
58
+ import { InMemoryDispatcher } from "./dispatcher.js";
49
59
  import { TOPIC_REQUIRED_SCOPE } from "./events.js";
50
60
  import { getDispatcher } from "./getDispatcher.js";
51
61
  import { getRegistryService } from "../apps/registryAccess.js";
52
62
  import type { AppInstall } from "../apps/registryService.js";
53
- import { fromD1 } from "../../catalog/d1/catalog.js";
54
- import { readD1 } from "../../publication/shared/env.js";
63
+ import { fromD1, type Queryable } from "../../catalog/d1/catalog.js";
64
+ import { setInventoryChangedNotify } from "../../inventory/mirrorStock.js";
65
+ import { getWorkerEnv, readD1, readEnv } from "../../publication/shared/env.js";
66
+ import type { CommerceStage } from "@tot/public-runtime";
55
67
 
56
68
  /** Contract-scoped payload schema version — `asyncapi.yaml`'s `dataschemaversion` is `const: "1"` for V1. */
57
69
  const DATASCHEMA_VERSION = "1";
70
+ const WEBHOOK_SIGNING_PRIVATE_KEY_ENV = "WEBHOOK_SIGNING_PRIVATE_KEY_B64";
58
71
 
59
72
  export interface EmitWebhookEventOptions {
60
73
  /**
@@ -120,6 +133,9 @@ export async function emitWebhookEvent(
120
133
  logDiag({ topic, tenantId, reason: "lifecycle_topic_requires_installId" });
121
134
  return null;
122
135
  }
136
+ if (isCommerceTopic(topic) && !commercePayloadAdmissible(topic, data)) {
137
+ throw new CommercePayloadRefused(topic);
138
+ }
123
139
 
124
140
  const d1 = await readD1("STOREFRONT_APPS_DB");
125
141
  if (!d1) {
@@ -165,3 +181,142 @@ export async function emitWebhookEvent(
165
181
 
166
182
  return { eventId: event.id, deliveryCount: deliveries.length };
167
183
  }
184
+
185
+ export interface InventoryChangedPayload {
186
+ sku: string;
187
+ locationId: string;
188
+ balance: number;
189
+ asOf: string;
190
+ }
191
+
192
+ export interface InventoryMovementIdentity {
193
+ tenantId: string;
194
+ stage: CommerceStage;
195
+ source: string;
196
+ sourceEventId: string;
197
+ sku: string;
198
+ locationId: string;
199
+ }
200
+
201
+ async function digestPrefix(prefix: string, parts: readonly string[]): Promise<string> {
202
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\n"))));
203
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
204
+ return `${prefix}.${hex.slice(0, 48)}`;
205
+ }
206
+
207
+ /** Deterministic `webhook_events.id` for one inventory movement key, so replays cannot double-emit. */
208
+ export async function inventoryEventId(key: InventoryMovementIdentity): Promise<string> {
209
+ return digestPrefix("inv", [key.tenantId, key.stage, key.source, key.sourceEventId, key.sku, key.locationId]);
210
+ }
211
+
212
+ /** Deterministic `webhook_deliveries.delivery_id` for one `(eventId, installId)` pair. */
213
+ export async function inventoryDeliveryId(eventId: string, installId: string): Promise<string> {
214
+ return digestPrefix("invdlv", [eventId, installId]);
215
+ }
216
+
217
+ /**
218
+ * Best-effort dispatch after committing `inventory.changed` delivery rows: arms the tenant
219
+ * commerce alarm and enqueues each delivery on the configured dispatcher.
220
+ */
221
+ export async function dispatchInventoryDeliveries(
222
+ tenantId: string,
223
+ deliveryIds: readonly string[],
224
+ now: number = Date.now(),
225
+ ): Promise<void> {
226
+ if (deliveryIds.length === 0) return;
227
+ try {
228
+ const namespace = (await getWorkerEnv())?.TENANT_PIPELINE as
229
+ | { idFromName(name: string): unknown; get(id: unknown): { scheduleCommerce(t: string, at: number): Promise<void> } }
230
+ | undefined;
231
+ if (namespace && typeof namespace.idFromName === "function") {
232
+ await namespace.get(namespace.idFromName(tenantId)).scheduleCommerce(tenantId, now + COMMERCE_DELIVERY_GRACE_MS + 1000);
233
+ }
234
+ } catch {
235
+ // The committed delivery rows remain pending for the next alarm sweep.
236
+ }
237
+ try {
238
+ const dispatcher = await getDispatcher();
239
+ if (dispatcher instanceof Response) return;
240
+ if (dispatcher instanceof InMemoryDispatcher && !(await readEnv(WEBHOOK_SIGNING_PRIVATE_KEY_ENV))) return;
241
+ for (const deliveryId of deliveryIds) await dispatcher.enqueue({ deliveryId });
242
+ } catch {
243
+ // Same: the pending rows remain the durable record.
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Emit `inventory.changed` once for a committed inventory movement on `db`. Writes the
249
+ * `webhook_events` row and one `pending` `webhook_deliveries` row per active `inventory:read`
250
+ * install on `input.tenantId`, gated on `input.gate` (defaulting to the movement row's presence in
251
+ * `commerce_inventory_movements`) and the absence of the deterministic `eventId`.
252
+ */
253
+ export async function emitInventoryChanged(
254
+ db: Queryable,
255
+ input: InventoryMovementIdentity &
256
+ InventoryChangedPayload & {
257
+ gate?: CommerceEventStatement;
258
+ notify?: (tenantId: string, deliveryIds: readonly string[]) => void | Promise<void>;
259
+ },
260
+ ): Promise<{ eventId: string; deliveryIds: string[] } | null> {
261
+ const eventId = await inventoryEventId(input);
262
+ const payload: InventoryChangedPayload = {
263
+ sku: input.sku,
264
+ locationId: input.locationId,
265
+ balance: input.balance,
266
+ asOf: input.asOf,
267
+ };
268
+ const targetsQuery = commerceTargetsQuery(input.tenantId, "inventory.changed");
269
+ const installs = await db.all<{ install_id: string }>(targetsQuery.sql, ...targetsQuery.params);
270
+ const targets = await Promise.all(
271
+ installs.map(async (row) => ({
272
+ installId: row.install_id,
273
+ deliveryId: await inventoryDeliveryId(eventId, row.install_id),
274
+ })),
275
+ );
276
+ const baseGate: CommerceEventStatement = input.gate ?? {
277
+ sql: `EXISTS (
278
+ SELECT 1 FROM commerce_inventory_movements
279
+ WHERE tenant_id = ? AND stage = ? AND source = ? AND source_event_id = ? AND sku = ? AND location_id = ?
280
+ )`,
281
+ params: [input.tenantId, input.stage, input.source, input.sourceEventId, input.sku, input.locationId],
282
+ };
283
+ const gate: CommerceEventStatement = {
284
+ sql: `(${baseGate.sql}) AND NOT EXISTS (SELECT 1 FROM webhook_events WHERE id = ?)`,
285
+ params: [...baseGate.params, eventId],
286
+ };
287
+ const statements = commerceEventStatements({
288
+ eventId,
289
+ tenantId: input.tenantId,
290
+ topic: "inventory.changed",
291
+ payload,
292
+ gate,
293
+ targets,
294
+ now: input.asOf,
295
+ });
296
+ if (db.batch) {
297
+ await db.batch(statements.map((s) => ({ sql: s.sql, params: [...s.params] })));
298
+ } else {
299
+ for (const statement of statements) await db.run(statement.sql, ...statement.params);
300
+ }
301
+ const written = await db.first<{ ok: number }>(`SELECT 1 AS ok FROM webhook_events WHERE id = ?`, eventId);
302
+ if (!written) return null;
303
+ const committed =
304
+ targets.length > 0
305
+ ? await db.all<{ delivery_id: string }>(
306
+ `SELECT delivery_id FROM webhook_deliveries WHERE event_id = ? ORDER BY created_at ASC, delivery_id ASC`,
307
+ eventId,
308
+ )
309
+ : [];
310
+ const deliveryIds = committed.map((row) => row.delivery_id);
311
+ if (deliveryIds.length > 0) {
312
+ const notify = input.notify ?? dispatchInventoryDeliveries;
313
+ try {
314
+ await notify(input.tenantId, deliveryIds);
315
+ } catch {
316
+ // Pending rows remain durable in webhook_deliveries.
317
+ }
318
+ }
319
+ return { eventId, deliveryIds };
320
+ }
321
+
322
+ setInventoryChangedNotify(dispatchInventoryDeliveries);
@@ -652,6 +652,13 @@ function commandFinding(reason: string): string {
652
652
  }
653
653
  }
654
654
 
655
+ import {
656
+ mirrorMovementDeliveryId,
657
+ mirrorMovementEventId,
658
+ ORDER_DECREMENT_SOURCE,
659
+ recordMirrorInventoryChanged,
660
+ } from "./mirrorStock.js";
661
+
655
662
  /** Move reserved units to confirmed once. A second call decrements nothing. */
656
663
  export async function confirmHoldOnce(
657
664
  runner: StatementRunner,
@@ -673,7 +680,7 @@ export async function confirmHoldOnce(
673
680
  SELECT 1 FROM scrappy_final_cart_authorizations
674
681
  WHERE tenant_id = ? AND stage = ? AND authorization_id = ? AND state = 'active'
675
682
  )
676
- RETURNING quantity`,
683
+ RETURNING sku, location_id, quantity`,
677
684
  params: [...scope, ...scope, ...scope],
678
685
  },
679
686
  {
@@ -710,8 +717,82 @@ export async function confirmHoldOnce(
710
717
  params: scope,
711
718
  },
712
719
  ]);
720
+ const confirmedRows = results[0] ?? [];
721
+ if (confirmedRows.length > 0) {
722
+ const orderRows = await runner.all(
723
+ `SELECT placed_at FROM scrappy_commerce_orders WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
724
+ scope,
725
+ );
726
+ const placedAt = text(orderRows[0] ?? {}, "placed_at") || new Date().toISOString();
727
+ const runnerQueryable = {
728
+ all: async <T>(sql: string, ...params: unknown[]) => (await runner.all(sql, params)) as T[],
729
+ first: async <T>(sql: string, ...params: unknown[]) => ((await runner.all(sql, params))[0] as T | undefined) ?? null,
730
+ run: async (sql: string, ...params: unknown[]) => {
731
+ await runner.batch([{ sql, params }]);
732
+ },
733
+ exec: async () => {},
734
+ batch: async (statements: readonly SqlStatement[]) => {
735
+ await runner.batch(statements);
736
+ },
737
+ };
738
+ for (const row of confirmedRows) {
739
+ const sku = text(row, "sku");
740
+ const locationId = text(row, "location_id") || "unspecified";
741
+ if (!sku) continue;
742
+ const stats = await runner.all(
743
+ `SELECT
744
+ (SELECT COALESCE(SUM(quantity_delta), 0) FROM commerce_inventory_movements
745
+ WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_sum,
746
+ (SELECT COUNT(*) FROM commerce_inventory_movements
747
+ WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_count,
748
+ (SELECT MAX(as_of) FROM commerce_inventory_movements
749
+ WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS max_as_of,
750
+ (SELECT COALESCE(SUM(quantity), 0) FROM scrappy_allocations
751
+ WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed') AS confirmed_sum`,
752
+ [
753
+ input.tenantId,
754
+ input.stage,
755
+ sku,
756
+ locationId,
757
+ input.tenantId,
758
+ input.stage,
759
+ sku,
760
+ locationId,
761
+ input.tenantId,
762
+ input.stage,
763
+ sku,
764
+ locationId,
765
+ input.tenantId,
766
+ input.stage,
767
+ sku,
768
+ locationId,
769
+ ],
770
+ );
771
+ const stat = stats[0] ?? {};
772
+ const ledgerCount = Number(stat.ledger_count ?? 0);
773
+ const balance = ledgerCount > 0 ? Number(stat.ledger_sum ?? 0) - Number(stat.confirmed_sum ?? 0) : 0;
774
+ const asOf = text(stat, "max_as_of") || placedAt;
775
+ await recordMirrorInventoryChanged(runnerQueryable, {
776
+ tenantId: input.tenantId,
777
+ stage: input.stage,
778
+ source: ORDER_DECREMENT_SOURCE,
779
+ sourceEventId: input.orderId,
780
+ sku,
781
+ locationId,
782
+ balance,
783
+ asOf,
784
+ gate: {
785
+ sql: `EXISTS (
786
+ SELECT 1 FROM scrappy_allocations
787
+ WHERE tenant_id = ? AND stage = ? AND order_id = ? AND sku = ? AND location_id = ? AND state = 'confirmed'
788
+ )`,
789
+ params: [input.tenantId, input.stage, input.orderId, sku, locationId],
790
+ },
791
+ });
792
+ }
793
+ }
713
794
  return {
714
- decremented: sumQuantity(results[0] ?? []),
795
+ decremented: sumQuantity(confirmedRows),
715
796
  states: (results[3] ?? []).map((row) => text(row, "state")),
716
797
  };
717
798
  }
@@ -5,6 +5,144 @@ import { isStoredSku } from "@tot/public-runtime/sku";
5
5
  import type { MirrorStockAuthority } from "./allocations.js";
6
6
 
7
7
  const ID = /^[A-Za-z0-9._:-]{1,128}$/;
8
+ const INVENTORY_CHANGED_TOPIC = "inventory.changed";
9
+ const INVENTORY_READ_SCOPE = "inventory:read";
10
+ const INVENTORY_DATASCHEMA_VERSION = "1";
11
+ const ELIGIBLE_INVENTORY_INSTALL_SQL = `i.tenant_id = ? AND i.status = 'active' AND i.managed_kind IS NULL
12
+ AND COALESCE(i.webhook_endpoint, '') != ''
13
+ AND EXISTS (SELECT 1 FROM json_each(i.scopes) WHERE json_each.value = '${INVENTORY_READ_SCOPE}')`;
14
+
15
+ export type InventoryChangedNotify = (tenantId: string, deliveryIds: readonly string[]) => void | Promise<void>;
16
+ let defaultInventoryNotify: InventoryChangedNotify | undefined;
17
+
18
+ /** Registers the runtime delivery notifier so ledger writes schedule committed `inventory.changed` deliveries. */
19
+ export function setInventoryChangedNotify(notify: InventoryChangedNotify | undefined): void {
20
+ defaultInventoryNotify = notify;
21
+ }
22
+
23
+ async function digestId(prefix: string, parts: readonly string[]): Promise<string> {
24
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\n"))));
25
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
26
+ return `${prefix}.${hex.slice(0, 48)}`;
27
+ }
28
+
29
+ export async function mirrorMovementEventId(input: {
30
+ tenantId: string;
31
+ stage: CommerceStage;
32
+ source: string;
33
+ sourceEventId: string;
34
+ sku: string;
35
+ locationId: string;
36
+ }): Promise<string> {
37
+ return digestId("inv", [
38
+ input.tenantId,
39
+ input.stage,
40
+ input.source,
41
+ input.sourceEventId,
42
+ input.sku,
43
+ input.locationId,
44
+ ]);
45
+ }
46
+
47
+ export async function mirrorMovementDeliveryId(eventId: string, installId: string): Promise<string> {
48
+ return digestId("invdlv", [eventId, installId]);
49
+ }
50
+
51
+ export async function recordMirrorInventoryChanged(
52
+ db: Queryable,
53
+ input: {
54
+ tenantId: string;
55
+ stage: CommerceStage;
56
+ source: string;
57
+ sourceEventId: string;
58
+ sku: string;
59
+ locationId: string;
60
+ balance: number;
61
+ asOf: string;
62
+ gate?: SqlCondition;
63
+ notify?: InventoryChangedNotify;
64
+ },
65
+ ): Promise<{ eventId: string; deliveryIds: string[] } | null> {
66
+ const eventId = await mirrorMovementEventId(input);
67
+ const payload = JSON.stringify({
68
+ sku: input.sku,
69
+ locationId: input.locationId,
70
+ balance: input.balance,
71
+ asOf: input.asOf,
72
+ });
73
+ const installs = await db.all<{ install_id: string }>(
74
+ `SELECT i.install_id AS install_id FROM app_installs AS i
75
+ WHERE ${ELIGIBLE_INVENTORY_INSTALL_SQL}
76
+ ORDER BY i.created_at ASC, i.install_id ASC`,
77
+ input.tenantId,
78
+ );
79
+ const targets = await Promise.all(
80
+ installs.map(async (row) => ({
81
+ installId: row.install_id,
82
+ deliveryId: await mirrorMovementDeliveryId(eventId, row.install_id),
83
+ })),
84
+ );
85
+ const baseGate: SqlCondition = input.gate ?? {
86
+ sql: `EXISTS (
87
+ SELECT 1 FROM commerce_inventory_movements
88
+ WHERE tenant_id = ? AND stage = ? AND source = ? AND source_event_id = ? AND sku = ? AND location_id = ?
89
+ )`,
90
+ params: [input.tenantId, input.stage, input.source, input.sourceEventId, input.sku, input.locationId],
91
+ };
92
+ const statements: { sql: string; params: unknown[] }[] = [
93
+ {
94
+ sql: `INSERT INTO webhook_events (id, tenant_id, topic, dataschema_version, payload, created_at)
95
+ SELECT ?, ?, '${INVENTORY_CHANGED_TOPIC}', '${INVENTORY_DATASCHEMA_VERSION}', ?, ?
96
+ WHERE (${baseGate.sql}) AND NOT EXISTS (SELECT 1 FROM webhook_events WHERE id = ?)`,
97
+ params: [eventId, input.tenantId, payload, input.asOf, ...baseGate.params, eventId],
98
+ },
99
+ ...targets.map((target) => ({
100
+ sql: `INSERT INTO webhook_deliveries
101
+ (delivery_id, event_id, install_id, tenant_id, topic, state, attempts, created_at, updated_at)
102
+ SELECT ?, ?, i.install_id, i.tenant_id, '${INVENTORY_CHANGED_TOPIC}', 'pending', 0, ?, ?
103
+ FROM app_installs AS i
104
+ WHERE i.install_id = ? AND ${ELIGIBLE_INVENTORY_INSTALL_SQL}
105
+ AND EXISTS (SELECT 1 FROM webhook_events WHERE id = ? AND tenant_id = ? AND topic = '${INVENTORY_CHANGED_TOPIC}')
106
+ AND NOT EXISTS (SELECT 1 FROM webhook_deliveries WHERE event_id = ? AND install_id = ?)`,
107
+ params: [
108
+ target.deliveryId,
109
+ eventId,
110
+ input.asOf,
111
+ input.asOf,
112
+ target.installId,
113
+ input.tenantId,
114
+ eventId,
115
+ input.tenantId,
116
+ eventId,
117
+ target.installId,
118
+ ],
119
+ })),
120
+ ];
121
+ if (db.batch) {
122
+ await db.batch(statements);
123
+ } else {
124
+ for (const statement of statements) await db.run(statement.sql, ...statement.params);
125
+ }
126
+ const written = await db.first<{ ok: number }>(`SELECT 1 AS ok FROM webhook_events WHERE id = ?`, eventId);
127
+ if (!written) return null;
128
+ const committed =
129
+ targets.length > 0
130
+ ? await db.all<{ delivery_id: string }>(
131
+ `SELECT delivery_id FROM webhook_deliveries WHERE event_id = ? ORDER BY created_at ASC, delivery_id ASC`,
132
+ eventId,
133
+ )
134
+ : [];
135
+ const deliveryIds = committed.map((row) => row.delivery_id);
136
+ const notify = input.notify ?? defaultInventoryNotify;
137
+ if (deliveryIds.length > 0 && notify) {
138
+ try {
139
+ await notify(input.tenantId, deliveryIds);
140
+ } catch {
141
+ // Pending rows remain in webhook_deliveries for the commerce alarm.
142
+ }
143
+ }
144
+ return { eventId, deliveryIds };
145
+ }
8
146
  /** Stable caller-visible failures; storage errors retain no public text. */
9
147
  export class InventoryMovementError extends Error {
10
148
  constructor(readonly code: "invalid-movement" | "conflict") {
@@ -82,6 +220,24 @@ export async function appendMirrorMovement(db: Queryable, input: MirrorMovement)
82
220
  actual.actor_id !== input.actorId
83
221
  )
84
222
  throw new InventoryMovementError("conflict");
223
+ if (!prior) {
224
+ const reading = await readMirrorBalance(db, {
225
+ tenantId: input.tenantId,
226
+ stage: input.stage,
227
+ sku: input.sku,
228
+ locationId: input.locationId,
229
+ });
230
+ await recordMirrorInventoryChanged(db, {
231
+ tenantId: input.tenantId,
232
+ stage: input.stage,
233
+ source: input.source,
234
+ sourceEventId: input.sourceEventId,
235
+ sku: input.sku,
236
+ locationId: input.locationId,
237
+ balance: reading?.balance ?? input.quantityDelta,
238
+ asOf: input.asOf,
239
+ });
240
+ }
85
241
  }
86
242
  export async function readMirrorStock(
87
243
  db: Queryable,
@@ -126,6 +282,37 @@ export const MIRROR_FRESH_MS = 15 * 60_000;
126
282
  export const MIRROR_LOCATION_UNSPECIFIED = "unspecified";
127
283
  export const CATALOG_IMPORT_ACTOR_ID = "catalog-import";
128
284
  export const CATALOG_IMPORT_SOURCE = "catalog-import";
285
+ export const ORDER_DECREMENT_SOURCE = "order-decrement";
286
+ export const ORDER_DECREMENT_ACTOR_ID = "commerce-order";
287
+
288
+ /** Records an order stock decrement in the mirror ledger and emits `inventory.changed` once. */
289
+ export async function appendOrderDecrement(
290
+ db: Queryable,
291
+ input: {
292
+ tenantId: string;
293
+ stage: CommerceStage;
294
+ orderId: string;
295
+ sku: string;
296
+ locationId?: string;
297
+ quantity: number;
298
+ asOf: string;
299
+ },
300
+ ): Promise<void> {
301
+ if (!Number.isSafeInteger(input.quantity) || input.quantity <= 0) {
302
+ throw new InventoryMovementError("invalid-movement");
303
+ }
304
+ await appendMirrorMovement(db, {
305
+ tenantId: input.tenantId,
306
+ stage: input.stage,
307
+ source: ORDER_DECREMENT_SOURCE,
308
+ sourceEventId: input.orderId,
309
+ sku: input.sku,
310
+ locationId: input.locationId ?? MIRROR_LOCATION_UNSPECIFIED,
311
+ quantityDelta: -input.quantity,
312
+ asOf: input.asOf,
313
+ actorId: ORDER_DECREMENT_ACTOR_ID,
314
+ });
315
+ }
129
316
 
130
317
  export interface MirrorBalance {
131
318
  balance: number;
@@ -201,6 +388,16 @@ export async function appendSourceOnHand(
201
388
  !["preview", "publication"].includes(input.stage)
202
389
  )
203
390
  throw new InventoryMovementError("invalid-movement");
391
+ const prior = await db.first<{ one: number }>(
392
+ `SELECT 1 AS one FROM commerce_inventory_movements
393
+ WHERE tenant_id=? AND stage=? AND source=? AND source_event_id=? AND sku=? AND location_id=?`,
394
+ input.tenantId,
395
+ input.stage,
396
+ input.source,
397
+ input.sourceEventId,
398
+ input.sku,
399
+ input.locationId,
400
+ );
204
401
  const others = [input.tenantId, input.stage, input.sku, input.locationId, input.source, input.sourceEventId];
205
402
  await db.run(
206
403
  `INSERT INTO commerce_inventory_movements
@@ -238,6 +435,24 @@ export async function appendSourceOnHand(
238
435
  actual.actor_id !== input.actorId
239
436
  )
240
437
  throw new InventoryMovementError("conflict");
438
+ if (!prior) {
439
+ const reading = await readMirrorBalance(db, {
440
+ tenantId: input.tenantId,
441
+ stage: input.stage,
442
+ sku: input.sku,
443
+ locationId: input.locationId,
444
+ });
445
+ await recordMirrorInventoryChanged(db, {
446
+ tenantId: input.tenantId,
447
+ stage: input.stage,
448
+ source: input.source,
449
+ sourceEventId: input.sourceEventId,
450
+ sku: input.sku,
451
+ locationId: input.locationId,
452
+ balance: reading?.balance ?? input.onHand,
453
+ asOf: input.asOf,
454
+ });
455
+ }
241
456
  }
242
457
 
243
458
  /** The largest balance a key may hold: the mirror ledger never stores or reports an unsafe integer. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.11.3",
3
+ "version": "6.11.4",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",