@12-apps/marketplace 1.6.0 → 1.8.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 (74) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +56 -0
  3. package/dist/99food/index.d.ts +4 -2
  4. package/dist/99food/index.js +38 -6
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-CCWMqt2g.d.ts → adapter-CYJzu1c9.d.ts} +81 -2
  7. package/dist/{chunk-4CJ7B5OR.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-NFZT5TWR.js → chunk-BMCERPQX.js} +214 -24
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-RGMSD7S7.js → chunk-HEXLCTOG.js} +7 -1
  12. package/dist/chunk-HEXLCTOG.js.map +1 -0
  13. package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
  14. package/dist/chunk-NP4EYKPO.js.map +1 -0
  15. package/dist/{engine-w2TgRrlc.d.ts → engine-wmW-VuBL.d.ts} +123 -9
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +3 -3
  18. package/dist/ifood/index.d.ts +1 -1
  19. package/dist/ifood/index.js +66 -6
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +119 -12
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/index.d.ts +3 -0
  25. package/dist/manifest/index.js +1 -1
  26. package/dist/manifest/server.d.ts +2 -2
  27. package/dist/manifest/server.js +3 -3
  28. package/dist/rappi/index.d.ts +7 -1
  29. package/dist/rappi/index.js +23 -5
  30. package/dist/rappi/index.js.map +1 -1
  31. package/dist/server/index.d.ts +6 -2
  32. package/dist/server/index.js +3 -3
  33. package/package.json +1 -1
  34. package/prisma/marketplace.prisma +48 -4
  35. package/prisma/migrations/20261125180000_marketplace_cancellation_failure_reason_widen/migration.sql +16 -0
  36. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  37. package/src/99food/index.ts +6 -0
  38. package/src/99food/normalize.ts +7 -1
  39. package/src/99food/outbound.ts +62 -2
  40. package/src/core/adapter.ts +58 -3
  41. package/src/core/bulk.ts +1 -1
  42. package/src/core/cancellation.ts +4 -1
  43. package/src/core/catalogue.ts +4 -3
  44. package/src/core/decisions.ts +3 -2
  45. package/src/core/engine.ts +9 -0
  46. package/src/core/fetch-order.ts +2 -2
  47. package/src/core/ingest.ts +6 -0
  48. package/src/core/integration.ts +17 -0
  49. package/src/core/lifecycle-port.ts +16 -0
  50. package/src/core/lifecycle.ts +133 -0
  51. package/src/core/order-fetch-marks.ts +13 -8
  52. package/src/core/outbound-queue.ts +24 -4
  53. package/src/core/outbound-sweep.ts +49 -5
  54. package/src/core/outbound.ts +26 -11
  55. package/src/core/pipeline.ts +35 -3
  56. package/src/core/ports.ts +54 -7
  57. package/src/core/state.ts +1 -1
  58. package/src/core/status-inform.ts +51 -0
  59. package/src/core/status-job.ts +207 -0
  60. package/src/core/status-store.ts +85 -0
  61. package/src/core/types.ts +39 -0
  62. package/src/ifood/index.ts +7 -1
  63. package/src/ifood/normalize.ts +70 -0
  64. package/src/ifood/outbound.ts +37 -1
  65. package/src/index.ts +9 -0
  66. package/src/rappi/index.ts +6 -1
  67. package/src/rappi/normalize.ts +6 -0
  68. package/src/rappi/outbound.ts +33 -3
  69. package/src/server/mcp.ts +2 -0
  70. package/src/server/webhook.ts +3 -1
  71. package/dist/chunk-4CJ7B5OR.js.map +0 -1
  72. package/dist/chunk-NFZT5TWR.js.map +0 -1
  73. package/dist/chunk-RGMSD7S7.js.map +0 -1
  74. package/dist/chunk-UYFYGGCS.js.map +0 -1
@@ -0,0 +1,133 @@
1
+ import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
+ import type { IngestSettings } from "./ingest";
3
+ import type { DeliveryOutcome } from "./pipeline";
4
+ import type { EngineContext } from "./ports";
5
+ import { readStatusRows, noteMarketplaceStep, statusTable } from "./status-store";
6
+ import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } from "./types";
7
+
8
+ /**
9
+ * Inbound lifecycle (FUT-4653): the marketplace says the order was dispatched
10
+ * or concluded, and the order follows, FORWARD only.
11
+ *
12
+ * What the engine owns, in order, each stopping the event with a reason the
13
+ * inbox row keeps:
14
+ *
15
+ * 1. an order the engine does not hold yet is DEFERRED (PENDING, one attempt
16
+ * counted), so the reconcile pass applies the event after the order's own
17
+ * event ingests, and retires it after `maxInboxAttempts` like any row;
18
+ * 2. an order that is not ACCEPTED is never moved: the aceite is where the
19
+ * stock is judged, and an ended order is not revived;
20
+ * 3. a cancellation request standing (PENDING or REQUESTED) is the store's
21
+ * last word and nothing here contradicts it;
22
+ * 4. an event that answers a step WE informed (a STORE row for DISPATCHED, or
23
+ * for HANDED_OVER when the event is CONCLUDED) is an echo: the failure case
24
+ * of forward-only alone is the store's undo, where the echo would
25
+ * dispatch a card again with no courier.
26
+ *
27
+ * What the host owns (`onLifecycle`): whether the order can move, to where,
28
+ * and how. Whatever it answers, the step is NOTED as the marketplace's, so our
29
+ * own job never informs it back and nothing is informed after a CONCLUDED.
30
+ *
31
+ * A host that binds no `onLifecycle`, a connection with the switch OFF (or
32
+ * settings built by hand without it) and a host without the status model get
33
+ * `null`: the caller's old answer, "no order body", byte for byte.
34
+ */
35
+
36
+ /** The step of the table an event's echo is looked for under. */
37
+ const ECHO_OF: Record<MarketplaceLifecycle, "DISPATCHED" | "HANDED_OVER"> = {
38
+ DISPATCHED: "DISPATCHED",
39
+ CONCLUDED: "HANDED_OVER",
40
+ };
41
+
42
+ interface HeldAcceptance {
43
+ orderId: string;
44
+ status: string;
45
+ deliveredBy: string | null;
46
+ cancellationStatus: string | null;
47
+ }
48
+
49
+ /** Settle the row IGNORED with a reason, and answer it. */
50
+ async function ignored(ctx: EngineContext, inboxId: string, reason: string): Promise<DeliveryOutcome> {
51
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
52
+ return { kind: "ignored", reason };
53
+ }
54
+
55
+ /** Why a held order is not moved by the marketplace's word, or null when it may be. */
56
+ function refusal(held: HeldAcceptance): string | null {
57
+ if (held.status !== "ACCEPTED") return `the order is ${held.status}, not ACCEPTED`;
58
+ // A request that FAILED left the order the store's own: only a standing one stops us.
59
+ if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") {
60
+ return `a cancellation request is ${held.cancellationStatus}`;
61
+ }
62
+ return null;
63
+ }
64
+
65
+ function deliveredByOf(held: HeldAcceptance): MarketplaceDeliveredBy | null {
66
+ return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
67
+ }
68
+
69
+ /** What `followLifecycle` needs once it is known the connection follows this event. */
70
+ interface Following {
71
+ lifecycle: MarketplaceLifecycle;
72
+ externalOrderId: string;
73
+ hook: NonNullable<EngineContext["ports"]["order"]["onLifecycle"]>;
74
+ }
75
+
76
+ /** Whether this ingestion follows this event at all: a lifecycle, the switch ON, a host hook. */
77
+ function following(ctx: EngineContext, event: NormalizedEvent, settings: IngestSettings): Following | null {
78
+ const hook = ctx.ports.order.onLifecycle;
79
+ if (!event.lifecycle || !event.externalOrderId || !settings.followStatus || !hook) return null;
80
+ return { lifecycle: event.lifecycle, externalOrderId: event.externalOrderId, hook };
81
+ }
82
+
83
+ /**
84
+ * Apply one lifecycle event, or null when this ingestion does not follow it
85
+ * (no lifecycle, switch OFF, no hook, no status model): the caller then does
86
+ * what it did before FUT-4653.
87
+ */
88
+ export async function followLifecycle(
89
+ ctx: EngineContext,
90
+ inboxId: string,
91
+ clientId: string,
92
+ event: NormalizedEvent,
93
+ settings: IngestSettings,
94
+ ): Promise<DeliveryOutcome | null> {
95
+ const follow = following(ctx, event, settings);
96
+ if (!follow) return null;
97
+ const { lifecycle, hook } = follow;
98
+ const db = await ctx.ports.db();
99
+ const table = statusTable(db);
100
+ if (!table) return null;
101
+
102
+ const held = (await db.marketplaceAcceptance.findFirst({
103
+ where: { clientId, provider: event.provider, externalOrderId: follow.externalOrderId },
104
+ select: { orderId: true, status: true, deliveredBy: true, cancellationStatus: true },
105
+ })) as HeldAcceptance | null;
106
+ if (!held) {
107
+ const reason = "lifecycle before its order";
108
+ await deferInboxEvent(ctx, inboxId, reason);
109
+ return { kind: "ignored", reason };
110
+ }
111
+ const stopped = refusal(held);
112
+ if (stopped) return ignored(ctx, inboxId, stopped);
113
+
114
+ const echo = ECHO_OF[lifecycle];
115
+ const ours = (await readStatusRows(table, held.orderId, [echo])).some((row) => row.source === "STORE");
116
+ if (ours) return ignored(ctx, inboxId, `echo of our ${echo}`);
117
+
118
+ // Two statements, not one: the echo was read above and the marketplace's word is noted below. A
119
+ // genuine event judged "no echo" can lose the unique on its note to our own job claiming in
120
+ // between, and that job then sends a step the marketplace already has. Harmless (at worst a 4xx,
121
+ // FAILED and logged): the marketplace's state and ours already agree, and a stricter ordering
122
+ // would put a write before the host's answer on every event.
123
+ const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
124
+ await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: lifecycle });
125
+ if (answer === "moved") {
126
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
127
+ ctx.ports.publishChanged(clientId);
128
+ return { kind: "moved", orderId: held.orderId, lifecycle };
129
+ }
130
+ const reason = answer === "unchanged" ? `already at or past ${lifecycle}` : answer.reason;
131
+ if (answer !== "unchanged") ctx.ports.logger.warn(`marketplace.lifecycle: ${event.provider} order ${held.orderId}: ${reason}`);
132
+ return ignored(ctx, inboxId, reason);
133
+ }
@@ -7,25 +7,30 @@ import type { MarketplaceProvider } from "./types";
7
7
  * For a marketplace whose events only announce an order (`fetchOrder`), the
8
8
  * marketplace's CANCELLED can arrive while the fetch is still queued, held or
9
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.
10
+ * say the order was cancelled. For a marketplace whose webhook carries the
11
+ * order, the same happens when the NEW_ORDER FAILED first: the retry sweep
12
+ * re-runs that row after the CANCELLED. Without a trace either path would
13
+ * ingest a cancelled order, send it to the kitchen and confirm it.
12
14
  *
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.
15
+ * So when a cancellation finds no acceptance to cancel, it leaves a MARKER, for
16
+ * every adapter: an IGNORED inbox row under a key derived from the order
17
+ * (`engine:cancelled:<id>`), found again through the inbox's own unique
18
+ * `(provider, eventId)` index, with no new column or table. The fetch and the
19
+ * carried ingest read it before they ingest.
17
20
  */
18
21
 
22
+ /** The settled reason of a row that was not ingested because its order was cancelled first. */
23
+ export const CANCELLED_BEFORE_INGEST_REASON = "cancelled before its order body arrived";
24
+
19
25
  const MARKER_TYPE = "ENGINE_CANCELLED_BEFORE_INGEST";
20
26
 
21
27
  const markerId = (externalOrderId: string): string => `engine:cancelled:${externalOrderId}`;
22
28
 
23
- /** Leave the marker, for an adapter that fetches its orders. Idempotent. */
29
+ /** Leave the marker, for any adapter. Idempotent. */
24
30
  export async function markCancelledBeforeIngest(
25
31
  ctx: EngineContext,
26
32
  input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
27
33
  ): Promise<void> {
28
- if (!ctx.registry.get(input.provider)?.fetchOrder) return;
29
34
  const db = await ctx.ports.db();
30
35
  try {
31
36
  await db.marketplaceInboxEvent.create({
@@ -1,3 +1,4 @@
1
+ import type { StatusStep } from "./adapter";
1
2
  import type { EngineContext } from "./ports";
2
3
  import type { MarketplaceProvider } from "./types";
3
4
 
@@ -14,19 +15,34 @@ import type { MarketplaceProvider } from "./types";
14
15
  /** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */
15
16
  export const MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
16
17
 
17
- /** What goes out: the store's aceite, or the store's cancellation request. */
18
- export type OutboundAction = "confirm" | "requestCancellation";
18
+ /**
19
+ * What goes out: the store's aceite, the store's cancellation request, or a
20
+ * step of the order the store reached (`status`, FUT-4653).
21
+ */
22
+ export type OutboundAction = "confirm" | "requestCancellation" | "status";
19
23
 
20
24
  /** The outbound job's payload. Identifiers only. */
21
25
  export interface OutboundJobPayload {
22
26
  clientId: string;
23
27
  orderId: string;
24
28
  action: OutboundAction;
29
+ /** OPTIONAL. The step a `status` call tells the marketplace about; absent on every other action. */
30
+ step?: StatusStep;
31
+ /**
32
+ * OPTIONAL. The key of the move (or of the sweep's re-claim) a `status` call
33
+ * belongs to: the owner of its SENDING claim. Absent on every other action.
34
+ */
35
+ claimKey?: string;
25
36
  }
26
37
 
27
38
  /** The dedupe key: at most one queued call per (order, action). */
28
39
  export function outboundDedupeKey(payload: OutboundJobPayload): string {
29
- return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;
40
+ return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.step ? `${payload.step}:` : ""}${payload.orderId}`;
41
+ }
42
+
43
+ /** The dedupe key of one status move: a re-dispatch after an undo is another instant, so another key. */
44
+ export function statusDedupeKey(step: StatusStep, orderId: string, at: Date): string {
45
+ return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
30
46
  }
31
47
 
32
48
  /**
@@ -50,7 +66,11 @@ export async function enqueueOutbound(
50
66
  const adapter = ctx.registry.get(provider);
51
67
  if (!adapter) return false;
52
68
  const able =
53
- payload.action === "confirm" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;
69
+ payload.action === "status"
70
+ ? Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step))
71
+ : payload.action === "confirm"
72
+ ? adapter.capabilities.apiConfirm
73
+ : adapter.capabilities.apiCancel;
54
74
  if (!able) return false;
55
75
  const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
56
76
  if (!outcome.enqueued) {
@@ -2,6 +2,8 @@ import { NO_STANDING_REQUEST } from "./cancellation";
2
2
  import { sweepCatalogue } from "./catalogue-sweep";
3
3
  import { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
4
4
  import { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from "./outbound-queue";
5
+ import { statusTable, type StatusRowStep } from "./status-store";
6
+ import type { StatusStep } from "./adapter";
5
7
  import type { EngineContext } from "./ports";
6
8
 
7
9
  /**
@@ -67,20 +69,30 @@ interface OwedRow {
67
69
  clientId: string;
68
70
  orderId: string;
69
71
  provider: string;
72
+ /** Only a status row has one. */
73
+ step?: StatusRowStep;
74
+ /** Only a status row has one: the claim the sweep takes over. */
75
+ claimKey?: string;
70
76
  }
71
77
 
72
78
  const OWED_SELECT = { clientId: true, orderId: true, provider: true } as const;
73
79
 
74
80
  /** The sweep's own dedupe key: distinct from the job's, and per pass. */
75
- function sweepDedupeKey(action: OutboundAction, orderId: string, now: Date): string {
76
- return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;
81
+ function sweepDedupeKey(action: OutboundAction, orderId: string, now: Date, step?: string): string {
82
+ return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${step ? `${step}:` : ""}${orderId}:sweep:${now.getTime()}`;
77
83
  }
78
84
 
79
85
  async function requeue(ctx: EngineContext, rows: readonly OwedRow[], action: OutboundAction, now: Date): Promise<number> {
80
86
  let queued = 0;
81
87
  for (const row of rows) {
82
- const payload = { clientId: row.clientId, orderId: row.orderId, action };
83
- if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;
88
+ const payload = {
89
+ clientId: row.clientId,
90
+ orderId: row.orderId,
91
+ action,
92
+ ...(row.step ? { step: row.step as StatusStep } : {}),
93
+ ...(row.claimKey === undefined ? {} : { claimKey: row.claimKey }),
94
+ };
95
+ if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now, row.step))) queued += 1;
84
96
  }
85
97
  return queued;
86
98
  }
@@ -137,6 +149,37 @@ async function expireUnanswered(ctx: EngineContext, now: Date): Promise<number>
137
149
  return expired;
138
150
  }
139
151
 
152
+ /**
153
+ * The status calls a dead job left SENDING (FUT-4653): re-queued once older
154
+ * than the job's retry span, failed once older than the give-up (a marketplace
155
+ * has long settled the order). Returns how many it re-queued and gave up on.
156
+ */
157
+ async function sweepStatus(ctx: EngineContext, now: Date): Promise<{ requeued: number; givenUp: number }> {
158
+ const table = statusTable(await ctx.ports.db());
159
+ if (!table) return { requeued: 0, givenUp: 0 };
160
+ const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
161
+ const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
162
+ const givenUp = (await table.updateMany({ where: { state: "SENDING", updatedAt: { lt: giveUp } }, data: { state: "FAILED" } })).count;
163
+ if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} status call(s).`);
164
+ const owed = (await table.findMany({
165
+ where: { state: "SENDING", source: "STORE", updatedAt: { lt: stale, gte: giveUp } },
166
+ select: { clientId: true, orderId: true, provider: true, step: true, claimKey: true },
167
+ })) as OwedRow[];
168
+ // The stale claim is TAKEN OVER under a fresh key, predicated on the old one, before the job
169
+ // is queued under the new: a job still alive under the old key can then settle or fail
170
+ // nothing, and a second sweep pass finds nothing to take.
171
+ const claimed: OwedRow[] = [];
172
+ for (const row of owed) {
173
+ const fresh = `sweep:${now.getTime()}`;
174
+ const taken = await table.updateMany({
175
+ where: { orderId: row.orderId, step: row.step, state: "SENDING", claimKey: row.claimKey, updatedAt: { lt: stale } },
176
+ data: { claimKey: fresh },
177
+ });
178
+ if (taken.count > 0) claimed.push({ ...row, claimKey: fresh });
179
+ }
180
+ return { requeued: await requeue(ctx, claimed, "status", now), givenUp };
181
+ }
182
+
140
183
  /**
141
184
  * One sweep pass: expire the requests nobody answered, give up on the very old,
142
185
  * and re-queue what is still owed, the catalogue's publishes and withdraws
@@ -170,5 +213,6 @@ export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<Outb
170
213
  (await requeue(ctx, cancellations, "requestCancellation", now)) + (await requeue(ctx, confirms, "confirm", now));
171
214
  if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
172
215
  const catalogueRequeued = await sweepCatalogue(ctx, now);
173
- return { requeued, givenUp, timedOut, catalogueRequeued };
216
+ const status = await sweepStatus(ctx, now);
217
+ return { requeued: requeued + status.requeued, givenUp: givenUp + status.givenUp, timedOut, catalogueRequeued };
174
218
  }
@@ -9,8 +9,9 @@ import {
9
9
  } from "./cancellation-outcome";
10
10
  import { readOutboundConnection, type OutboundConnection } from "./integration";
11
11
  import type { OutboundJobPayload } from "./outbound-queue";
12
+ import { failStatusRow, runStatus } from "./status-job";
12
13
  import { failAsTimeout } from "./outbound-sweep";
13
- import type { EngineContext } from "./ports";
14
+ import type { CancellationFailureReason, EngineContext } from "./ports";
14
15
  import { resolveReason } from "./registry";
15
16
 
16
17
  /**
@@ -62,6 +63,7 @@ interface OutboundRow {
62
63
  status: string;
63
64
  confirmedAt: Date | null;
64
65
  confirmFailedAt: Date | null;
66
+ deliveredBy: string | null;
65
67
  cancellationStatus: string | null;
66
68
  cancellationReasonCode: string | null;
67
69
  cancellationOffendingSkus: unknown;
@@ -78,6 +80,7 @@ const ROW_SELECT = {
78
80
  status: true,
79
81
  confirmedAt: true,
80
82
  confirmFailedAt: true,
83
+ deliveredBy: true,
81
84
  cancellationStatus: true,
82
85
  cancellationReasonCode: true,
83
86
  cancellationOffendingSkus: true,
@@ -133,15 +136,16 @@ async function stampCancellation(
133
136
  row: OutboundRow,
134
137
  status: "REQUESTED" | "CONFIRMED" | "FAILED",
135
138
  clientId: string,
139
+ failure: CancellationFailureReason = "REFUSED",
136
140
  ): Promise<void> {
137
141
  if (status === "CONFIRMED") return stampConfirmedCancellation(ctx, row, clientId);
138
142
  const db = await ctx.ports.db();
139
- const data = status === "FAILED" ? failedRequestData("REFUSED") : { cancellationStatus: status };
143
+ const data = status === "FAILED" ? failedRequestData(failure) : { cancellationStatus: status };
140
144
  const moved = await db.marketplaceAcceptance.updateMany({
141
145
  where: { orderId: row.orderId, cancellationStatus: "PENDING" },
142
146
  data,
143
147
  });
144
- if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
148
+ if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, failure);
145
149
  }
146
150
 
147
151
  /**
@@ -218,7 +222,7 @@ async function settle(
218
222
  result: OutboundResult,
219
223
  attempt: OutboundAttempt,
220
224
  succeed: () => Promise<void>,
221
- fail: () => Promise<void>,
225
+ fail: (reason: CancellationFailureReason) => Promise<void>,
222
226
  ): Promise<OutboundOutcome> {
223
227
  if (result.kind === "accepted") {
224
228
  await succeed();
@@ -229,7 +233,9 @@ async function settle(
229
233
  if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
230
234
  throw new OutboundRetryError(`${payload.action} for order ${row.orderId}: ${reason}`);
231
235
  }
232
- await fail();
236
+ // A refusal that is the marketplace's judgement is REFUSED; anything else (our
237
+ // own refusal, retries that ran out) never got one.
238
+ await fail(result.kind === "refused" && !result.own ? "REFUSED" : "UNREACHABLE");
233
239
  ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${row.orderId} failed: ${reason}`);
234
240
  ctx.ports.publishChanged(payload.clientId);
235
241
  return { kind: "failed", action: payload.action, reason };
@@ -248,7 +254,7 @@ async function runConfirm(
248
254
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
249
255
  const result: OutboundResult =
250
256
  typeof connection === "string"
251
- ? { kind: "refused", status: 0, message: connection }
257
+ ? { kind: "refused", status: 0, message: connection, own: true }
252
258
  : await adapter.confirm(
253
259
  { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },
254
260
  refOf(row),
@@ -299,8 +305,9 @@ async function runCancellation(
299
305
  const reason = resolveReason(adapter, row.cancellationReasonCode);
300
306
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
301
307
  let result: OutboundResult;
302
- if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's" };
303
- else if (typeof connection === "string") result = { kind: "refused", status: 0, message: connection };
308
+ // A stored reason that is not the marketplace's own was never sent: our side (UNREACHABLE).
309
+ if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's", own: true };
310
+ else if (typeof connection === "string") result = { kind: "refused", status: 0, message: connection, own: true };
304
311
  else {
305
312
  result = await adapter.requestCancellation(
306
313
  { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
@@ -316,7 +323,7 @@ async function runCancellation(
316
323
  result,
317
324
  attempt,
318
325
  () => stampCancellation(ctx, row, taken, payload.clientId),
319
- () => stampCancellation(ctx, row, "FAILED", payload.clientId),
326
+ (failure) => stampCancellation(ctx, row, "FAILED", payload.clientId, failure),
320
327
  );
321
328
  }
322
329
 
@@ -327,6 +334,11 @@ async function runCancellation(
327
334
  */
328
335
  async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {
329
336
  const reason = error instanceof Error ? error.message : String(error);
337
+ if (payload.action === "status") {
338
+ await failStatusRow(ctx, payload);
339
+ ctx.ports.logger.error(`marketplace.outbound: status ${payload.step ?? ""} for order ${payload.orderId} failed: ${reason}`);
340
+ return { kind: "failed", action: payload.action, reason };
341
+ }
330
342
  const db = await ctx.ports.db();
331
343
  const moved = await (payload.action === "confirm"
332
344
  ? db.marketplaceAcceptance.updateMany({
@@ -335,12 +347,12 @@ async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobP
335
347
  })
336
348
  : db.marketplaceAcceptance.updateMany({
337
349
  where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: "PENDING" },
338
- data: failedRequestData("REFUSED"),
350
+ data: failedRequestData("UNREACHABLE"),
339
351
  }));
340
352
  ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);
341
353
  ctx.ports.publishChanged(payload.clientId);
342
354
  if (payload.action === "requestCancellation" && moved.count > 0) {
343
- await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "REFUSED");
355
+ await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "UNREACHABLE");
344
356
  }
345
357
  return { kind: "failed", action: payload.action, reason };
346
358
  }
@@ -354,6 +366,9 @@ async function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt:
354
366
  if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
355
367
  const adapter = ctx.registry.get(row.provider);
356
368
  if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
369
+ if (payload.action === "status") {
370
+ return runStatus(ctx, payload, row, adapter, { attempt, ref: refOf(row), retryError: (m) => new OutboundRetryError(m) });
371
+ }
357
372
  return payload.action === "confirm"
358
373
  ? runConfirm(ctx, payload, row, adapter, attempt)
359
374
  : runCancellation(ctx, payload, row, adapter, attempt);
@@ -4,9 +4,10 @@ import { awaitOrderBody, merchantMismatch, requeueOwedFetch } from "./fetch-orde
4
4
  import { deferInboxEvent, recordInboxEvent, settleInboxEvent } from "./inbox";
5
5
  import { ingestMarketplaceOrder, type IngestSettings } from "./ingest";
6
6
  import { connectionMerchantId, resolveIngestionTarget } from "./integration";
7
- import { markCancelledBeforeIngest } from "./order-fetch-marks";
7
+ import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest, markCancelledBeforeIngest } from "./order-fetch-marks";
8
8
  import type { EngineContext } from "./ports";
9
- import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
9
+ import type { MarketplaceLifecycle, MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
10
+ import { followLifecycle } from "./lifecycle";
10
11
 
11
12
  /**
12
13
  * One delivery, start to finish: normalize → inbox → ingest.
@@ -34,6 +35,8 @@ export function normalizeEvent(
34
35
  /** How a delivery ended. `duplicate` and `ignored` are both ordinary outcomes. */
35
36
  export type DeliveryOutcome =
36
37
  | { kind: "ingested"; orderId: string; unmappedSkus: string[] }
38
+ /** A lifecycle event moved the order forward, through the host's `onLifecycle` (FUT-4653). */
39
+ | { kind: "moved"; orderId: string; lifecycle: MarketplaceLifecycle }
37
40
  | { kind: "cancelled" }
38
41
  | { kind: "cancellationFailed" }
39
42
  /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
@@ -160,6 +163,23 @@ async function applyEvent(
160
163
  return { kind: "awaitingOrder" };
161
164
  }
162
165
 
166
+ // A lifecycle event (dispatched, concluded) of an order we hold: with the
167
+ // connection's switch ON and a host that binds the hook, the order follows.
168
+ // Anything else falls through to "understood, nothing to do", as before.
169
+ const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
170
+ if (followed) return followed;
171
+ return ingestOrIgnore(ctx, inboxId, clientId, event, settings, now);
172
+ }
173
+
174
+ /** An event with no order body is understood and ignored; one that carries an order is ingested. */
175
+ async function ingestOrIgnore(
176
+ ctx: EngineContext,
177
+ inboxId: string,
178
+ clientId: string,
179
+ event: NormalizedEvent,
180
+ settings: IngestSettings,
181
+ now: Date | undefined,
182
+ ): Promise<DeliveryOutcome> {
163
183
  if (!event.order) {
164
184
  // An event type this ingestion does not act on. Marketplaces emit a wide
165
185
  // stream (dispatched, concluded, driver assigned…) and most of it is not an
@@ -190,7 +210,19 @@ async function ingestCarried(
190
210
  ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);
191
211
  return { kind: "failed", reason: mismatch };
192
212
  }
213
+ // A CANCELLED that found nothing to cancel left its marker (an earlier
214
+ // NEW_ORDER FAILED, so no acceptance existed). The retry sweep re-runs that
215
+ // row: ingesting it now would send a cancelled order to the kitchen.
216
+ if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {
217
+ await settleInboxEvent(ctx, inboxId, "IGNORED", CANCELLED_BEFORE_INGEST_REASON);
218
+ return { kind: "ignored", reason: CANCELLED_BEFORE_INGEST_REASON };
219
+ }
193
220
  const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });
221
+ // A CANCELLED that read the acceptances while this ingest's transaction was
222
+ // still open found none and left its marker: honour it now, through the
223
+ // ordinary cancel path (the order is cancelled; no confirm is owed).
224
+ const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };
225
+ if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);
194
226
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
195
227
  return { kind: "ingested", orderId: result.orderId, unmappedSkus: result.unmappedSkus };
196
228
  }
@@ -231,7 +263,7 @@ export async function reprocessStoredDelivery(
231
263
  input.id,
232
264
  input.clientId,
233
265
  event,
234
- { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },
266
+ { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus },
235
267
  undefined,
236
268
  );
237
269
  } catch (error) {
package/src/core/ports.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import type { AdapterRegistry } from "./registry";
2
- import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp } from "./adapter";
2
+ import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp, StatusStep } from "./adapter";
3
3
  import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
4
- import type { NormalizedMarketplaceOrder } from "./types";
4
+ import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
5
+ import type { NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
6
+
7
+ export type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
5
8
 
6
9
  /**
7
10
  * What the engine needs FROM its host, and nothing more.
@@ -81,6 +84,16 @@ export interface MarketplaceDb {
81
84
  upsert(args: unknown): Promise<unknown>;
82
85
  updateMany(args: unknown): Promise<{ count: number }>;
83
86
  };
87
+ /**
88
+ * OPTIONAL in the type, so a host on 1.x that has not yet composed the
89
+ * status model still compiles; the lifecycle and status paths do nothing
90
+ * without it (FUT-4653, migration `20261126120000_marketplace_status_updates`).
91
+ */
92
+ marketplaceStatusUpdate?: {
93
+ findMany(args: unknown): Promise<unknown[]>;
94
+ create(args: unknown): Promise<unknown>;
95
+ updateMany(args: unknown): Promise<{ count: number }>;
96
+ };
84
97
  }
85
98
 
86
99
  /**
@@ -146,11 +159,22 @@ export type MarketplaceAdmissionResult =
146
159
  export type MarketplaceRefusal = "REJECTED" | "EXPIRED" | "CANCELLED";
147
160
 
148
161
  /**
149
- * Why the store's own cancellation request FAILED: REFUSED (the marketplace
150
- * said no, or every attempt failed) or TIMEOUT (no answer inside the
151
- * marketplace's cancellation window). Vocabulary, not copy.
162
+ * Why the store's own cancellation request FAILED. Vocabulary, not copy.
163
+ *
164
+ * - `REFUSED`: the marketplace judged the request and denied it: its denial
165
+ * event, an answer that is its business refusal, or an adapter that has no
166
+ * cancellation API to call. An adapter that cannot tell a business 4xx from
167
+ * a malformed request (iFood, Rappi) reports every final 4xx as REFUSED.
168
+ * - `UNREACHABLE`: our own request never got a judgement: no credentials or
169
+ * ones that do not open, a token the marketplace did not grant, a request
170
+ * the marketplace calls malformed (99Food's 400), or every attempt failed
171
+ * on the network or a 5xx. Retrying, or fixing the connection, can help.
172
+ * - `TIMEOUT`: no answer inside the marketplace's cancellation window.
173
+ *
174
+ * A host written before `UNREACHABLE` existed treats an unknown value as it
175
+ * treats REFUSED: the order stays and a person finishes in the marketplace's app.
152
176
  */
153
- export type CancellationFailureReason = "REFUSED" | "TIMEOUT";
177
+ export type CancellationFailureReason = "REFUSED" | "UNREACHABLE" | "TIMEOUT";
154
178
 
155
179
  /**
156
180
  * The host's domain, as five questions the engine asks and never answers.
@@ -215,6 +239,29 @@ export interface MarketplaceOrderPort {
215
239
  * marketplace's: a person finishes it there, through the adapter's app link.
216
240
  */
217
241
  onCancellationFailed?(clientId: string, orderId: string, reason: CancellationFailureReason): Promise<void>;
242
+ /**
243
+ * OPTIONAL. The marketplace announced a step of an order the engine holds
244
+ * (`DISPATCHED`, `CONCLUDED`), the connection follows the marketplace's
245
+ * status, and the order is ACCEPTED with no cancellation request standing.
246
+ * Move the order FORWARD to the step if it is not there yet, and never
247
+ * otherwise: answer `unchanged` for an order already there or past it, or
248
+ * one that has no such step. Idempotent by forward-only: a hook that throws
249
+ * leaves the inbox row FAILED and the reconcile pass runs it again. Absent:
250
+ * every lifecycle event is understood and ignored, as before FUT-4653.
251
+ */
252
+ onLifecycle?(
253
+ clientId: string,
254
+ orderId: string,
255
+ event: NormalizedEvent,
256
+ facts: MarketplaceLifecycleFacts,
257
+ ): Promise<MarketplaceLifecycleAnswer>;
258
+ /**
259
+ * OPTIONAL. Does the order still hold this step: the card is at it or past
260
+ * it, not canceled or failed. Asked by the status job right before it tells
261
+ * the marketplace, so a step the store undid in the meantime is never sent.
262
+ * Absent: the engine cannot tell, and sends nothing.
263
+ */
264
+ statusHolds?(clientId: string, orderId: string, step: StatusStep): Promise<boolean>;
218
265
  /** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
219
266
  summarize(
220
267
  clientId: string,
@@ -242,7 +289,7 @@ export interface MarketplaceEnqueuePort {
242
289
  enqueue(
243
290
  name: string,
244
291
  payload: unknown,
245
- options?: { dedupeKey?: string },
292
+ options?: { dedupeKey?: string; delayMs?: number },
246
293
  ): Promise<{ enqueued: boolean; reason?: string }>;
247
294
  }
248
295
 
package/src/core/state.ts CHANGED
@@ -17,7 +17,7 @@ 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. */
20
+ /** Why the request FAILED (REFUSED, UNREACHABLE or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */
21
21
  cancellationFailure: CancellationFailureReason | null;
22
22
  /** The adapter's app link, or null when no adapter is registered for it. */
23
23
  appUrl: string | null;