@12-apps/marketplace 1.2.0 → 1.4.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 (69) hide show
  1. package/ADOPTING.md +76 -4
  2. package/README.md +163 -3
  3. package/dist/99food/index.d.ts +79 -2
  4. package/dist/99food/index.js +117 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/adapter-B8QtQ2RA.d.ts +612 -0
  7. package/dist/{chunk-CRYFYDQ2.js → chunk-DPCZVN2C.js} +69 -5
  8. package/dist/chunk-DPCZVN2C.js.map +1 -0
  9. package/dist/{chunk-D2X7TOR6.js → chunk-EBAIZQPB.js} +841 -86
  10. package/dist/chunk-EBAIZQPB.js.map +1 -0
  11. package/dist/chunk-M2V4RFMA.js +23 -0
  12. package/dist/chunk-M2V4RFMA.js.map +1 -0
  13. package/dist/{chunk-24RQZPSV.js → chunk-SZRZTLVU.js} +1 -1
  14. package/dist/chunk-SZRZTLVU.js.map +1 -0
  15. package/dist/{engine-D-a4mttc.d.ts → engine-o5cm54vC.d.ts} +462 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +22 -2
  19. package/dist/ifood/index.js +396 -56
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +30 -4
  22. package/dist/index.js +445 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +5 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +15 -2
  27. package/dist/rappi/index.js +62 -2
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +25 -10
  30. package/dist/server/index.js +4 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +158 -1
  33. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  34. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  35. package/src/99food/catalogue.ts +117 -0
  36. package/src/99food/index.ts +14 -0
  37. package/src/99food/outbound.ts +3 -3
  38. package/src/99food/pause.ts +56 -0
  39. package/src/core/adapter.ts +20 -1
  40. package/src/core/catalogue-category.ts +119 -0
  41. package/src/core/catalogue-ids.ts +23 -0
  42. package/src/core/catalogue-job.ts +332 -0
  43. package/src/core/catalogue-port.ts +173 -0
  44. package/src/core/catalogue-store.ts +172 -0
  45. package/src/core/catalogue-sweep.ts +43 -0
  46. package/src/core/catalogue.ts +226 -0
  47. package/src/core/engine.ts +83 -0
  48. package/src/core/outbound-sweep.ts +7 -2
  49. package/src/core/pause-job.ts +381 -0
  50. package/src/core/pause-port.ts +110 -0
  51. package/src/core/pause-retired.ts +139 -0
  52. package/src/core/pause-store.ts +151 -0
  53. package/src/core/pause-sweep.ts +148 -0
  54. package/src/core/pause.ts +316 -0
  55. package/src/core/ports.ts +47 -0
  56. package/src/ifood/catalogue.ts +273 -0
  57. package/src/ifood/index.ts +8 -0
  58. package/src/ifood/outbound.ts +9 -6
  59. package/src/ifood/pause.ts +257 -0
  60. package/src/index.ts +64 -0
  61. package/src/rappi/index.ts +17 -0
  62. package/src/rappi/outbound.ts +2 -2
  63. package/src/rappi/pause.ts +98 -0
  64. package/src/server/index.ts +1 -0
  65. package/src/server/jobs.ts +100 -10
  66. package/dist/adapter-_iuSxvVD.d.ts +0 -319
  67. package/dist/chunk-24RQZPSV.js.map +0 -1
  68. package/dist/chunk-CRYFYDQ2.js.map +0 -1
  69. package/dist/chunk-D2X7TOR6.js.map +0 -1
@@ -0,0 +1,151 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ import type { EngineContext, MarketplaceDb } from "./ports";
4
+ import type { MarketplaceProvider } from "./types";
5
+
6
+ /**
7
+ * The pause record: one row per (store, marketplace), the engine's memory of
8
+ * what it asked the marketplace and what the marketplace holds (FUT-4851).
9
+ *
10
+ * Two fields say two different things, and the job reconciles them:
11
+ *
12
+ * - `wanted` is the host's LAST ask (PAUSED or OPEN). The last ask wins: a
13
+ * resume that lands while a pause is in flight, or a pause while a resume
14
+ * is, only rewrites `wanted`, and the job re-reads it after every call.
15
+ * - `state` is where the marketplace stands as far as the engine knows:
16
+ * OPEN → PAUSING → PAUSED → RESUMING → OPEN, or FAILED with a code.
17
+ *
18
+ * What the engine holds on the marketplace is `externalId` (the closure's id,
19
+ * for an `interruption`), `sentUntil` (the end the marketplace was given; the
20
+ * only proof of a `switch` the engine turned off) and `attemptKey` with
21
+ * `attemptUntil` (the key a create goes out under, written BEFORE the call,
22
+ * and the end it carried, kept while its answer is in doubt).
23
+ * `retiredExternalIds` are the closures a renewal replaced, still to be
24
+ * deleted. Nothing else is ever deleted: a closure the owner made by hand is
25
+ * in none of them.
26
+ */
27
+
28
+ /** Where the marketplace stands, as far as the engine knows. Vocabulary, not copy. */
29
+ export type StorePauseState = "OPEN" | "PAUSING" | "PAUSED" | "RESUMING" | "FAILED";
30
+
31
+ /** The host's last ask. */
32
+ export type StorePauseWanted = "PAUSED" | "OPEN";
33
+
34
+ /**
35
+ * Why a record is FAILED. Machine codes, never a sentence: the host renders
36
+ * them, and the marketplace's own words travel in `failureDetail`.
37
+ *
38
+ * - `UNSUPPORTED`: the marketplace's adapter has no availability capability.
39
+ * - `NOT_CONNECTED`: no credentials or no merchant id on the connection.
40
+ * - `PAUSE_REFUSED` / `RESUME_REFUSED`: the marketplace said no (a final 4xx).
41
+ * - `PAUSE_UNANSWERED` / `RESUME_UNANSWERED`: every attempt failed without an
42
+ * answer (5xx, a timeout, a rate limit), or the sweep gave up waiting.
43
+ */
44
+ export type StorePauseFailureCode =
45
+ | "UNSUPPORTED"
46
+ | "NOT_CONNECTED"
47
+ | "PAUSE_REFUSED"
48
+ | "PAUSE_UNANSWERED"
49
+ | "RESUME_REFUSED"
50
+ | "RESUME_UNANSWERED";
51
+
52
+ /** One record as the engine reads it. */
53
+ export interface StorePauseRow {
54
+ id: string;
55
+ clientId: string;
56
+ provider: string;
57
+ state: StorePauseState;
58
+ wanted: StorePauseWanted;
59
+ until: Date | null;
60
+ reason: string | null;
61
+ timeZone: string | null;
62
+ externalId: string | null;
63
+ sentUntil: Date | null;
64
+ attemptKey: string | null;
65
+ attemptUntil: Date | null;
66
+ /** The replaced closures still to delete, oldest first (`./pause-retired.ts` reads and writes it); null when none. */
67
+ retiredExternalIds: string | null;
68
+ failureCode: StorePauseFailureCode | null;
69
+ failureDetail: string | null;
70
+ requestedAt: Date;
71
+ leaseUntil: Date | null;
72
+ pausedAt: Date | null;
73
+ resumedAt: Date | null;
74
+ failedAt: Date | null;
75
+ updatedAt: Date | null;
76
+ }
77
+
78
+ /** The job's wire name. */
79
+ export const MARKETPLACE_AVAILABILITY_JOB = "marketplace.availability";
80
+
81
+ /** The job's payload: identifiers only; the ask lives on the row. */
82
+ export interface AvailabilityJobPayload {
83
+ clientId: string;
84
+ provider: MarketplaceProvider;
85
+ }
86
+
87
+ /** How long one run holds a record, so two runs never call the marketplace for it at once. */
88
+ export const STORE_PAUSE_LEASE_MS = 2 * 60_000;
89
+
90
+ /** The marketplace's words are kept to this length: a column a person reads in a list. */
91
+ const DETAIL_MAX = 300;
92
+
93
+ /** The pause delegate, or a clear refusal on a host that has not composed the model. */
94
+ export function pauseTable(db: MarketplaceDb): NonNullable<MarketplaceDb["marketplaceStorePause"]> {
95
+ const table = db.marketplaceStorePause;
96
+ if (!table) {
97
+ throw new Error(
98
+ "@12-apps/marketplace: the store pause needs the MarketplaceStorePause model " +
99
+ "(migration 20261113230000_marketplace_store_pause); compose the partial and migrate.",
100
+ );
101
+ }
102
+ return table;
103
+ }
104
+
105
+ /** Whether a host's database has the pause model at all. */
106
+ export function hasPauseTable(db: MarketplaceDb): boolean {
107
+ return db.marketplaceStorePause !== undefined;
108
+ }
109
+
110
+ /** One record by (store, marketplace). */
111
+ export async function readPause(ctx: EngineContext, clientId: string, provider: string): Promise<StorePauseRow | null> {
112
+ const table = pauseTable(await ctx.ports.db());
113
+ return (await table.findFirst({ where: { clientId, provider } })) as StorePauseRow | null;
114
+ }
115
+
116
+ /** Whether anything of ours may stand on the marketplace for this record. */
117
+ export function holdsSomething(row: Pick<StorePauseRow, "externalId" | "sentUntil" | "attemptKey" | "retiredExternalIds">): boolean {
118
+ const retired = row.retiredExternalIds !== null && row.retiredExternalIds.trim() !== "";
119
+ return row.externalId !== null || row.sentUntil !== null || row.attemptKey !== null || retired;
120
+ }
121
+
122
+ /** A fresh key for one closure's create. */
123
+ export function newAttemptKey(): string {
124
+ return randomUUID();
125
+ }
126
+
127
+ /** The marketplace's words, cut for the column. */
128
+ export function detailOf(message: string): string {
129
+ return message.slice(0, DETAIL_MAX);
130
+ }
131
+
132
+ /** The dedupe key of one ask: per record and per ask instant, so a new ask is never swallowed. */
133
+ export function availabilityDedupeKey(payload: AvailabilityJobPayload, requestedAt: Date, suffix = ""): string {
134
+ return `${MARKETPLACE_AVAILABILITY_JOB}:${payload.clientId}:${payload.provider}:${requestedAt.getTime()}${suffix}`;
135
+ }
136
+
137
+ /** Queue the job for one record. The queue port never throws; a refusal is left to the sweep. */
138
+ export async function enqueueAvailability(
139
+ ctx: EngineContext,
140
+ payload: AvailabilityJobPayload,
141
+ dedupeKey: string,
142
+ ): Promise<boolean> {
143
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_AVAILABILITY_JOB, payload, { dedupeKey });
144
+ if (!outcome.enqueued) {
145
+ ctx.ports.logger.warn(
146
+ `${MARKETPLACE_AVAILABILITY_JOB}: ${payload.provider} for ${payload.clientId} was not queued; the sweep will re-queue it` +
147
+ (outcome.reason ? ` (${outcome.reason})` : ""),
148
+ );
149
+ }
150
+ return outcome.enqueued;
151
+ }
@@ -0,0 +1,148 @@
1
+ import { OUTBOUND_GIVE_UP_MS, OUTBOUND_STALE_MS } from "./outbound-sweep";
2
+ import {
3
+ availabilityDedupeKey,
4
+ enqueueAvailability,
5
+ hasPauseTable,
6
+ holdsSomething,
7
+ pauseTable,
8
+ type StorePauseRow,
9
+ } from "./pause-store";
10
+ import type { EngineContext } from "./ports";
11
+
12
+ /**
13
+ * The availability sweep (`marketplace.availability-sweep`, every five
14
+ * minutes): nothing the engine owes a marketplace for a store's pause is lost,
15
+ * and no store stays closed past the kitchen's pause (FUT-4851).
16
+ *
17
+ * - **Expired**: a pause whose `until` has passed without a renewal is over.
18
+ * The host stopped renewing (it died, or forgot to resume), so the engine
19
+ * resumes on its own: the owner's "never closed on a marketplace longer than
20
+ * the kitchen's own pause". An interruption has already ended on the
21
+ * marketplace (its delete answers "gone", which is done); a switch would
22
+ * otherwise stay off for good.
23
+ * - **Stale**: an ask still PAUSING or RESUMING after the job's own retry span
24
+ * (a refused enqueue, a dead process) is re-queued; past
25
+ * {@link OUTBOUND_GIVE_UP_MS} it is FAILED as unanswered.
26
+ * - **A failed resume that still holds something** is retried each pass until
27
+ * the give-up: a store must not stay closed because one delete failed.
28
+ * - **A replaced closure** an extend could not delete is retried.
29
+ * - **An OPEN record that still holds something** (a pause call whose answer
30
+ * was lost after a resume landed) goes back to RESUMING and is re-queued.
31
+ *
32
+ * Re-queued under a key of its own per pass, as the outbound sweep does. The
33
+ * job is idempotent by the row and leased, so a duplicate run calls nobody
34
+ * twice.
35
+ */
36
+
37
+ /** What one pass did. */
38
+ export interface AvailabilitySweepResult {
39
+ /** Pauses past their `until`, turned into resumes. */
40
+ expired: number;
41
+ /** Asks re-queued. */
42
+ requeued: number;
43
+ /** Asks failed as unanswered past the give-up. */
44
+ givenUp: number;
45
+ }
46
+
47
+ const sweepKey = (row: StorePauseRow, now: Date): string =>
48
+ availabilityDedupeKey({ clientId: row.clientId, provider: row.provider }, row.requestedAt, `:sweep:${now.getTime()}`);
49
+
50
+ async function requeue(ctx: EngineContext, rows: readonly StorePauseRow[], now: Date): Promise<number> {
51
+ let queued = 0;
52
+ for (const row of rows) {
53
+ if (await enqueueAvailability(ctx, { clientId: row.clientId, provider: row.provider }, sweepKey(row, now))) queued += 1;
54
+ }
55
+ return queued;
56
+ }
57
+
58
+ /** Pauses past their end: resume them, predicated on nobody having renewed meanwhile. */
59
+ async function expire(ctx: EngineContext, now: Date): Promise<number> {
60
+ const table = pauseTable(await ctx.ports.db());
61
+ const rows = (await table.findMany({
62
+ where: { wanted: "PAUSED", state: { in: ["PAUSING", "PAUSED", "FAILED"] }, until: { lt: now } },
63
+ })) as StorePauseRow[];
64
+ let expired = 0;
65
+ for (const row of rows) {
66
+ const held = holdsSomething(row);
67
+ const moved = await table.updateMany({
68
+ where: { id: row.id, wanted: "PAUSED", until: row.until },
69
+ data: { wanted: "OPEN", state: held ? "RESUMING" : "OPEN", requestedAt: now, failureCode: null, failureDetail: null, failedAt: null },
70
+ });
71
+ if (moved.count === 0) continue;
72
+ expired += 1;
73
+ ctx.ports.publishChanged(row.clientId);
74
+ if (held) await requeue(ctx, [{ ...row, requestedAt: now }], now);
75
+ }
76
+ return expired;
77
+ }
78
+
79
+ /** Asks waiting past the give-up: FAILED as unanswered. */
80
+ async function giveUp(ctx: EngineContext, cutoff: Date, now: Date): Promise<number> {
81
+ const table = pauseTable(await ctx.ports.db());
82
+ let failed = 0;
83
+ for (const [state, code] of [["PAUSING", "PAUSE_UNANSWERED"], ["RESUMING", "RESUME_UNANSWERED"]] as const) {
84
+ const moved = await table.updateMany({
85
+ where: { state, requestedAt: { lt: cutoff } },
86
+ data: { state: "FAILED", failureCode: code, failureDetail: null, failedAt: now },
87
+ });
88
+ failed += moved.count;
89
+ }
90
+ return failed;
91
+ }
92
+
93
+ /** A failed resume that still holds something, failed for a while and asked inside the give-up: back to RESUMING. */
94
+ async function retryFailedResumes(ctx: EngineContext, stale: Date, cutoff: Date): Promise<StorePauseRow[]> {
95
+ const table = pauseTable(await ctx.ports.db());
96
+ const rows = (await table.findMany({
97
+ where: { state: "FAILED", wanted: "OPEN", failedAt: { lt: stale }, requestedAt: { gte: cutoff } },
98
+ })) as StorePauseRow[];
99
+ const retried: StorePauseRow[] = [];
100
+ for (const row of rows.filter(holdsSomething)) {
101
+ const moved = await table.updateMany({ where: { id: row.id, state: "FAILED", wanted: "OPEN" }, data: { state: "RESUMING" } });
102
+ if (moved.count > 0) retried.push(row);
103
+ }
104
+ return retried;
105
+ }
106
+
107
+ /**
108
+ * An OPEN record that still holds something (a call whose answer was lost
109
+ * after a resume landed): back to RESUMING, so the job deletes it.
110
+ */
111
+ async function reopenOrphans(ctx: EngineContext, stale: Date): Promise<StorePauseRow[]> {
112
+ const table = pauseTable(await ctx.ports.db());
113
+ const rows = (await table.findMany({
114
+ where: {
115
+ state: "OPEN",
116
+ wanted: "OPEN",
117
+ requestedAt: { lt: stale },
118
+ OR: [{ attemptKey: { not: null } }, { externalId: { not: null } }, { sentUntil: { not: null } }, { retiredExternalIds: { not: null } }],
119
+ },
120
+ })) as StorePauseRow[];
121
+ const reopened: StorePauseRow[] = [];
122
+ for (const row of rows) {
123
+ const moved = await table.updateMany({ where: { id: row.id, state: "OPEN", wanted: "OPEN" }, data: { state: "RESUMING" } });
124
+ if (moved.count > 0) reopened.push(row);
125
+ }
126
+ return reopened;
127
+ }
128
+
129
+ /** One sweep pass. A host whose database has no pause model sweeps nothing. */
130
+ export async function sweepAvailability(ctx: EngineContext, now: Date): Promise<AvailabilitySweepResult> {
131
+ const db = await ctx.ports.db();
132
+ if (!hasPauseTable(db)) return { expired: 0, requeued: 0, givenUp: 0 };
133
+ const table = pauseTable(db);
134
+ const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
135
+ const cutoff = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
136
+
137
+ const expired = await expire(ctx, now);
138
+ const givenUp = await giveUp(ctx, cutoff, now);
139
+ const waiting = (await table.findMany({
140
+ where: { state: { in: ["PAUSING", "RESUMING"] }, requestedAt: { lt: stale, gte: cutoff } },
141
+ })) as StorePauseRow[];
142
+ const retired = (await table.findMany({ where: { state: "PAUSED", retiredExternalIds: { not: null } } })) as StorePauseRow[];
143
+ const failedResumes = await retryFailedResumes(ctx, stale, cutoff);
144
+ const orphans = await reopenOrphans(ctx, stale);
145
+ const requeued = await requeue(ctx, [...waiting, ...retired, ...failedResumes, ...orphans], now);
146
+ if (givenUp > 0) ctx.ports.logger.error(`marketplace.availability-sweep: gave up on ${givenUp} store pause ask(s).`);
147
+ return { expired, requeued, givenUp };
148
+ }
@@ -0,0 +1,316 @@
1
+ import type { EngineContext } from "./ports";
2
+ import {
3
+ availabilityDedupeKey,
4
+ enqueueAvailability,
5
+ holdsSomething,
6
+ pauseTable,
7
+ readPause,
8
+ type StorePauseFailureCode,
9
+ type StorePauseRow,
10
+ type StorePauseState,
11
+ type StorePauseWanted,
12
+ } from "./pause-store";
13
+ import type { MarketplaceProvider } from "./types";
14
+
15
+ /**
16
+ * The store pause, as the host calls it (FUT-4851): `pauseStore` when the
17
+ * kitchen pauses and on every renewal, `resumeStore` the moment the pause is
18
+ * over, `availabilityState` for the screen. The host owns the debounce; these
19
+ * calls only record the ask and queue `marketplace.availability`, whose job
20
+ * makes the calls (`./pause-job.ts`). No path that answers a request reaches
21
+ * a marketplace.
22
+ */
23
+
24
+ /** What `pauseStore` did on one marketplace. */
25
+ export type PauseOutcome =
26
+ /** The ask was recorded and the job queued. */
27
+ | "queued"
28
+ /** A pause with exactly this end already stands or is on its way. */
29
+ | "unchanged"
30
+ /** The marketplace's adapter cannot pause a store: the host says so. */
31
+ | "unsupported"
32
+ /** The connection has no credentials or no merchant id. */
33
+ | "not-connected";
34
+
35
+ /** What `resumeStore` did on one marketplace. */
36
+ export type ResumeOutcome =
37
+ /** Something of ours stands on the marketplace: the job deletes it. */
38
+ | "queued"
39
+ /** Nothing of ours stands there: the record is OPEN, and nobody is called. */
40
+ | "open"
41
+ /** A resume is already on its way. */
42
+ | "unchanged";
43
+
44
+ export interface PauseStoreInput {
45
+ clientId: string;
46
+ /** The kitchen's estimated reopening time: the end every marketplace is given. */
47
+ until: Date;
48
+ /** The host's words for the closure (its copy, in the store's language). */
49
+ reason: string;
50
+ /** The store's IANA time zone. */
51
+ timeZone: string;
52
+ now?: Date;
53
+ }
54
+
55
+ export type PauseStoreResult =
56
+ | { kind: "invalid"; code: "UNTIL_NOT_FUTURE" | "TIME_ZONE_INVALID" }
57
+ | { kind: "ok"; marketplaces: { provider: MarketplaceProvider; outcome: PauseOutcome }[] };
58
+
59
+ /** One marketplace's pause as the screen shows it. */
60
+ export interface StoreAvailabilityView {
61
+ provider: MarketplaceProvider;
62
+ /** The adapter can pause a store at all. */
63
+ supported: boolean;
64
+ /** `interruption` (an id and an end) or `switch` (on/off); null when unsupported. */
65
+ kind: "interruption" | "switch" | null;
66
+ /** The connection has credentials and a merchant id. */
67
+ connected: boolean;
68
+ state: StorePauseState;
69
+ wanted: StorePauseWanted;
70
+ /** The end the host asked for. */
71
+ until: Date | null;
72
+ /** The end the marketplace was given and confirmed. */
73
+ sentUntil: Date | null;
74
+ failureCode: StorePauseFailureCode | null;
75
+ /** The marketplace's own words, verbatim and cut; never copy to show as is. */
76
+ failureDetail: string | null;
77
+ pausedAt: Date | null;
78
+ resumedAt: Date | null;
79
+ updatedAt: Date | null;
80
+ }
81
+
82
+ interface ConnectionRow {
83
+ provider: string;
84
+ externalMerchantId: string | null;
85
+ credentials: string;
86
+ }
87
+
88
+ /** The store's live connections (enabled, not archived), with whether each can be called. */
89
+ async function liveConnections(ctx: EngineContext, clientId: string): Promise<ConnectionRow[]> {
90
+ const db = await ctx.ports.db();
91
+ return (await db.marketplaceIntegration.findMany({
92
+ where: { clientId, enabled: true, archivedAt: null },
93
+ select: { provider: true, externalMerchantId: true, credentials: true },
94
+ orderBy: { provider: "asc" },
95
+ })) as ConnectionRow[];
96
+ }
97
+
98
+ const isConnected = (row: ConnectionRow): boolean => row.credentials !== "" && Boolean(row.externalMerchantId);
99
+
100
+ /** Whether an IANA zone name is one this runtime knows. */
101
+ function validTimeZone(timeZone: string): boolean {
102
+ try {
103
+ new Intl.DateTimeFormat("en-US", { timeZone });
104
+ return timeZone !== "";
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Whether a pause with exactly this end already stands, or is on its way. An
112
+ * earlier end is asked like a later one: the store is never closed on a
113
+ * marketplace longer than the kitchen's own pause.
114
+ */
115
+ function alreadyAsked(row: StorePauseRow | null, until: Date): boolean {
116
+ if (!row || row.wanted !== "PAUSED") return false;
117
+ if (row.state !== "PAUSING" && row.state !== "PAUSED") return false;
118
+ return row.until !== null && row.until.getTime() === until.getTime();
119
+ }
120
+
121
+ /** Record one marketplace's pause and queue its job, unless it already stands. */
122
+ async function askPause(ctx: EngineContext, input: Required<PauseStoreInput>, provider: string): Promise<PauseOutcome> {
123
+ const existing = await readPause(ctx, input.clientId, provider);
124
+ if (alreadyAsked(existing, input.until)) return "unchanged";
125
+ const table = pauseTable(await ctx.ports.db());
126
+ const data = {
127
+ wanted: "PAUSED",
128
+ state: "PAUSING",
129
+ until: input.until,
130
+ reason: input.reason,
131
+ timeZone: input.timeZone,
132
+ requestedAt: input.now,
133
+ // No key is minted here: the job writes one just before its call, so a
134
+ // resume that lands first knows nothing of ours can stand there. A key
135
+ // still in doubt stays on the row (its create may have landed).
136
+ failureCode: null,
137
+ failureDetail: null,
138
+ failedAt: null,
139
+ };
140
+ await table.upsert({
141
+ where: { clientId_provider: { clientId: input.clientId, provider } },
142
+ create: { clientId: input.clientId, provider, ...data },
143
+ update: data,
144
+ });
145
+ const payload = { clientId: input.clientId, provider };
146
+ await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, input.now));
147
+ return "queued";
148
+ }
149
+
150
+ /**
151
+ * Pause the store on every live connection whose marketplace can be paused.
152
+ * Idempotent: a pause already standing (or on its way) with exactly this end
153
+ * does nothing; any other end renews it, an earlier one included. Called again
154
+ * on every renewal of the kitchen's pause.
155
+ */
156
+ export async function pauseStore(ctx: EngineContext, input: PauseStoreInput): Promise<PauseStoreResult> {
157
+ const now = input.now ?? ctx.ports.clock.now();
158
+ if (input.until.getTime() <= now.getTime()) return { kind: "invalid", code: "UNTIL_NOT_FUTURE" };
159
+ if (!validTimeZone(input.timeZone)) return { kind: "invalid", code: "TIME_ZONE_INVALID" };
160
+ pauseTable(await ctx.ports.db());
161
+ const full = { ...input, now };
162
+ const marketplaces: { provider: MarketplaceProvider; outcome: PauseOutcome }[] = [];
163
+ for (const connection of await liveConnections(ctx, input.clientId)) {
164
+ const adapter = ctx.registry.get(connection.provider);
165
+ let outcome: PauseOutcome;
166
+ if (!adapter?.availability) outcome = "unsupported";
167
+ else if (!isConnected(connection)) outcome = "not-connected";
168
+ else outcome = await askPause(ctx, full, connection.provider);
169
+ marketplaces.push({ provider: connection.provider, outcome });
170
+ }
171
+ if (marketplaces.some((entry) => entry.outcome === "queued")) ctx.ports.publishChanged(input.clientId);
172
+ return { kind: "ok", marketplaces };
173
+ }
174
+
175
+ /**
176
+ * Rewrite one record's ask to OPEN; queue the job when something of ours
177
+ * stands there OR may be on its way: a PAUSING record may have a call in
178
+ * flight whose key the job wrote after this read. The write is predicated on
179
+ * the key read, so a claim that lands in between makes this re-read.
180
+ */
181
+ async function askResume(ctx: EngineContext, read: StorePauseRow, now: Date): Promise<ResumeOutcome> {
182
+ let row: StorePauseRow | null = read;
183
+ for (let tries = 0; row && tries < 3; tries += 1) {
184
+ if (resumeAsked(row)) return "unchanged";
185
+ const outcome = await writeResume(ctx, row, now);
186
+ if (outcome !== null) return outcome;
187
+ row = await readPause(ctx, read.clientId, read.provider);
188
+ }
189
+ return row ? forceResume(ctx, row, now) : "unchanged";
190
+ }
191
+
192
+ /**
193
+ * Every predicated write missed (the row kept moving): the resume is never
194
+ * lost. RESUMING with no predicate, and the job queued: it re-reads the row
195
+ * and deletes whatever of ours stands, or finds nothing and settles OPEN.
196
+ */
197
+ async function forceResume(ctx: EngineContext, row: StorePauseRow, now: Date): Promise<ResumeOutcome> {
198
+ const table = pauseTable(await ctx.ports.db());
199
+ await table.updateMany({
200
+ where: { id: row.id },
201
+ data: { wanted: "OPEN", state: "RESUMING", requestedAt: now, failureCode: null, failureDetail: null, failedAt: null },
202
+ });
203
+ const payload = { clientId: row.clientId, provider: row.provider };
204
+ await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, now));
205
+ return "queued";
206
+ }
207
+
208
+ /** Whether a resume already stands: on its way, or OPEN with nothing of ours left. */
209
+ function resumeAsked(row: StorePauseRow): boolean {
210
+ if (row.wanted !== "OPEN") return false;
211
+ return row.state === "RESUMING" || (row.state === "OPEN" && !holdsSomething(row));
212
+ }
213
+
214
+ /** The resume's write, predicated on the key read; null when the row moved under it. */
215
+ async function writeResume(ctx: EngineContext, row: StorePauseRow, now: Date): Promise<ResumeOutcome | null> {
216
+ const held = holdsSomething(row) || row.state === "PAUSING";
217
+ const table = pauseTable(await ctx.ports.db());
218
+ const moved = await table.updateMany({
219
+ where: { id: row.id, attemptKey: row.attemptKey },
220
+ data: {
221
+ wanted: "OPEN",
222
+ state: held ? "RESUMING" : "OPEN",
223
+ requestedAt: now,
224
+ failureCode: null,
225
+ failureDetail: null,
226
+ failedAt: null,
227
+ ...(held ? {} : { resumedAt: now }),
228
+ },
229
+ });
230
+ if (moved.count === 0) return null;
231
+ if (!held) return "open";
232
+ const payload = { clientId: row.clientId, provider: row.provider };
233
+ await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, now));
234
+ return "queued";
235
+ }
236
+
237
+ /**
238
+ * The kitchen's pause is over: open the store again wherever the engine
239
+ * closed it. Only what the engine created is deleted; a marketplace where
240
+ * nothing of ours stands is not called at all. Every record is answered,
241
+ * a connection disabled since the pause included.
242
+ */
243
+ export async function resumeStore(
244
+ ctx: EngineContext,
245
+ input: { clientId: string; now?: Date },
246
+ ): Promise<{ marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] }> {
247
+ const now = input.now ?? ctx.ports.clock.now();
248
+ const table = pauseTable(await ctx.ports.db());
249
+ const rows = (await table.findMany({
250
+ where: { clientId: input.clientId },
251
+ orderBy: { provider: "asc" },
252
+ })) as StorePauseRow[];
253
+ const marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] = [];
254
+ for (const row of rows) marketplaces.push({ provider: row.provider, outcome: await askResume(ctx, row, now) });
255
+ if (marketplaces.some((entry) => entry.outcome !== "unchanged")) ctx.ports.publishChanged(input.clientId);
256
+ return { marketplaces };
257
+ }
258
+
259
+ /** What a marketplace with no record reads as: OPEN, never asked. */
260
+ const NEVER_ASKED: Omit<StoreAvailabilityView, "provider" | "supported" | "kind" | "connected"> = {
261
+ state: "OPEN",
262
+ wanted: "OPEN",
263
+ until: null,
264
+ sentUntil: null,
265
+ failureCode: null,
266
+ failureDetail: null,
267
+ pausedAt: null,
268
+ resumedAt: null,
269
+ updatedAt: null,
270
+ };
271
+
272
+ function viewOf(ctx: EngineContext, provider: string, connection: ConnectionRow | undefined, row: StorePauseRow | undefined): StoreAvailabilityView {
273
+ const availability = ctx.registry.get(provider)?.availability;
274
+ const recorded = row
275
+ ? {
276
+ state: row.state,
277
+ wanted: row.wanted,
278
+ until: row.until,
279
+ sentUntil: row.sentUntil,
280
+ failureCode: row.failureCode,
281
+ failureDetail: row.failureDetail,
282
+ pausedAt: row.pausedAt,
283
+ resumedAt: row.resumedAt,
284
+ updatedAt: row.updatedAt,
285
+ }
286
+ : NEVER_ASKED;
287
+ return {
288
+ provider,
289
+ supported: availability !== undefined,
290
+ kind: availability?.kind ?? null,
291
+ connected: connection !== undefined && isConnected(connection),
292
+ ...recorded,
293
+ };
294
+ }
295
+
296
+ /**
297
+ * Where the store's pause stands on each marketplace: every live connection,
298
+ * plus any record of a connection since disabled that still holds something.
299
+ * A host on a database without the pause model reads every marketplace OPEN.
300
+ */
301
+ export async function availabilityState(ctx: EngineContext, clientId: string): Promise<StoreAvailabilityView[]> {
302
+ const db = await ctx.ports.db();
303
+ const connections = await liveConnections(ctx, clientId);
304
+ const rows = db.marketplaceStorePause
305
+ ? ((await db.marketplaceStorePause.findMany({ where: { clientId } })) as StorePauseRow[])
306
+ : [];
307
+ const byProvider = new Map(rows.map((row) => [row.provider, row]));
308
+ const views = connections.map((connection) =>
309
+ viewOf(ctx, connection.provider, connection, byProvider.get(connection.provider)),
310
+ );
311
+ const live = new Set(connections.map((connection) => connection.provider));
312
+ for (const row of rows) {
313
+ if (!live.has(row.provider) && holdsSomething(row)) views.push(viewOf(ctx, row.provider, undefined, row));
314
+ }
315
+ return views;
316
+ }
package/src/core/ports.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { AdapterRegistry } from "./registry";
2
2
  import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp } from "./adapter";
3
+ import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
3
4
  import type { NormalizedMarketplaceOrder } from "./types";
4
5
 
5
6
  /**
@@ -52,6 +53,34 @@ export interface MarketplaceDb {
52
53
  create(args: unknown): Promise<unknown>;
53
54
  updateMany(args: unknown): Promise<{ count: number }>;
54
55
  };
56
+ /**
57
+ * OPTIONAL in the type, so a host on 1.x that has not yet composed the
58
+ * catalogue model still compiles; the catalogue calls refuse without it
59
+ * (FUT-4768, migration `20261113120000_marketplace_catalogue`).
60
+ */
61
+ marketplaceCataloguePublication?: {
62
+ findFirst(args: unknown): Promise<unknown>;
63
+ findMany(args: unknown): Promise<unknown[]>;
64
+ upsert(args: unknown): Promise<unknown>;
65
+ updateMany(args: unknown): Promise<{ count: number }>;
66
+ };
67
+ /** OPTIONAL, as above: the marketplace's category ids, found or created once per name. */
68
+ marketplaceCatalogueCategory?: {
69
+ findFirst(args: unknown): Promise<unknown>;
70
+ create(args: unknown): Promise<unknown>;
71
+ updateMany(args: unknown): Promise<{ count: number }>;
72
+ };
73
+ /**
74
+ * OPTIONAL in the type, so a host on 1.x that has not yet composed the
75
+ * pause model still compiles; `pauseStore` refuses without it (FUT-4851,
76
+ * migration `20261113230000_marketplace_store_pause`).
77
+ */
78
+ marketplaceStorePause?: {
79
+ findFirst(args: unknown): Promise<unknown>;
80
+ findMany(args: unknown): Promise<unknown[]>;
81
+ upsert(args: unknown): Promise<unknown>;
82
+ updateMany(args: unknown): Promise<{ count: number }>;
83
+ };
55
84
  }
56
85
 
57
86
  /**
@@ -239,6 +268,19 @@ export interface MarketplaceLogger {
239
268
  error(message: string, ...meta: unknown[]): void;
240
269
  }
241
270
 
271
+ /**
272
+ * The host's catalogue, as the catalogue publishing reads it (FUT-4768). The
273
+ * engine never reads a host table: the host maps its product into the item
274
+ * shape, at the moment the job sends it, so what goes out is the product as it
275
+ * is now rather than as it was when the switch was turned on.
276
+ */
277
+ export interface MarketplaceCataloguePort {
278
+ /** These products as they go out, keyed by product id. Missing ids are products that no longer exist. */
279
+ items(clientId: string, productIds: readonly string[]): Promise<Map<string, CatalogueItem>>;
280
+ /** The bytes behind an item's photo, for a marketplace that takes an upload; null when they cannot be read. */
281
+ image(url: string): Promise<CatalogueImage | null>;
282
+ }
283
+
242
284
  /** Everything the host plugs in. */
243
285
  export interface MarketplacePorts {
244
286
  db: () => Promise<MarketplaceDb>;
@@ -270,6 +312,11 @@ export interface MarketplacePorts {
270
312
  * only given up on after `OUTBOUND_GIVE_UP_MS`.
271
313
  */
272
314
  cancellationWindowMs?: number;
315
+ /**
316
+ * OPTIONAL. The host's catalogue, for publishing products to a marketplace's
317
+ * catalogue. Absent: every catalogue call answers `UNSUPPORTED`.
318
+ */
319
+ catalogue?: MarketplaceCataloguePort;
273
320
  /** The acceptance window a connection gets when it does not state its own. */
274
321
  defaultAckSlaSeconds: number;
275
322
  /** How many stored deliveries one reconciliation pass re-runs. */