@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
@@ -1,6 +1,15 @@
1
1
  import type { MarketplaceAdapter, OutboundOrderRef, OutboundResult } from "./adapter";
2
+ import {
3
+ cancellationWindowMs,
4
+ confirmedToHost,
5
+ failedRequestData,
6
+ rejectConfirmed,
7
+ requestsFirst,
8
+ tellCancellationFailed,
9
+ } from "./cancellation-outcome";
2
10
  import { readOutboundConnection, type OutboundConnection } from "./integration";
3
11
  import type { OutboundJobPayload } from "./outbound-queue";
12
+ import { failAsTimeout } from "./outbound-sweep";
4
13
  import type { EngineContext } from "./ports";
5
14
  import { resolveReason } from "./registry";
6
15
 
@@ -56,6 +65,7 @@ interface OutboundRow {
56
65
  cancellationStatus: string | null;
57
66
  cancellationReasonCode: string | null;
58
67
  cancellationOffendingSkus: unknown;
68
+ cancellationRequestedAt: Date | null;
59
69
  preparationMinutes: number | null;
60
70
  createdAt: Date;
61
71
  }
@@ -71,6 +81,7 @@ const ROW_SELECT = {
71
81
  cancellationStatus: true,
72
82
  cancellationReasonCode: true,
73
83
  cancellationOffendingSkus: true,
84
+ cancellationRequestedAt: true,
74
85
  preparationMinutes: true,
75
86
  createdAt: true,
76
87
  } as const;
@@ -87,6 +98,11 @@ function refOf(row: OutboundRow): OutboundOrderRef {
87
98
  /** Why a confirm is not owed, or null when it is. */
88
99
  function confirmSkip(row: OutboundRow, adapter: MarketplaceAdapter): string | null {
89
100
  if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
101
+ // A request to cancel stands (FUT-4758: the status stays ACCEPTED while it
102
+ // waits): confirming now would tell the marketplace the opposite.
103
+ if (row.cancellationStatus !== null && row.cancellationStatus !== "FAILED") {
104
+ return `a cancellation request is ${row.cancellationStatus}`;
105
+ }
90
106
  if (row.confirmedAt || row.confirmFailedAt) return "the confirm is already stamped";
91
107
  if (!adapter.capabilities.apiConfirm) return "the marketplace has no confirm API";
92
108
  return null;
@@ -106,17 +122,79 @@ async function stampConfirm(
106
122
  });
107
123
  }
108
124
 
109
- /** The cancellation stamp, predicated on the request still being PENDING. */
125
+ /**
126
+ * The cancellation stamp, predicated on the request still being PENDING, and
127
+ * the host told how it ended when this run is what ended it (FUT-4758): a
128
+ * marketplace that answers in the response CONFIRMS here, and a refusal FAILS
129
+ * here. REQUESTED tells nobody: the answer is still to come, by event.
130
+ */
110
131
  async function stampCancellation(
111
132
  ctx: EngineContext,
112
133
  row: OutboundRow,
113
134
  status: "REQUESTED" | "CONFIRMED" | "FAILED",
135
+ clientId: string,
114
136
  ): Promise<void> {
137
+ if (status === "CONFIRMED") return stampConfirmedCancellation(ctx, row, clientId);
115
138
  const db = await ctx.ports.db();
116
- await db.marketplaceAcceptance.updateMany({
139
+ const data = status === "FAILED" ? failedRequestData("REFUSED") : { cancellationStatus: status };
140
+ const moved = await db.marketplaceAcceptance.updateMany({
117
141
  where: { orderId: row.orderId, cancellationStatus: "PENDING" },
118
- data: { cancellationStatus: status },
142
+ data,
119
143
  });
144
+ if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
145
+ }
146
+
147
+ /**
148
+ * Which rows a synchronous "cancelled" answers: the request still waiting or
149
+ * FAILED, or the tombstone an accept left of THIS request (no status, the
150
+ * same `cancellation_requested_at` the job read) on an order STILL ACCEPTED.
151
+ * A later request of the store carries a new instant and a status of its own,
152
+ * so it is never mistaken for it; and once the marketplace's own cancel event
153
+ * has moved the order to REJECTED (and told the host), the tombstone answers
154
+ * nothing more, so the host is never told twice.
155
+ */
156
+ function answerableRequest(row: OutboundRow): Record<string, unknown>[] {
157
+ const waiting = { cancellationStatus: { in: ["PENDING", "FAILED"] } };
158
+ if (row.cancellationRequestedAt === null) return [waiting];
159
+ const tombstone = { status: "ACCEPTED", cancellationStatus: null, cancellationRequestedAt: row.cancellationRequestedAt };
160
+ return [waiting, tombstone];
161
+ }
162
+
163
+ /**
164
+ * A marketplace that confirms in its answer: the same stamps as its
165
+ * CANCELLED event (`cancelAcceptance`) — CONFIRMED and REJECTED in one
166
+ * transaction — then the host's `onCancellationConfirmed`, or
167
+ * `onRefused(…, "CANCELLED")` when it binds none. A host failure is logged:
168
+ * the stamps have committed.
169
+ */
170
+ async function stampConfirmedCancellation(ctx: EngineContext, row: OutboundRow, clientId: string): Promise<void> {
171
+ const now = ctx.ports.clock.now();
172
+ const moved = await ctx.ports.transaction(async (tx) => {
173
+ // From FAILED too: the sweep may have timed the request out while this
174
+ // call was in flight, and a marketplace that answers in the response sends
175
+ // no event — its "cancelled" is the only word that it did (the event path's
176
+ // own rule: a confirmation after a TIMEOUT still confirms). And from the
177
+ // TOMBSTONE of this same request (FUT-4765, R3-N2): the store may have
178
+ // accepted the order once the request timed out, which clears the request
179
+ // but keeps its `cancellation_requested_at`. The order is cancelled on the
180
+ // marketplace, so it is cancelled here too, and the host hears it.
181
+ const confirmed = await tx.marketplaceAcceptance.updateMany({
182
+ where: { orderId: row.orderId, OR: answerableRequest(row) },
183
+ data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null },
184
+ });
185
+ if (confirmed.count === 0) return false;
186
+ await rejectConfirmed(tx, row.orderId, now);
187
+ return true;
188
+ });
189
+ if (!moved) return;
190
+ try {
191
+ await confirmedToHost(ctx, clientId, row.orderId);
192
+ } catch (error) {
193
+ ctx.ports.logger.error(
194
+ `marketplace.outbound: order ${row.orderId} was cancelled on the store's request but the host's half failed: ` +
195
+ (error instanceof Error ? error.message : String(error)),
196
+ );
197
+ }
120
198
  }
121
199
 
122
200
  /** The connection, or the reason it cannot be used (a refusal: no retry fixes it). */
@@ -188,6 +266,15 @@ async function runConfirm(
188
266
  );
189
267
  }
190
268
 
269
+ /** Whether a request is older than its marketplace's answer window, so it must not be sent any more. */
270
+ function pastWindow(ctx: EngineContext, row: OutboundRow, adapter: MarketplaceAdapter): boolean {
271
+ // A 1.0.0 host (no `onCancellationConfirmed`) has no window: it retries, as before.
272
+ if (!requestsFirst(ctx)) return false;
273
+ const window = cancellationWindowMs(ctx, adapter);
274
+ if (window === null || row.cancellationRequestedAt === null) return false;
275
+ return ctx.ports.clock.now().getTime() - row.cancellationRequestedAt.getTime() > window;
276
+ }
277
+
191
278
  /** The offending SKUs stored with the request. */
192
279
  function skusOf(row: OutboundRow): string[] {
193
280
  return Array.isArray(row.cancellationOffendingSkus) ? row.cancellationOffendingSkus.map(String) : [];
@@ -203,6 +290,12 @@ async function runCancellation(
203
290
  if (row.cancellationStatus !== "PENDING") {
204
291
  return { kind: "skipped", reason: `the request is ${row.cancellationStatus ?? "absent"}, not PENDING` };
205
292
  }
293
+ if (pastWindow(ctx, row, adapter)) {
294
+ // A retry that comes after the window never delivers (FUT-4758): the host
295
+ // was, or is now, told TIMEOUT, and the store cancels in the marketplace's app.
296
+ await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);
297
+ return { kind: "failed", action: payload.action, reason: "past the marketplace's answer window" };
298
+ }
206
299
  const reason = resolveReason(adapter, row.cancellationReasonCode);
207
300
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
208
301
  let result: OutboundResult;
@@ -222,8 +315,8 @@ async function runCancellation(
222
315
  row,
223
316
  result,
224
317
  attempt,
225
- () => stampCancellation(ctx, row, taken),
226
- () => stampCancellation(ctx, row, "FAILED"),
318
+ () => stampCancellation(ctx, row, taken, payload.clientId),
319
+ () => stampCancellation(ctx, row, "FAILED", payload.clientId),
227
320
  );
228
321
  }
229
322
 
@@ -235,17 +328,20 @@ async function runCancellation(
235
328
  async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {
236
329
  const reason = error instanceof Error ? error.message : String(error);
237
330
  const db = await ctx.ports.db();
238
- await (payload.action === "confirm"
331
+ const moved = await (payload.action === "confirm"
239
332
  ? db.marketplaceAcceptance.updateMany({
240
333
  where: { orderId: payload.orderId, clientId: payload.clientId, confirmedAt: null, confirmFailedAt: null },
241
334
  data: { confirmFailedAt: ctx.ports.clock.now() },
242
335
  })
243
336
  : db.marketplaceAcceptance.updateMany({
244
337
  where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: "PENDING" },
245
- data: { cancellationStatus: "FAILED" },
338
+ data: failedRequestData("REFUSED"),
246
339
  }));
247
340
  ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);
248
341
  ctx.ports.publishChanged(payload.clientId);
342
+ if (payload.action === "requestCancellation" && moved.count > 0) {
343
+ await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "REFUSED");
344
+ }
249
345
  return { kind: "failed", action: payload.action, reason };
250
346
  }
251
347
 
@@ -0,0 +1,101 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+
3
+ /**
4
+ * The defensive readers every adapter's normalizer is built from.
5
+ *
6
+ * A marketplace payload is UNTRUSTED: a documented shape and the shape that
7
+ * actually arrives drift, and a `TypeError` reading a missing field would
8
+ * reject a paid order at the door. Every reader here produces a value or
9
+ * null, never a throw. They are wire-format-neutral (no marketplace's key
10
+ * names), which is why they live beside the engine rather than in an adapter.
11
+ */
12
+
13
+ /** Read a nested value without asserting the shape of anything on the way. */
14
+ export function pick(source: unknown, ...path: string[]): unknown {
15
+ let cursor: unknown = source;
16
+ for (const key of path) {
17
+ if (typeof cursor !== "object" || cursor === null) return undefined;
18
+ cursor = (cursor as Record<string, unknown>)[key];
19
+ }
20
+ return cursor;
21
+ }
22
+
23
+ /** A non-blank string (trimmed), a finite number as text, or null. */
24
+ export function asString(value: unknown): string | null {
25
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
26
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
27
+ return null;
28
+ }
29
+
30
+ /**
31
+ * The first of several candidate paths that yields a string.
32
+ *
33
+ * A marketplace states the same fact under different keys depending on which
34
+ * API version delivered it, so nearly every read is a fallback chain. Expressed
35
+ * as data rather than as `??` so a chain grows by one entry, not one branch.
36
+ */
37
+ export function firstString(source: unknown, paths: string[][]): string | null {
38
+ for (const path of paths) {
39
+ const found = asString(pick(source, ...path));
40
+ if (found !== null) return found;
41
+ }
42
+ return null;
43
+ }
44
+
45
+ /**
46
+ * Money stated in DECIMAL units (`12.9`) → integer cents.
47
+ *
48
+ * Rounded rather than truncated: `Math.trunc(12.9 * 100)` is 1289 on IEEE-754,
49
+ * so truncation loses a cent on ordinary prices, always in the store's
50
+ * disfavour.
51
+ */
52
+ export function toCents(value: unknown): number | null {
53
+ const numeric = typeof value === "string" ? Number(value) : value;
54
+ if (typeof numeric !== "number" || !Number.isFinite(numeric)) return null;
55
+ return Math.round(numeric * 100);
56
+ }
57
+
58
+ /** {@link firstString} for money. */
59
+ export function firstCents(source: unknown, paths: string[][]): number | null {
60
+ for (const path of paths) {
61
+ const found = toCents(pick(source, ...path));
62
+ if (found !== null) return found;
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /** An ISO timestamp → a Date, or null when absent or unparseable. */
68
+ function toDate(value: unknown): Date | null {
69
+ const raw = asString(value);
70
+ if (!raw) return null;
71
+ const parsed = new Date(raw);
72
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
73
+ }
74
+
75
+ /** {@link firstString} for timestamps. */
76
+ export function firstDate(source: unknown, paths: string[][]): Date | null {
77
+ for (const path of paths) {
78
+ const found = toDate(pick(source, ...path));
79
+ if (found !== null) return found;
80
+ }
81
+ return null;
82
+ }
83
+
84
+ /**
85
+ * Verify a lowercase-hex HMAC-SHA256 of the raw body (an optional `sha256=`
86
+ * prefix tolerated), keyed by `secret`.
87
+ *
88
+ * Unsigned deliveries are refused whenever a secret is CONFIGURED; a store
89
+ * that has not set one yet is accepted, and that state is visible on the
90
+ * connection screen rather than silent. Compared in constant time over bytes:
91
+ * an early-exit `===` on a hex digest leaks the prefix a forger already got
92
+ * right, one request at a time.
93
+ */
94
+ export function verifyHmacSha256Hex(rawBody: string, signature: string | null, secret: string | null): boolean {
95
+ if (!secret) return true;
96
+ if (!signature) return false;
97
+ const expected = createHmac("sha256", secret).update(rawBody, "utf8").digest("hex");
98
+ const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, ""), "utf8");
99
+ const mine = Buffer.from(expected, "utf8");
100
+ return given.length === mine.length && timingSafeEqual(given, mine);
101
+ }
@@ -1,10 +1,12 @@
1
1
  import { cancelAcceptance } from "./acceptance";
2
2
  import { failCancellationRequest } from "./cancellation";
3
+ import { awaitOrderBody, merchantMismatch, requeueOwedFetch } from "./fetch-order";
3
4
  import { deferInboxEvent, recordInboxEvent, settleInboxEvent } from "./inbox";
4
5
  import { ingestMarketplaceOrder, type IngestSettings } from "./ingest";
5
- import { resolveIngestionTarget } from "./integration";
6
+ import { connectionMerchantId, resolveIngestionTarget } from "./integration";
7
+ import { markCancelledBeforeIngest } from "./order-fetch-marks";
6
8
  import type { EngineContext } from "./ports";
7
- import type { MarketplaceProvider, NormalizedEvent } from "./types";
9
+ import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
8
10
 
9
11
  /**
10
12
  * One delivery, start to finish: normalize → inbox → ingest.
@@ -34,6 +36,8 @@ export type DeliveryOutcome =
34
36
  | { kind: "ingested"; orderId: string; unmappedSkus: string[] }
35
37
  | { kind: "cancelled" }
36
38
  | { kind: "cancellationFailed" }
39
+ /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
40
+ | { kind: "awaitingOrder" }
37
41
  | { kind: "duplicate" }
38
42
  | { kind: "ignored"; reason: string }
39
43
  | { kind: "failed"; reason: string };
@@ -88,6 +92,28 @@ export async function processDelivery(
88
92
  }
89
93
  }
90
94
 
95
+ /** The event names an order whose body the marketplace serves apart (`orderToFetch`). */
96
+ function announcesOrderToFetch(event: NormalizedEvent): boolean {
97
+ return event.order === null && event.orderToFetch === true && event.externalOrderId !== null;
98
+ }
99
+
100
+ /**
101
+ * Why an order the event CARRIES must not be ingested for this store: it names
102
+ * another merchant than the connection's (a wrong webhook URL, a replay), the
103
+ * rule a fetched order is held to. Read only for an order that names its
104
+ * merchant (an adapter that sets `externalMerchantId` on the order); an order
105
+ * that names none costs no read.
106
+ */
107
+ async function carriedOrderMismatch(
108
+ ctx: EngineContext,
109
+ clientId: string,
110
+ order: NormalizedMarketplaceOrder,
111
+ ): Promise<string | null> {
112
+ if (!order.externalMerchantId) return null;
113
+ // The one column, never the whole target: no credentials opened per order.
114
+ return merchantMismatch(order, await connectionMerchantId(ctx, clientId, order.provider));
115
+ }
116
+
91
117
  /**
92
118
  * Act on one recorded delivery: cancel, ingest, or deliberately nothing.
93
119
  *
@@ -118,16 +144,22 @@ async function applyEvent(
118
144
  }
119
145
 
120
146
  if (event.cancelled && event.externalOrderId) {
121
- await cancelAcceptance(ctx, {
122
- clientId,
123
- provider: event.provider,
124
- externalOrderId: event.externalOrderId,
125
- now,
126
- });
147
+ const order = { clientId, provider: event.provider, externalOrderId: event.externalOrderId };
148
+ // A cancellation that outran a fetched order's body leaves its marker, so
149
+ // the fetch that follows ingests nothing.
150
+ if (!(await cancelAcceptance(ctx, { ...order, now }))) await markCancelledBeforeIngest(ctx, order);
127
151
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
128
152
  return { kind: "cancelled" };
129
153
  }
130
154
 
155
+ if (announcesOrderToFetch(event)) {
156
+ // The event announces an order whose body the marketplace serves apart.
157
+ // Fetching is a call to the marketplace, so it is a job's, never this
158
+ // request's: the row waits PENDING and the fetch is queued.
159
+ await awaitOrderBody(ctx, clientId, inboxId);
160
+ return { kind: "awaitingOrder" };
161
+ }
162
+
131
163
  if (!event.order) {
132
164
  // An event type this ingestion does not act on. Marketplaces emit a wide
133
165
  // stream (dispatched, concluded, driver assigned…) and most of it is not an
@@ -138,12 +170,27 @@ async function applyEvent(
138
170
  return { kind: "ignored", reason };
139
171
  }
140
172
 
141
- const result = await ingestMarketplaceOrder(ctx, {
142
- clientId,
143
- order: event.order,
144
- settings,
145
- now,
146
- });
173
+ return ingestCarried(ctx, inboxId, clientId, event.order, settings, now);
174
+ }
175
+
176
+ /** Ingest the order an event carries, unless it names another merchant than the connection's. */
177
+ async function ingestCarried(
178
+ ctx: EngineContext,
179
+ inboxId: string,
180
+ clientId: string,
181
+ order: NormalizedMarketplaceOrder,
182
+ settings: IngestSettings,
183
+ now: Date | undefined,
184
+ ): Promise<DeliveryOutcome> {
185
+ const mismatch = await carriedOrderMismatch(ctx, clientId, order);
186
+ if (mismatch) {
187
+ // FAILED, so the reconciliation sweep retries it once the connection's
188
+ // merchant id is corrected, within the inbox's attempt bound.
189
+ await settleInboxEvent(ctx, inboxId, "FAILED", mismatch);
190
+ ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);
191
+ return { kind: "failed", reason: mismatch };
192
+ }
193
+ const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });
147
194
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
148
195
  return { kind: "ingested", orderId: result.orderId, unmappedSkus: result.unmappedSkus };
149
196
  }
@@ -158,7 +205,7 @@ async function applyEvent(
158
205
  */
159
206
  export async function reprocessStoredDelivery(
160
207
  ctx: EngineContext,
161
- input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown },
208
+ input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown; receivedAt?: Date | null },
162
209
  ): Promise<DeliveryOutcome> {
163
210
  const event = normalizeEvent(ctx, input.provider, input.payload);
164
211
  if (!event) {
@@ -176,6 +223,8 @@ export async function reprocessStoredDelivery(
176
223
  await deferInboxEvent(ctx, input.id, reason);
177
224
  return { kind: "ignored", reason };
178
225
  }
226
+ // A row waiting for its order body is the fetch job's: re-queued, never fetched here.
227
+ if (announcesOrderToFetch(event)) return requeueOwedFetch(ctx, input);
179
228
  try {
180
229
  return await applyEvent(
181
230
  ctx,
package/src/core/ports.ts CHANGED
@@ -116,6 +116,13 @@ export type MarketplaceAdmissionResult =
116
116
  /** Why the engine tells the host to refuse an order. Vocabulary, not copy. */
117
117
  export type MarketplaceRefusal = "REJECTED" | "EXPIRED" | "CANCELLED";
118
118
 
119
+ /**
120
+ * Why the store's own cancellation request FAILED: REFUSED (the marketplace
121
+ * said no, or every attempt failed) or TIMEOUT (no answer inside the
122
+ * marketplace's cancellation window). Vocabulary, not copy.
123
+ */
124
+ export type CancellationFailureReason = "REFUSED" | "TIMEOUT";
125
+
119
126
  /**
120
127
  * The host's domain, as five questions the engine asks and never answers.
121
128
  *
@@ -151,6 +158,23 @@ export interface MarketplaceOrderPort {
151
158
  onAccepted(clientId: string, orderId: string): Promise<void>;
152
159
  /** The store said no, the marketplace cancelled, or the clock lapsed. */
153
160
  onRefused(clientId: string, orderId: string, reason: MarketplaceRefusal): Promise<void>;
161
+ /**
162
+ * OPTIONAL. The marketplace CONFIRMED the store's own cancellation request
163
+ * (the job's answer, or the marketplace's event). A host that requests first
164
+ * and cancels on confirm runs its cancel here. When present it is called
165
+ * INSTEAD of `onRefused(…, "CANCELLED")` for a cancellation the store asked
166
+ * for; a cancellation the marketplace made on its own still reaches
167
+ * `onRefused`. Absent (a 1.0.0 host): `onRefused(…, "CANCELLED")` as before.
168
+ */
169
+ onCancellationConfirmed?(clientId: string, orderId: string): Promise<void>;
170
+ /**
171
+ * OPTIONAL. The store's own cancellation request FAILED: refused (the job's
172
+ * answer, the marketplace's event, or the last attempt) or timed out (the
173
+ * outbound sweep, past the marketplace's window). Called once per request,
174
+ * by the call that moved the row to FAILED. The pedido is still the
175
+ * marketplace's: a person finishes it there, through the adapter's app link.
176
+ */
177
+ onCancellationFailed?(clientId: string, orderId: string, reason: CancellationFailureReason): Promise<void>;
154
178
  /** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
155
179
  summarize(
156
180
  clientId: string,
@@ -238,6 +262,14 @@ export interface MarketplacePorts {
238
262
  * awaits it, and a dead bus costs latency, never a transition.
239
263
  */
240
264
  publishChanged: (clientId: string) => void;
265
+ /**
266
+ * OPTIONAL. How long a store's cancellation request may wait for the
267
+ * marketplace's answer before the outbound sweep fails it as TIMEOUT, in
268
+ * milliseconds, for every adapter. Absent: each adapter's own
269
+ * `capabilities.cancellationAnswerWindowMs`; an adapter that states none is
270
+ * only given up on after `OUTBOUND_GIVE_UP_MS`.
271
+ */
272
+ cancellationWindowMs?: number;
241
273
  /** The acceptance window a connection gets when it does not state its own. */
242
274
  defaultAckSlaSeconds: number;
243
275
  /** How many stored deliveries one reconciliation pass re-runs. */
package/src/core/state.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
2
- import type { EngineContext } from "./ports";
2
+ import type { CancellationFailureReason, EngineContext } from "./ports";
3
3
  import type { MarketplaceProvider } from "./types";
4
4
 
5
5
  /**
@@ -17,6 +17,8 @@ export interface MarketplaceOrderState {
17
17
  confirmFailedAt: Date | null;
18
18
  cancellation: CancellationStatus | null;
19
19
  cancellationReasonCode: string | null;
20
+ /** Why the request FAILED (REFUSED or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */
21
+ cancellationFailure: CancellationFailureReason | null;
20
22
  /** The adapter's app link, or null when no adapter is registered for it. */
21
23
  appUrl: string | null;
22
24
  }
@@ -31,6 +33,7 @@ interface StateRow {
31
33
  confirmFailedAt: Date | null;
32
34
  cancellationStatus: string | null;
33
35
  cancellationReasonCode: string | null;
36
+ cancellationFailureReason: string | null;
34
37
  }
35
38
 
36
39
  /** The state of each of these orders that is a marketplace order, keyed by id. */
@@ -53,6 +56,7 @@ export async function readOrderStates(
53
56
  confirmFailedAt: true,
54
57
  cancellationStatus: true,
55
58
  cancellationReasonCode: true,
59
+ cancellationFailureReason: true,
56
60
  },
57
61
  })) as StateRow[];
58
62
  return new Map(
@@ -68,6 +72,7 @@ export async function readOrderStates(
68
72
  confirmFailedAt: row.confirmFailedAt,
69
73
  cancellation: row.cancellationStatus as CancellationStatus | null,
70
74
  cancellationReasonCode: row.cancellationReasonCode,
75
+ cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,
71
76
  appUrl: adapter ? adapter.appLink(row) : null,
72
77
  };
73
78
  return [row.orderId, state];
package/src/core/types.ts CHANGED
@@ -96,6 +96,12 @@ export interface NormalizedMarketplaceOrder {
96
96
  deliveredBy?: MarketplaceDeliveredBy | null;
97
97
  /** Null on a take-out and when unstated. */
98
98
  deliveryAddress?: NormalizedAddress | null;
99
+ /**
100
+ * OPTIONAL. The merchant the order names, when its body says (Open
101
+ * Delivery's `merchant.id`). A fetched order naming another merchant than
102
+ * the connection's is refused.
103
+ */
104
+ externalMerchantId?: string | null;
99
105
  }
100
106
 
101
107
  /**
@@ -128,4 +134,12 @@ export interface NormalizedEvent {
128
134
  * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.
129
135
  */
130
136
  cancellationOutcome?: CancellationOutcome | null;
137
+ /**
138
+ * OPTIONAL. This event announces an order whose body the marketplace serves
139
+ * separately (Open Delivery's `CREATED` carries only the order's id): the
140
+ * engine fetches it through the adapter's `fetchOrder`, in the
141
+ * `marketplace.fetch-order` job, never inside the request that delivered
142
+ * the event. Ignored when `order` is present.
143
+ */
144
+ orderToFetch?: boolean;
131
145
  }
@@ -25,6 +25,9 @@ export const IFOOD_PROVIDER = "IFOOD";
25
25
  /** The one reason that means "an item is unavailable". */
26
26
  const ITEM_UNAVAILABLE: IfoodReasonCode = "503";
27
27
 
28
+ /** How long iFood may take to answer a cancellation request: 5 minutes, ESTIMATED (see the adapter's capabilities). */
29
+ export const IFOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;
30
+
28
31
  export interface IfoodAdapterConfig {
29
32
  /** The words the adapter needs: reason labels and the missing-number text. Required. */
30
33
  copy: IfoodAdapterCopy;
@@ -48,6 +51,12 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
48
51
  asyncCancellationOutcome: true,
49
52
  perOrderAppLink: false,
50
53
  confirmTakesPreparationTime: false,
54
+ // How long iFood takes, at most, to answer a cancellation request: its
55
+ // CANCELLED or CANCELLATION_REQUEST_FAILED event. ESTIMATED, not read off
56
+ // iFood's documentation, which names no answer deadline: iFood answers a
57
+ // request in seconds when it answers at all, so 5 minutes is generous.
58
+ // A host overrides it with the engine's `cancellationWindowMs`.
59
+ cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
51
60
  },
52
61
  normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
53
62
  readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),