@12-apps/marketplace 1.7.0 → 1.9.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 (96) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +153 -3
  3. package/dist/99food/index.d.ts +30 -52
  4. package/dist/99food/index.js +62 -391
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
  7. package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -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/chunk-PYHNM47K.js +478 -0
  16. package/dist/chunk-PYHNM47K.js.map +1 -0
  17. package/dist/client-B4EQCRD_.d.ts +20 -0
  18. package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
  19. package/dist/hono/index.d.ts +2 -2
  20. package/dist/hono/index.js +3 -3
  21. package/dist/ifood/index.d.ts +1 -1
  22. package/dist/ifood/index.js +29 -3
  23. package/dist/ifood/index.js.map +1 -1
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +104 -7
  26. package/dist/index.js.map +1 -1
  27. package/dist/keeta/en-US.d.ts +19 -0
  28. package/dist/keeta/en-US.js +23 -0
  29. package/dist/keeta/en-US.js.map +1 -0
  30. package/dist/keeta/index.d.ts +253 -0
  31. package/dist/keeta/index.js +388 -0
  32. package/dist/keeta/index.js.map +1 -0
  33. package/dist/keeta/pt-BR.d.ts +23 -0
  34. package/dist/keeta/pt-BR.js +23 -0
  35. package/dist/keeta/pt-BR.js.map +1 -0
  36. package/dist/manifest/index.d.ts +3 -0
  37. package/dist/manifest/index.js +1 -1
  38. package/dist/manifest/server.d.ts +2 -2
  39. package/dist/manifest/server.js +3 -3
  40. package/dist/rappi/index.d.ts +7 -1
  41. package/dist/rappi/index.js +20 -3
  42. package/dist/rappi/index.js.map +1 -1
  43. package/dist/server/index.d.ts +6 -2
  44. package/dist/server/index.js +3 -3
  45. package/package.json +14 -2
  46. package/prisma/marketplace.prisma +45 -1
  47. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  48. package/src/99food/catalogue.ts +19 -89
  49. package/src/99food/copy.ts +4 -19
  50. package/src/99food/index.ts +29 -28
  51. package/src/99food/normalize.ts +11 -247
  52. package/src/99food/outbound.ts +29 -215
  53. package/src/99food/pause.ts +7 -22
  54. package/src/core/adapter.ts +41 -1
  55. package/src/core/bulk.ts +1 -1
  56. package/src/core/engine.ts +9 -0
  57. package/src/core/ingest.ts +6 -0
  58. package/src/core/integration.ts +17 -0
  59. package/src/core/lifecycle-port.ts +16 -0
  60. package/src/core/lifecycle.ts +133 -0
  61. package/src/core/outbound-queue.ts +24 -4
  62. package/src/core/outbound-sweep.ts +49 -5
  63. package/src/core/outbound.ts +11 -0
  64. package/src/core/pipeline.ts +22 -2
  65. package/src/core/ports.ts +39 -3
  66. package/src/core/status-inform.ts +51 -0
  67. package/src/core/status-job.ts +207 -0
  68. package/src/core/status-store.ts +85 -0
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +7 -1
  71. package/src/ifood/normalize.ts +17 -0
  72. package/src/ifood/outbound.ts +35 -0
  73. package/src/index.ts +8 -1
  74. package/src/keeta/authorization.ts +226 -0
  75. package/src/keeta/copy.ts +27 -0
  76. package/src/keeta/en-US.ts +19 -0
  77. package/src/keeta/index.ts +162 -0
  78. package/src/keeta/merchant.ts +70 -0
  79. package/src/keeta/normalize.ts +131 -0
  80. package/src/keeta/outbound.ts +55 -0
  81. package/src/keeta/pt-BR.ts +23 -0
  82. package/src/keeta/signature.ts +85 -0
  83. package/src/open-delivery/client.ts +185 -0
  84. package/src/open-delivery/merchant.ts +126 -0
  85. package/src/open-delivery/normalize.ts +269 -0
  86. package/src/open-delivery/orders.ts +241 -0
  87. package/src/open-delivery/reasons.ts +26 -0
  88. package/src/rappi/index.ts +6 -1
  89. package/src/rappi/normalize.ts +6 -0
  90. package/src/rappi/outbound.ts +31 -2
  91. package/src/server/mcp.ts +2 -0
  92. package/src/server/webhook.ts +3 -1
  93. package/dist/chunk-L3DCOZUU.js.map +0 -1
  94. package/dist/chunk-SJUKBCVO.js.map +0 -1
  95. package/dist/chunk-UYFYGGCS.js.map +0 -1
  96. package/dist/chunk-YVUZHXUF.js.map +0 -1
@@ -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,6 +9,7 @@ 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
14
  import type { CancellationFailureReason, EngineContext } from "./ports";
14
15
  import { resolveReason } from "./registry";
@@ -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,
@@ -331,6 +334,11 @@ async function runCancellation(
331
334
  */
332
335
  async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {
333
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
+ }
334
342
  const db = await ctx.ports.db();
335
343
  const moved = await (payload.action === "confirm"
336
344
  ? db.marketplaceAcceptance.updateMany({
@@ -358,6 +366,9 @@ async function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt:
358
366
  if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
359
367
  const adapter = ctx.registry.get(row.provider);
360
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
+ }
361
372
  return payload.action === "confirm"
362
373
  ? runConfirm(ctx, payload, row, adapter, attempt)
363
374
  : runCancellation(ctx, payload, row, adapter, attempt);
@@ -6,7 +6,8 @@ import { ingestMarketplaceOrder, type IngestSettings } from "./ingest";
6
6
  import { connectionMerchantId, resolveIngestionTarget } from "./integration";
7
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
@@ -243,7 +263,7 @@ export async function reprocessStoredDelivery(
243
263
  input.id,
244
264
  input.clientId,
245
265
  event,
246
- { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },
266
+ { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus },
247
267
  undefined,
248
268
  );
249
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
  /**
@@ -226,6 +239,29 @@ export interface MarketplaceOrderPort {
226
239
  * marketplace's: a person finishes it there, through the adapter's app link.
227
240
  */
228
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>;
229
265
  /** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
230
266
  summarize(
231
267
  clientId: string,
@@ -253,7 +289,7 @@ export interface MarketplaceEnqueuePort {
253
289
  enqueue(
254
290
  name: string,
255
291
  payload: unknown,
256
- options?: { dedupeKey?: string },
292
+ options?: { dedupeKey?: string; delayMs?: number },
257
293
  ): Promise<{ enqueued: boolean; reason?: string }>;
258
294
  }
259
295
 
@@ -0,0 +1,51 @@
1
+ import type { StatusStep } from "./adapter";
2
+ import { MARKETPLACE_OUTBOUND_JOB, statusDedupeKey } from "./outbound-queue";
3
+ import type { EngineContext } from "./ports";
4
+
5
+ /** What the host says when an order reaches a step (FUT-4653). */
6
+ export interface InformStatusInput {
7
+ clientId: string;
8
+ /** The host's order id. */
9
+ orderId: string;
10
+ step: StatusStep;
11
+ /**
12
+ * The instant of the move (the card's own timestamp), which makes the job's
13
+ * key: a re-dispatch after an undo is another instant, and a queue keeps a
14
+ * finished job's id and would swallow the same key.
15
+ */
16
+ at: Date;
17
+ /** OPTIONAL. Run the job this much later: the board's undo window for a dispatch. */
18
+ delayMs?: number;
19
+ }
20
+
21
+ /**
22
+ * One enqueue and nothing else: no statement, no call to a marketplace, no
23
+ * provider lookup (the host knows the order is a marketplace's, not whose).
24
+ * The job asks the adapter whether it takes the step. A refused or throwing
25
+ * queue is logged and answers false; nothing owed is recorded, so nothing is
26
+ * re-queued (no row exists before the job, and writing one in the host's tap
27
+ * would cost a statement on every move).
28
+ */
29
+ export async function informStatus(ctx: EngineContext, input: InformStatusInput): Promise<boolean> {
30
+ const payload = { clientId: input.clientId, orderId: input.orderId, action: "status" as const, step: input.step, claimKey: String(input.at.getTime()) };
31
+ const options = {
32
+ dedupeKey: statusDedupeKey(input.step, input.orderId, input.at),
33
+ ...(input.delayMs === undefined ? {} : { delayMs: input.delayMs }),
34
+ };
35
+ try {
36
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, options);
37
+ if (!outcome.enqueued) {
38
+ ctx.ports.logger.warn(
39
+ `${MARKETPLACE_OUTBOUND_JOB}: status ${input.step} for order ${input.orderId} was not queued` +
40
+ (outcome.reason ? ` (${outcome.reason})` : ""),
41
+ );
42
+ }
43
+ return outcome.enqueued;
44
+ } catch (error) {
45
+ ctx.ports.logger.warn(
46
+ `${MARKETPLACE_OUTBOUND_JOB}: status ${input.step} for order ${input.orderId} was not queued: ` +
47
+ (error instanceof Error ? error.message : String(error)),
48
+ );
49
+ return false;
50
+ }
51
+ }
@@ -0,0 +1,207 @@
1
+ import type { MarketplaceAdapter, OutboundOrderRef, OutboundResult, StatusStep } from "./adapter";
2
+ import { readOutboundConnection, type OutboundConnection } from "./integration";
3
+ import { MARKETPLACE_OUTBOUND_JOB, type OutboundJobPayload } from "./outbound-queue";
4
+ import type { EngineContext, MarketplaceDb } from "./ports";
5
+ import { insertStatusRow, readStatusRows, settleStatusRow, statusTable, type StatusRow } from "./status-store";
6
+ import type { MarketplaceDeliveredBy } from "./types";
7
+
8
+ /**
9
+ * The status job's body (FUT-4653), `marketplace.outbound` with action
10
+ * `status`: tell the marketplace the order reached a step.
11
+ *
12
+ * In order, stopping at the first rule that fails, with no row and no call:
13
+ *
14
+ * 1. the acceptance is ACCEPTED and no cancellation request stands;
15
+ * 2. the adapter states the step and takes it for this kind of order;
16
+ * 3. the host says the order still holds the step (a dispatch undone inside
17
+ * the board's undo window sends nothing);
18
+ * 4. no row exists for (order, step), and the marketplace has not CONCLUDED
19
+ * the order (a step it announced itself is in the same table);
20
+ * 5. claim: insert the row (STORE, SENDING), unique on (order, step); a lost
21
+ * claim stops the run;
22
+ * 6. call the adapter: 2xx SENT; a final 4xx FAILED, logged at error, never
23
+ * retried; 408/425/429/5xx/timeout retried, the last attempt FAILED. A run
24
+ * on a SENDING row it owns (a retry, or the sweep's re-queue) calls again.
25
+ *
26
+ * Nothing here touches the order: a failed, refused or lost status call
27
+ * changes nothing in the host.
28
+ */
29
+
30
+ /** What the job reads of the acceptance row. */
31
+ interface StatusJobRow {
32
+ orderId: string;
33
+ provider: string;
34
+ status: string;
35
+ cancellationStatus: string | null;
36
+ deliveredBy: string | null;
37
+ }
38
+
39
+ /** What one run did, in the outbound job's own shape. */
40
+ type StatusJobOutcome =
41
+ | { kind: "skipped"; reason: string }
42
+ | { kind: "done"; action: "status" }
43
+ | { kind: "failed"; action: "status"; reason: string };
44
+
45
+ interface StatusJobDeps {
46
+ attempt: { attempt: number; maxAttempts: number };
47
+ ref: OutboundOrderRef;
48
+ retryError: (message: string) => Error;
49
+ }
50
+
51
+ function deliveredByOf(row: StatusJobRow): MarketplaceDeliveredBy | null {
52
+ return row.deliveredBy === "MERCHANT" || row.deliveredBy === "MARKETPLACE" ? row.deliveredBy : null;
53
+ }
54
+
55
+ const skipped = (reason: string): StatusJobOutcome => ({ kind: "skipped", reason });
56
+
57
+ /** Why rule 1 stops the job, or null. */
58
+ function acceptanceSkip(row: StatusJobRow): string | null {
59
+ if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
60
+ const standing = row.cancellationStatus !== null && row.cancellationStatus !== "FAILED";
61
+ return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
62
+ }
63
+
64
+ /** Why rules 2 and 3 stop the job, or null. Rule 3 asks the host, so it comes last. */
65
+ async function adapterAndHostSkip(
66
+ ctx: EngineContext,
67
+ payload: OutboundJobPayload,
68
+ step: StatusStep,
69
+ row: StatusJobRow,
70
+ adapter: MarketplaceAdapter,
71
+ ): Promise<string | null> {
72
+ const takes =
73
+ adapter.informStatus !== undefined &&
74
+ adapter.capabilities.statusSteps?.includes(step) === true &&
75
+ adapter.statusSupported?.({ step, deliveredBy: deliveredByOf(row) }) !== false;
76
+ if (!takes) return `the marketplace does not take ${step} for this order`;
77
+ const holds = ctx.ports.order.statusHolds;
78
+ if (!holds) return "the host binds no statusHolds, so it cannot say the order still holds the step";
79
+ return (await holds.call(ctx.ports.order, payload.clientId, row.orderId, step)) ? null : `the order no longer holds ${step}`;
80
+ }
81
+
82
+ /** The opened connection, or why the store has none (disconnected, no secrets, secrets that do not open). */
83
+ async function connectionOf(ctx: EngineContext, clientId: string, provider: string): Promise<OutboundConnection | string> {
84
+ try {
85
+ return (await readOutboundConnection(ctx, clientId, provider)) ?? "no credentials on file";
86
+ } catch (error) {
87
+ return `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
88
+ }
89
+ }
90
+
91
+ /** Call the adapter with the opened connection. */
92
+ function callAdapter(
93
+ ctx: EngineContext,
94
+ connection: OutboundConnection,
95
+ adapter: MarketplaceAdapter,
96
+ row: StatusJobRow,
97
+ step: StatusStep,
98
+ ref: OutboundOrderRef,
99
+ ): Promise<OutboundResult | { kind: "unsupported" }> {
100
+ const now = ctx.ports.clock.now();
101
+ return adapter.informStatus!({ http: ctx.ports.http, tokens: ctx.tokens, now, ...connection }, ref, {
102
+ step,
103
+ deliveredBy: deliveredByOf(row),
104
+ });
105
+ }
106
+
107
+ /** Stamp the answer; a retry throws until the last attempt. */
108
+ async function settle(
109
+ ctx: EngineContext,
110
+ db: MarketplaceDb,
111
+ where: { orderId: string; step: StatusStep; claimKey: string },
112
+ result: OutboundResult | { kind: "unsupported" },
113
+ deps: StatusJobDeps,
114
+ ): Promise<StatusJobOutcome> {
115
+ const table = statusTable(db)!;
116
+ if (result.kind === "accepted") {
117
+ await settleStatusRow(table, where, "SENT");
118
+ return { kind: "done", action: "status" };
119
+ }
120
+ const reason =
121
+ result.kind === "refused"
122
+ ? `refused ${result.status}: ${result.message}`
123
+ : result.kind === "retry"
124
+ ? result.reason
125
+ : "the adapter answered unsupported after the claim";
126
+ if (result.kind === "retry" && deps.attempt.attempt < deps.attempt.maxAttempts) {
127
+ throw deps.retryError(`status ${where.step} for order ${where.orderId}: ${reason}`);
128
+ }
129
+ await settleStatusRow(table, where, "FAILED");
130
+ ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: status ${where.step} for order ${where.orderId} failed: ${reason}`);
131
+ return { kind: "failed", action: "status", reason };
132
+ }
133
+
134
+ /** Whether a row is a SENDING claim of the run holding `key`. */
135
+ function ownsClaim(found: StatusRow, key: string): boolean {
136
+ return found.source === "STORE" && found.state === "SENDING" && found.claimKey === key;
137
+ }
138
+
139
+ /**
140
+ * Rules 4 and 5: why the step is not ours to send (a row stands, or the
141
+ * marketplace concluded, or the claim was lost), or null once the row is ours.
142
+ */
143
+ async function claim(
144
+ table: NonNullable<MarketplaceDb["marketplaceStatusUpdate"]>,
145
+ payload: OutboundJobPayload,
146
+ row: StatusJobRow,
147
+ step: StatusStep,
148
+ key: string,
149
+ ): Promise<string | null> {
150
+ const rows = await readStatusRows(table, row.orderId, [step, "CONCLUDED"]);
151
+ if (rows.some((found) => found.step === "CONCLUDED" && found.source === "MARKETPLACE")) {
152
+ return "the marketplace concluded this order";
153
+ }
154
+ const own = rows.find((found) => found.step === step);
155
+ // A SENDING row under THIS job's key is its own retry (or the sweep's re-claim of it): it
156
+ // calls again. Under any other key another move's job holds it, and sends nothing.
157
+ if (own) return ownsClaim(own, key) ? null : `${step} is already ${own.state}${own.state === "SENDING" ? ", held by another run" : ""}`;
158
+ const claimed = await insertStatusRow(table, {
159
+ clientId: payload.clientId,
160
+ orderId: row.orderId,
161
+ provider: row.provider,
162
+ step,
163
+ source: "STORE",
164
+ state: "SENDING",
165
+ claimKey: key,
166
+ });
167
+ return claimed ? null : `another run holds the claim on ${step}`;
168
+ }
169
+
170
+ /** Run one status job. `row` is the acceptance the outbound job already read. */
171
+ export async function runStatus(
172
+ ctx: EngineContext,
173
+ payload: OutboundJobPayload,
174
+ row: StatusJobRow,
175
+ adapter: MarketplaceAdapter,
176
+ deps: StatusJobDeps,
177
+ ): Promise<StatusJobOutcome> {
178
+ const step = payload.step;
179
+ if (!step) return skipped("a status call names no step");
180
+ const stopped = acceptanceSkip(row) ?? (await adapterAndHostSkip(ctx, payload, step, row, adapter));
181
+ if (stopped) return skipped(stopped);
182
+ const db = await ctx.ports.db();
183
+ const table = statusTable(db);
184
+ if (!table) return skipped("the host has not composed the status model");
185
+
186
+ // A store with no connection, or secrets that do not open, is not a failure of this step: it
187
+ // is asked before the claim so no row is left behind, and said at info (a disconnected store
188
+ // would otherwise log an error on every move).
189
+ const connection = await connectionOf(ctx, payload.clientId, row.provider);
190
+ if (typeof connection === "string") {
191
+ ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: status ${step} for order ${row.orderId} not sent: ${connection}`);
192
+ return skipped(connection);
193
+ }
194
+ const key = payload.claimKey ?? "";
195
+ const unclaimed = await claim(table, payload, row, step, key);
196
+ if (unclaimed) return skipped(unclaimed);
197
+ const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
198
+ return settle(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
199
+ }
200
+
201
+ /** The last attempt died without an answer: FAILED, never left SENDING. Best-effort. */
202
+ export async function failStatusRow(ctx: EngineContext, payload: OutboundJobPayload): Promise<void> {
203
+ const table = statusTable(await ctx.ports.db());
204
+ if (table && payload.step) {
205
+ await settleStatusRow(table, { orderId: payload.orderId, step: payload.step, claimKey: payload.claimKey ?? "" }, "FAILED");
206
+ }
207
+ }
@@ -0,0 +1,85 @@
1
+ import type { StatusStep } from "./adapter";
2
+ import type { EngineContext, MarketplaceDb } from "./ports";
3
+ import type { MarketplaceLifecycle } from "./types";
4
+
5
+ /**
6
+ * The engine's memory of what was said about an order's steps, in
7
+ * `marketplace_status_updates` (FUT-4653): one row per (order, step), so the
8
+ * same row is the claim that keeps a step from being sent twice, the marker an
9
+ * inbound echo is recognised by, and the note of what the marketplace itself
10
+ * announced. Every function here is a statement or two, never a call out.
11
+ */
12
+
13
+ /** A step as the table holds it: the three the store informs, and the one only a marketplace announces. */
14
+ export type StatusRowStep = StatusStep | MarketplaceLifecycle;
15
+
16
+ /** Where a row stands. */
17
+ export type StatusRowState = "SENDING" | "SENT" | "FAILED" | "NOTED";
18
+
19
+ /** One row, as the engine reads it. */
20
+ export interface StatusRow {
21
+ orderId: string;
22
+ step: StatusRowStep;
23
+ source: "STORE" | "MARKETPLACE";
24
+ state: StatusRowState;
25
+ /** Which run holds a SENDING claim. */
26
+ claimKey: string;
27
+ }
28
+
29
+ type StatusTable = NonNullable<MarketplaceDb["marketplaceStatusUpdate"]>;
30
+
31
+ /** The status delegate, or null on a host that has not composed the model: the paths that need it then do nothing. */
32
+ export function statusTable(db: MarketplaceDb): StatusTable | null {
33
+ return db.marketplaceStatusUpdate ?? null;
34
+ }
35
+
36
+ /** Every row of an order for these steps, in one read. */
37
+ export async function readStatusRows(
38
+ table: StatusTable,
39
+ orderId: string,
40
+ steps: readonly StatusRowStep[],
41
+ ): Promise<StatusRow[]> {
42
+ return (await table.findMany({
43
+ where: { orderId, step: { in: [...steps] } },
44
+ select: { orderId: true, step: true, source: true, state: true, claimKey: true },
45
+ })) as StatusRow[];
46
+ }
47
+
48
+ /**
49
+ * Insert one row. False when the (order, step) row already exists: the unique
50
+ * is the guard and losing it is an answer, not a failure.
51
+ */
52
+ export async function insertStatusRow(
53
+ table: StatusTable,
54
+ row: { clientId: string; orderId: string; provider: string; step: StatusRowStep; source: StatusRow["source"]; state: StatusRowState; claimKey: string },
55
+ ): Promise<boolean> {
56
+ try {
57
+ await table.create({ data: row });
58
+ return true;
59
+ } catch (error) {
60
+ if ((error as { code?: string }).code === "P2002") return false;
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ /** Remember a step the marketplace announced, so our own job never informs it back. */
66
+ export async function noteMarketplaceStep(
67
+ ctx: EngineContext,
68
+ row: { clientId: string; orderId: string; provider: string; step: MarketplaceLifecycle },
69
+ ): Promise<void> {
70
+ const table = statusTable(await ctx.ports.db());
71
+ if (table) await insertStatusRow(table, { ...row, source: "MARKETPLACE", state: "NOTED", claimKey: "" });
72
+ }
73
+
74
+ /**
75
+ * Move a row this run owns from SENDING to its answer; predicated on the state
76
+ * AND the run's claim key, so a settled row is never rewritten and a row
77
+ * another run holds is never settled by this one.
78
+ */
79
+ export async function settleStatusRow(
80
+ table: StatusTable,
81
+ where: { orderId: string; step: StatusRowStep; claimKey: string },
82
+ state: "SENT" | "FAILED",
83
+ ): Promise<number> {
84
+ return (await table.updateMany({ where: { ...where, state: "SENDING" }, data: { state } })).count;
85
+ }