@12-apps/marketplace 1.0.0 → 1.2.0

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.
Files changed (83) hide show
  1. package/ADOPTING.md +44 -9
  2. package/README.md +149 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +116 -0
  7. package/dist/99food/index.js +361 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-CgCAYBSJ.d.ts → adapter-_iuSxvVD.d.ts} +41 -1
  13. package/dist/{chunk-OEKTWUQH.js → chunk-24RQZPSV.js} +1 -1
  14. package/dist/chunk-24RQZPSV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/{chunk-BEMTRJYM.js → chunk-CRYFYDQ2.js} +28 -4
  18. package/dist/{chunk-BEMTRJYM.js.map → chunk-CRYFYDQ2.js.map} +1 -1
  19. package/dist/chunk-D2X7TOR6.js +1240 -0
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-DDE0mnTu.d.ts → engine-D-a4mttc.d.ts} +117 -17
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +10 -12
  25. package/dist/ifood/index.js +19 -61
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +113 -497
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +3 -2
  31. package/dist/manifest/server.js +2 -2
  32. package/dist/rappi/en-US.d.ts +14 -0
  33. package/dist/rappi/en-US.js +18 -0
  34. package/dist/rappi/en-US.js.map +1 -0
  35. package/dist/rappi/index.d.ts +190 -0
  36. package/dist/rappi/index.js +353 -0
  37. package/dist/rappi/index.js.map +1 -0
  38. package/dist/rappi/pt-BR.d.ts +18 -0
  39. package/dist/rappi/pt-BR.js +18 -0
  40. package/dist/rappi/pt-BR.js.map +1 -0
  41. package/dist/server/index.d.ts +12 -5
  42. package/dist/server/index.js +4 -2
  43. package/package.json +26 -2
  44. package/prisma/marketplace.prisma +12 -1
  45. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  46. package/src/99food/copy.ts +36 -0
  47. package/src/99food/en-US.ts +19 -0
  48. package/src/99food/index.ts +121 -0
  49. package/src/99food/normalize.ts +263 -0
  50. package/src/99food/outbound.ts +220 -0
  51. package/src/99food/pt-BR.ts +23 -0
  52. package/src/core/acceptance.ts +30 -14
  53. package/src/core/adapter.ts +23 -1
  54. package/src/core/cancellation-outcome.ts +92 -0
  55. package/src/core/cancellation.ts +46 -15
  56. package/src/core/decisions.ts +94 -19
  57. package/src/core/engine.ts +8 -0
  58. package/src/core/fetch-order.ts +253 -0
  59. package/src/core/inbox.ts +8 -2
  60. package/src/core/ingest.ts +10 -2
  61. package/src/core/integration.ts +30 -1
  62. package/src/core/order-fetch-marks.ts +63 -0
  63. package/src/core/outbound-sweep.ts +87 -8
  64. package/src/core/outbound.ts +103 -7
  65. package/src/core/payload-read.ts +101 -0
  66. package/src/core/pipeline.ts +64 -15
  67. package/src/core/ports.ts +32 -0
  68. package/src/core/state.ts +6 -1
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +9 -0
  71. package/src/ifood/normalize.ts +15 -88
  72. package/src/index.ts +10 -1
  73. package/src/rappi/copy.ts +39 -0
  74. package/src/rappi/en-US.ts +14 -0
  75. package/src/rappi/index.ts +155 -0
  76. package/src/rappi/normalize.ts +314 -0
  77. package/src/rappi/outbound.ts +182 -0
  78. package/src/rappi/pt-BR.ts +18 -0
  79. package/src/server/index.ts +1 -0
  80. package/src/server/jobs.ts +38 -4
  81. package/dist/chunk-6OODIO3E.js +0 -395
  82. package/dist/chunk-6OODIO3E.js.map +0 -1
  83. package/dist/chunk-OEKTWUQH.js.map +0 -1
@@ -0,0 +1,253 @@
1
+ import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
+ import { ingestMarketplaceOrder } from "./ingest";
3
+ import { readOutboundConnection, resolveIngestionTarget } from "./integration";
4
+ import type { FetchOrderResult } from "./adapter";
5
+ import { cancelAcceptance } from "./acceptance";
6
+ import { cancelledBeforeIngest } from "./order-fetch-marks";
7
+ import type { EngineContext } from "./ports";
8
+ import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
9
+
10
+ /**
11
+ * Fetching an order the event only announced — the engine's half of a
12
+ * marketplace whose events carry no order body (Open Delivery's `CREATED`).
13
+ *
14
+ * The rule this keeps: no path that answers a request calls a marketplace. So
15
+ * the webhook only RECORDS the delivery (PENDING, "order details to fetch")
16
+ * and queues `marketplace.fetch-order`; the job reads the row, asks the
17
+ * adapter's `fetchOrder` through the host's HTTP port with the store's own
18
+ * credentials, and ingests what comes back through the one ingest path. The
19
+ * inbox reconciliation sweep re-queues the job for a row that is still owed
20
+ * once it is older than the job's own retry span ({@link FETCH_REQUEUE_AGE_MS}),
21
+ * so a refused enqueue or a dead worker loses nothing — and it never fetches
22
+ * itself, so a host that holds the job (its enqueue port answers "held")
23
+ * holds every fetch.
24
+ *
25
+ * Two things are judged before a fetched order is ingested: a cancellation
26
+ * that outran the fetch (`./order-fetch-marks.ts`) wins, and an order naming a
27
+ * merchant other than the connection's is refused.
28
+ *
29
+ * Nothing here knows a marketplace: which events need a fetch is the adapter's
30
+ * `orderToFetch`, and how to fetch is its `fetchOrder`.
31
+ */
32
+
33
+ /** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */
34
+ export const MARKETPLACE_FETCH_ORDER_JOB = "marketplace.fetch-order";
35
+
36
+ /** The job's payload. Identifiers only: the event itself is the inbox row's. */
37
+ export interface FetchOrderJobPayload {
38
+ clientId: string;
39
+ inboxId: string;
40
+ }
41
+
42
+ /** What one run did. */
43
+ export type FetchOrderOutcome =
44
+ | { kind: "skipped"; reason: string }
45
+ | { kind: "ingested"; orderId: string; unmappedSkus: string[] }
46
+ | { kind: "failed"; reason: string };
47
+
48
+ /** Thrown so the queue retries the fetch. Its message is what the job log reads. */
49
+ export class FetchOrderRetryError extends Error {
50
+ constructor(message: string) {
51
+ super(message);
52
+ this.name = "FetchOrderRetryError";
53
+ }
54
+ }
55
+
56
+ /** The reason a recorded row waits for its fetch. */
57
+ const AWAITING_ORDER_REASON = "order details to fetch";
58
+
59
+ /**
60
+ * A row waiting for its fetch is left alone by the reconciliation sweep this
61
+ * long: the job's own three attempts (5 s, then 10 s apart) finish well inside
62
+ * it. Past it the sweep re-queues, and only then counts an attempt, so a slow
63
+ * queue never spends the row's attempts while its first job still waits.
64
+ */
65
+ export const FETCH_REQUEUE_AGE_MS = 2 * 60_000;
66
+
67
+ /**
68
+ * Leave the row PENDING for its fetch and queue the job. The queue port never
69
+ * throws; a refusal is logged and recovered by the reconciliation sweep.
70
+ * `dedupeKey` defaults to the row's own; a re-queue passes a fresh one, since
71
+ * a queue may keep a finished job's id and swallow a re-queue under it.
72
+ */
73
+ export async function awaitOrderBody(
74
+ ctx: EngineContext,
75
+ clientId: string,
76
+ inboxId: string,
77
+ dedupeKey: string = `${MARKETPLACE_FETCH_ORDER_JOB}:${inboxId}`,
78
+ ): Promise<void> {
79
+ await deferInboxEvent(ctx, inboxId, AWAITING_ORDER_REASON);
80
+ const payload: FetchOrderJobPayload = { clientId, inboxId };
81
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_FETCH_ORDER_JOB, payload, { dedupeKey });
82
+ if (!outcome.enqueued) {
83
+ ctx.ports.logger.warn(
84
+ `${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${inboxId} was not queued; the reconciliation sweep will re-queue it` +
85
+ (outcome.reason ? ` (${outcome.reason})` : ""),
86
+ );
87
+ }
88
+ }
89
+
90
+ /**
91
+ * The reconciliation sweep's answer to a row still waiting for its order body:
92
+ * untouched while younger than {@link FETCH_REQUEUE_AGE_MS} (no attempt
93
+ * counted, nothing queued), else re-queued under a fresh key with a warning,
94
+ * so a hold or a dead worker is visible rather than silent.
95
+ */
96
+ export async function requeueOwedFetch(
97
+ ctx: EngineContext,
98
+ input: { id: string; clientId: string; receivedAt?: Date | null },
99
+ ): Promise<{ kind: "awaitingOrder" }> {
100
+ const now = ctx.ports.clock.now();
101
+ const age = input.receivedAt ? now.getTime() - input.receivedAt.getTime() : Number.POSITIVE_INFINITY;
102
+ if (age < FETCH_REQUEUE_AGE_MS) return { kind: "awaitingOrder" };
103
+ ctx.ports.logger.warn(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${input.id} still waits for its order body; re-queued`);
104
+ await awaitOrderBody(ctx, input.clientId, input.id, `${MARKETPLACE_FETCH_ORDER_JOB}:${input.id}:${now.getTime()}`);
105
+ return { kind: "awaitingOrder" };
106
+ }
107
+
108
+ interface InboxRow {
109
+ id: string;
110
+ clientId: string | null;
111
+ provider: string;
112
+ payload: unknown;
113
+ status: string;
114
+ receivedAt: Date | null;
115
+ }
116
+
117
+ /** The recorded row and its event, or why there is nothing to fetch. */
118
+ async function owedFetch(
119
+ ctx: EngineContext,
120
+ payload: FetchOrderJobPayload,
121
+ ): Promise<{ row: InboxRow; event: NormalizedEvent } | string> {
122
+ const db = await ctx.ports.db();
123
+ const row = (await db.marketplaceInboxEvent.findUnique({
124
+ where: { id: payload.inboxId },
125
+ select: { id: true, clientId: true, provider: true, payload: true, status: true, receivedAt: true },
126
+ })) as InboxRow | null;
127
+ if (!row || row.clientId !== payload.clientId) return "no such inbox row for this tenant";
128
+ if (row.status !== "PENDING" && row.status !== "FAILED") return `the row is already ${row.status}`;
129
+ const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
130
+ if (!event?.orderToFetch || event.order) return "the event announces no order to fetch";
131
+ return { row, event };
132
+ }
133
+
134
+ /** One call to the adapter, or the refusal that stands in for it. */
135
+ async function fetchThroughAdapter(
136
+ ctx: EngineContext,
137
+ clientId: string,
138
+ provider: MarketplaceProvider,
139
+ externalOrderId: string,
140
+ ): Promise<FetchOrderResult> {
141
+ const adapter = ctx.registry.get(provider);
142
+ if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
143
+ let connection;
144
+ try {
145
+ connection = await readOutboundConnection(ctx, clientId, provider);
146
+ } catch (error) {
147
+ const reason = error instanceof Error ? error.message : String(error);
148
+ return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
149
+ }
150
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
151
+ try {
152
+ return await adapter.fetchOrder(
153
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
154
+ { externalOrderId },
155
+ );
156
+ } catch (error) {
157
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Why a fetched order must not be ingested, or null. A cancellation recorded
163
+ * before the body arrived wins: the order is cancelled, so no pedido and no
164
+ * confirm. An order naming another merchant than the connection's is someone
165
+ * else's order delivered to this store's URL (a wrong webhook URL, a replay).
166
+ */
167
+ async function refusalOf(
168
+ ctx: EngineContext,
169
+ clientId: string,
170
+ order: NormalizedMarketplaceOrder,
171
+ connectionMerchantId: string | null,
172
+ ): Promise<{ settle: "IGNORED" | "FAILED"; reason: string; failed: boolean } | null> {
173
+ if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {
174
+ return { settle: "IGNORED", reason: "cancelled before its order body arrived", failed: false };
175
+ }
176
+ const mismatch = merchantMismatch(order, connectionMerchantId);
177
+ // FAILED, not IGNORED: a connection whose merchant id was entered wrong is
178
+ // corrected, and the reconciliation sweep then retries within its bound.
179
+ return mismatch ? { settle: "FAILED", reason: mismatch, failed: true } : null;
180
+ }
181
+
182
+ /**
183
+ * Why an order naming a merchant cannot be this connection's, or null. An
184
+ * order that names none, or a connection that states none, is not judged.
185
+ * Shared by the fetched path and an order the event carries (`./pipeline.ts`).
186
+ */
187
+ export function merchantMismatch(order: NormalizedMarketplaceOrder, connectionMerchantId: string | null): string | null {
188
+ const named = order.externalMerchantId ?? null;
189
+ if (named === null || connectionMerchantId === null || named === connectionMerchantId) return null;
190
+ return `the order names merchant ${named}, not this connection's`;
191
+ }
192
+
193
+ /** Ingest a fetched order, unless {@link refusalOf} says otherwise. */
194
+ async function ingestFetched(
195
+ ctx: EngineContext,
196
+ row: InboxRow,
197
+ clientId: string,
198
+ order: NormalizedMarketplaceOrder,
199
+ target: { autoAccept: boolean; ackSlaSeconds: number; externalMerchantId: string | null },
200
+ ): Promise<FetchOrderOutcome> {
201
+ const refusal = await refusalOf(ctx, clientId, order, target.externalMerchantId);
202
+ if (refusal) {
203
+ await settleInboxEvent(ctx, row.id, refusal.settle, refusal.reason);
204
+ if (!refusal.failed) return { kind: "skipped", reason: refusal.reason };
205
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} refused: ${refusal.reason}`);
206
+ return { kind: "failed", reason: refusal.reason };
207
+ }
208
+ const ingested = await ingestMarketplaceOrder(ctx, {
209
+ clientId,
210
+ order,
211
+ settings: { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },
212
+ // The store's acceptance window starts when the event arrived, not when a
213
+ // delayed fetch finished: the marketplace's own clock started then.
214
+ clockStartsAt: row.receivedAt ?? undefined,
215
+ });
216
+ // A CANCELLED that read the acceptances while this ingest's transaction was
217
+ // still open found none and left its marker: honour it now, through the
218
+ // ordinary cancel path (the order is cancelled; no confirm is owed).
219
+ const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };
220
+ if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);
221
+ await settleInboxEvent(ctx, row.id, "PROCESSED");
222
+ return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
223
+ }
224
+
225
+ /**
226
+ * Run one queued fetch. Returns what it did; throws {@link FetchOrderRetryError}
227
+ * for an answer worth retrying before the last attempt. A refusal, or the last
228
+ * attempt's retry, settles the row FAILED: the reconciliation sweep re-queues
229
+ * it within the inbox's attempt bound.
230
+ */
231
+ export async function runFetchOrder(
232
+ ctx: EngineContext,
233
+ payload: FetchOrderJobPayload,
234
+ attempt: { attempt: number; maxAttempts: number },
235
+ ): Promise<FetchOrderOutcome> {
236
+ const owed = await owedFetch(ctx, payload);
237
+ if (typeof owed === "string") return { kind: "skipped", reason: owed };
238
+ const { row, event } = owed;
239
+ const target = await resolveIngestionTarget(ctx, payload.clientId, event.provider);
240
+ if (!target?.enabled) {
241
+ await deferInboxEvent(ctx, row.id, "integration is not enabled");
242
+ return { kind: "skipped", reason: "integration is not enabled" };
243
+ }
244
+ const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
245
+ if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
246
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
247
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
248
+ throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
249
+ }
250
+ await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
251
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
252
+ return { kind: "failed", reason };
253
+ }
package/src/core/inbox.ts CHANGED
@@ -53,6 +53,9 @@ export async function recordInboxEvent(
53
53
  eventType: input.event.eventType,
54
54
  externalOrderId: input.event.externalOrderId,
55
55
  payload: input.payload,
56
+ // The engine's clock, not the database's: an announced order's
57
+ // acceptance window counts from here (`./fetch-order.ts`).
58
+ receivedAt: ctx.ports.clock.now(),
56
59
  },
57
60
  select: { id: true },
58
61
  })) as { id: string };
@@ -136,6 +139,8 @@ export interface PendingInboxEvent {
136
139
  clientId: string;
137
140
  provider: MarketplaceProvider;
138
141
  payload: unknown;
142
+ /** When the delivery was recorded. */
143
+ receivedAt?: Date | null;
139
144
  }
140
145
 
141
146
  /**
@@ -161,12 +166,13 @@ export async function listRetryableInboxEvents(
161
166
  },
162
167
  orderBy: { receivedAt: "asc" },
163
168
  take: ctx.ports.reconcileBatchSize,
164
- select: { id: true, clientId: true, provider: true, payload: true },
165
- })) as { id: string; clientId: string; provider: string; payload: unknown }[];
169
+ select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true },
170
+ })) as { id: string; clientId: string; provider: string; payload: unknown; receivedAt: Date | null }[];
166
171
  return rows.map((row) => ({
167
172
  id: row.id,
168
173
  clientId: row.clientId,
169
174
  provider: row.provider as MarketplaceProvider,
170
175
  payload: row.payload,
176
+ receivedAt: row.receivedAt,
171
177
  }));
172
178
  }
@@ -80,6 +80,7 @@ function acceptanceData(
80
80
  order: NormalizedMarketplaceOrder,
81
81
  settings: IngestSettings,
82
82
  now: Date,
83
+ clockStartsAt: Date,
83
84
  ): Record<string, unknown> {
84
85
  const accepted = settings.autoAccept;
85
86
  return {
@@ -91,7 +92,7 @@ function acceptanceData(
91
92
  // Who carries a delivery: the merchant's courier or the marketplace's fleet.
92
93
  deliveredBy: order.deliveredBy ?? null,
93
94
  status: accepted ? "ACCEPTED" : "AWAITING",
94
- acknowledgeBy: new Date(now.getTime() + settings.ackSlaSeconds * 1000),
95
+ acknowledgeBy: new Date(clockStartsAt.getTime() + settings.ackSlaSeconds * 1000),
95
96
  acknowledgedAt: accepted ? now : null,
96
97
  externalDueAt: order.deliveryDueAt,
97
98
  commissionCents: order.commissionCents,
@@ -122,10 +123,17 @@ export async function ingestMarketplaceOrder(
122
123
  order: NormalizedMarketplaceOrder;
123
124
  settings: IngestSettings;
124
125
  now?: Date;
126
+ /**
127
+ * When the acceptance window started, if not `now`: the arrival of the
128
+ * event that announced an order fetched later. Moves ONLY the deadline;
129
+ * the liveness stamp and an auto-accept's time stay `now`.
130
+ */
131
+ clockStartsAt?: Date;
125
132
  },
126
133
  ): Promise<IngestResult> {
127
134
  const { clientId, order, settings } = input;
128
135
  const now = input.now ?? ctx.ports.clock.now();
136
+ const clockStartsAt = input.clockStartsAt ?? now;
129
137
 
130
138
  const db = await ctx.ports.db();
131
139
  // Answered from this package's OWN table rather than through a port: the
@@ -148,7 +156,7 @@ export async function ingestMarketplaceOrder(
148
156
  const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {
149
157
  const lines = await composeLines(tx, clientId, order, now);
150
158
  const created = await ctx.ports.order.create(clientId, order, lines, tx);
151
- await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now) });
159
+ await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now, clockStartsAt) });
152
160
  await markMarketplaceEventSeen(tx, clientId, order.provider, now);
153
161
  return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };
154
162
  });
@@ -168,6 +168,26 @@ export interface IngestionTarget {
168
168
  autoAccept: boolean;
169
169
  ackSlaSeconds: number;
170
170
  webhookSecret: string | null;
171
+ /** The merchant the store connected; a fetched order naming another is refused. */
172
+ externalMerchantId: string | null;
173
+ }
174
+
175
+ /**
176
+ * The merchant id a store's live connection states, read alone: no
177
+ * credentials are opened. Null when it states none, or when there is no live
178
+ * connection (archived or absent).
179
+ */
180
+ export async function connectionMerchantId(
181
+ ctx: EngineContext,
182
+ clientId: string,
183
+ provider: MarketplaceProvider,
184
+ ): Promise<string | null> {
185
+ const db = await ctx.ports.db();
186
+ const row = (await db.marketplaceIntegration.findUnique({
187
+ where: { clientId_provider: { clientId, provider } },
188
+ select: { externalMerchantId: true, archivedAt: true },
189
+ })) as { externalMerchantId: string | null; archivedAt: Date | null } | null;
190
+ return row && !row.archivedAt ? (row.externalMerchantId ?? null) : null;
171
191
  }
172
192
 
173
193
  /**
@@ -188,8 +208,16 @@ export async function resolveIngestionTarget(
188
208
  const db = await ctx.ports.db();
189
209
  const row = (await db.marketplaceIntegration.findUnique({
190
210
  where: { clientId_provider: { clientId, provider } },
191
- select: { enabled: true, autoAccept: true, ackSlaSeconds: true, credentials: true, archivedAt: true },
211
+ select: {
212
+ enabled: true,
213
+ autoAccept: true,
214
+ ackSlaSeconds: true,
215
+ credentials: true,
216
+ archivedAt: true,
217
+ externalMerchantId: true,
218
+ },
192
219
  })) as {
220
+ externalMerchantId: string | null;
193
221
  enabled: boolean;
194
222
  autoAccept: boolean;
195
223
  ackSlaSeconds: number;
@@ -202,6 +230,7 @@ export async function resolveIngestionTarget(
202
230
  enabled: row.enabled,
203
231
  autoAccept: row.autoAccept,
204
232
  ackSlaSeconds: row.ackSlaSeconds,
233
+ externalMerchantId: row.externalMerchantId ?? null,
205
234
  // An unopenable blob must not read as "no secret configured" — that would
206
235
  // turn a key-rotation problem into an endpoint that accepts unsigned
207
236
  // deliveries. The secrets port throws instead, and the caller answers 401.
@@ -0,0 +1,63 @@
1
+ import type { EngineContext } from "./ports";
2
+ import type { MarketplaceProvider } from "./types";
3
+
4
+ /**
5
+ * A cancellation that outran its order's body.
6
+ *
7
+ * For a marketplace whose events only announce an order (`fetchOrder`), the
8
+ * marketplace's CANCELLED can arrive while the fetch is still queued, held or
9
+ * retrying, and the fetched body (Open Delivery's `Order` has no status) cannot
10
+ * say the order was cancelled. Without a trace the fetch would then ingest a
11
+ * cancelled order, send it to the kitchen and confirm it.
12
+ *
13
+ * So when a cancellation finds no acceptance to cancel, it leaves a MARKER: an
14
+ * IGNORED inbox row under a key derived from the order (`engine:cancelled:<id>`),
15
+ * found again through the inbox's own unique `(provider, eventId)` index, with
16
+ * no new column or table. The fetch reads it before it ingests.
17
+ */
18
+
19
+ const MARKER_TYPE = "ENGINE_CANCELLED_BEFORE_INGEST";
20
+
21
+ const markerId = (externalOrderId: string): string => `engine:cancelled:${externalOrderId}`;
22
+
23
+ /** Leave the marker, for an adapter that fetches its orders. Idempotent. */
24
+ export async function markCancelledBeforeIngest(
25
+ ctx: EngineContext,
26
+ input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
27
+ ): Promise<void> {
28
+ if (!ctx.registry.get(input.provider)?.fetchOrder) return;
29
+ const db = await ctx.ports.db();
30
+ try {
31
+ await db.marketplaceInboxEvent.create({
32
+ data: {
33
+ clientId: input.clientId,
34
+ provider: input.provider,
35
+ eventId: markerId(input.externalOrderId),
36
+ eventType: MARKER_TYPE,
37
+ externalOrderId: input.externalOrderId,
38
+ payload: {},
39
+ status: "IGNORED",
40
+ error: "cancelled before the order was ingested",
41
+ receivedAt: ctx.ports.clock.now(),
42
+ processedAt: ctx.ports.clock.now(),
43
+ },
44
+ select: { id: true },
45
+ });
46
+ } catch (error) {
47
+ // A redelivered cancellation: the marker is already there.
48
+ if ((error as { code?: string }).code !== "P2002") throw error;
49
+ }
50
+ }
51
+
52
+ /** Whether this store's order was cancelled before it was ingested. */
53
+ export async function cancelledBeforeIngest(
54
+ ctx: EngineContext,
55
+ input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
56
+ ): Promise<boolean> {
57
+ const db = await ctx.ports.db();
58
+ const row = (await db.marketplaceInboxEvent.findUnique({
59
+ where: { provider_eventId: { provider: input.provider, eventId: markerId(input.externalOrderId) } },
60
+ select: { clientId: true },
61
+ })) as { clientId: string | null } | null;
62
+ return row !== null && row.clientId === input.clientId;
63
+ }
@@ -1,3 +1,5 @@
1
+ import { NO_STANDING_REQUEST } from "./cancellation";
2
+ import { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
1
3
  import { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from "./outbound-queue";
2
4
  import type { EngineContext } from "./ports";
3
5
 
@@ -14,12 +16,27 @@ import type { EngineContext } from "./ports";
14
16
  * - younger than {@link OUTBOUND_STALE_MS}: the original job may still be
15
17
  * retrying, so it is left alone;
16
18
  * - older than {@link OUTBOUND_GIVE_UP_MS}: a marketplace has long since
17
- * settled the order on its own clock. A PENDING request that old is stamped
18
- * FAILED (a person finishes it on the marketplace, through the app link),
19
+ * settled the order on its own clock. A request still waiting that old is
20
+ * stamped FAILED, TIMEOUT (a person finishes it on the marketplace, through
21
+ * the app link),
19
22
  * and an accept that old is never confirmed — which is also what keeps a
20
23
  * host's ACCEPTED history from before this engine from being confirmed on
21
24
  * the first pass.
22
25
  *
26
+ * For a host that REQUESTS FIRST (it binds `onCancellationConfirmed`; a 1.0.0
27
+ * host keeps the re-queue and the give-up below, unchanged), and before
28
+ * anything else, a store's cancellation request still waiting (PENDING:
29
+ * never delivered, or REQUESTED: delivered and unanswered) past its
30
+ * marketplace's answer window — the engine's `cancellationWindowMs`, else the
31
+ * adapter's `cancellationAnswerWindowMs`, counted from the request — is FAILED
32
+ * as TIMEOUT, and the host hears it through `onCancellationFailed` (FUT-4758,
33
+ * the owner: "it cannot stay in that state with nothing happening"). The
34
+ * store then cancels in the marketplace's own app. A PENDING request's
35
+ * retries stop with it: the job re-reads the row and sends only from PENDING,
36
+ * a run that starts past the window ends TIMEOUT itself without calling, and
37
+ * this sweep re-queues no FAILED row. The window is read at the sweep's own
38
+ * cadence, so a request ends between the window and the window plus one pass.
39
+ *
23
40
  * Re-queued under a key of its own per pass: a queue keeps a finished job's id
24
41
  * and would swallow a re-queue under the job's plain key. The job itself is
25
42
  * idempotent by the row, so a duplicate run calls nobody twice.
@@ -34,9 +51,15 @@ export const OUTBOUND_GIVE_UP_MS = 24 * 60 * 60_000;
34
51
  /** What one sweep pass did. */
35
52
  export interface OutboundSweepResult {
36
53
  requeued: number;
54
+ /** Requests still waiting past {@link OUTBOUND_GIVE_UP_MS}, failed as TIMEOUT. */
37
55
  givenUp: number;
56
+ /** Requests failed as TIMEOUT past their marketplace's answer window. */
57
+ timedOut: number;
38
58
  }
39
59
 
60
+ /** A store's cancellation request still waiting on the marketplace. */
61
+ const WAITING = ["PENDING", "REQUESTED"];
62
+
40
63
  interface OwedRow {
41
64
  clientId: string;
42
65
  orderId: string;
@@ -60,15 +83,69 @@ async function requeue(ctx: EngineContext, rows: readonly OwedRow[], action: Out
60
83
  }
61
84
 
62
85
  /** Re-queue every owed call older than the job's retry span; give up on the ancient ones. */
86
+ /**
87
+ * Fail as TIMEOUT every request in `rows` still waiting, one predicated write
88
+ * each, so a confirmation that lands meanwhile wins and its host hears nothing
89
+ * twice. Returns how many moved.
90
+ */
91
+ export async function failAsTimeout(ctx: EngineContext, rows: readonly OwedRow[]): Promise<number> {
92
+ const db = await ctx.ports.db();
93
+ let failed = 0;
94
+ for (const row of rows) {
95
+ const moved = await db.marketplaceAcceptance.updateMany({
96
+ where: { orderId: row.orderId, clientId: row.clientId, cancellationStatus: { in: WAITING } },
97
+ data: failedRequestData("TIMEOUT"),
98
+ });
99
+ if (moved.count === 0) continue;
100
+ failed += 1;
101
+ ctx.ports.publishChanged(row.clientId);
102
+ await tellCancellationFailed(ctx, row.clientId, row.orderId, "TIMEOUT");
103
+ }
104
+ return failed;
105
+ }
106
+
107
+ /** Every request in `statuses` since before `cutoff`, for one provider or all. */
108
+ async function waitingSince(
109
+ ctx: EngineContext,
110
+ cutoff: Date,
111
+ statuses: readonly string[],
112
+ provider?: string,
113
+ ): Promise<OwedRow[]> {
114
+ const db = await ctx.ports.db();
115
+ return (await db.marketplaceAcceptance.findMany({
116
+ where: { ...(provider ? { provider } : {}), cancellationStatus: { in: statuses }, cancellationRequestedAt: { lt: cutoff } },
117
+ select: OWED_SELECT,
118
+ })) as OwedRow[];
119
+ }
120
+
121
+ /** Fail every request still waiting past its marketplace's window; no window, only the give-up. */
122
+ async function expireUnanswered(ctx: EngineContext, now: Date): Promise<number> {
123
+ // Only for a host that requests first: a 1.0.0 host (it cancelled already)
124
+ // keeps the re-queue and the 24-hour give-up exactly as before.
125
+ if (!requestsFirst(ctx)) return 0;
126
+ let expired = 0;
127
+ for (const provider of ctx.registry.providers()) {
128
+ const adapter = ctx.registry.get(provider);
129
+ const window = adapter ? cancellationWindowMs(ctx, adapter) : null;
130
+ if (window === null) continue;
131
+ const cutoff = new Date(now.getTime() - window);
132
+ expired += await failAsTimeout(ctx, await waitingSince(ctx, cutoff, WAITING, provider));
133
+ }
134
+ return expired;
135
+ }
136
+
137
+ /**
138
+ * One sweep pass: expire the requests nobody answered, give up on the very old,
139
+ * and re-queue what is still owed.
140
+ */
63
141
  export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<OutboundSweepResult> {
64
142
  const db = await ctx.ports.db();
65
143
  const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
66
144
  const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
67
145
 
68
- const abandoned = await db.marketplaceAcceptance.updateMany({
69
- where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: giveUp } },
70
- data: { cancellationStatus: "FAILED" },
71
- });
146
+ const timedOut = await expireUnanswered(ctx, now);
147
+ // 1.0.0 gave up on PENDING requests only; a host that requests first, on any still waiting.
148
+ const givenUp = await failAsTimeout(ctx, await waitingSince(ctx, giveUp, requestsFirst(ctx) ? WAITING : ["PENDING"]));
72
149
  const cancellations = (await db.marketplaceAcceptance.findMany({
73
150
  where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: stale, gte: giveUp } },
74
151
  select: OWED_SELECT,
@@ -79,12 +156,14 @@ export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<Outb
79
156
  confirmedAt: null,
80
157
  confirmFailedAt: null,
81
158
  acknowledgedAt: { lt: stale, gte: giveUp },
159
+ // An accept the store asked to cancel is not confirmed while the request waits.
160
+ ...NO_STANDING_REQUEST,
82
161
  },
83
162
  select: OWED_SELECT,
84
163
  })) as OwedRow[];
85
164
 
86
165
  const requeued =
87
166
  (await requeue(ctx, cancellations, "requestCancellation", now)) + (await requeue(ctx, confirms, "confirm", now));
88
- if (abandoned.count > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${abandoned.count} cancellation request(s).`);
89
- return { requeued, givenUp: abandoned.count };
167
+ if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
168
+ return { requeued, givenUp, timedOut };
90
169
  }