@12-apps/marketplace 1.3.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.
- package/ADOPTING.md +47 -0
- package/README.md +71 -0
- package/dist/99food/index.d.ts +33 -2
- package/dist/99food/index.js +34 -2
- package/dist/99food/index.js.map +1 -1
- package/dist/{adapter-0l_EmuJA.d.ts → adapter-B8QtQ2RA.d.ts} +126 -3
- package/dist/{chunk-AYYBRQJV.js → chunk-DPCZVN2C.js} +43 -3
- package/dist/chunk-DPCZVN2C.js.map +1 -0
- package/dist/{chunk-XUAFXNOH.js → chunk-EBAIZQPB.js} +395 -4
- package/dist/chunk-EBAIZQPB.js.map +1 -0
- package/dist/{chunk-RVBTARIY.js → chunk-SZRZTLVU.js} +1 -1
- package/dist/chunk-SZRZTLVU.js.map +1 -0
- package/dist/{engine-CZsP8KWd.d.ts → engine-o5cm54vC.d.ts} +242 -2
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +14 -2
- package/dist/ifood/index.js +164 -1
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +300 -3
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +4 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/index.d.ts +15 -2
- package/dist/rappi/index.js +56 -2
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +18 -7
- package/dist/server/index.js +4 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +67 -1
- package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
- package/src/99food/index.ts +10 -0
- package/src/99food/pause.ts +56 -0
- package/src/core/adapter.ts +12 -2
- package/src/core/engine.ts +37 -0
- package/src/core/pause-job.ts +381 -0
- package/src/core/pause-port.ts +110 -0
- package/src/core/pause-retired.ts +139 -0
- package/src/core/pause-store.ts +151 -0
- package/src/core/pause-sweep.ts +148 -0
- package/src/core/pause.ts +316 -0
- package/src/core/ports.ts +11 -0
- package/src/ifood/index.ts +4 -0
- package/src/ifood/pause.ts +257 -0
- package/src/index.ts +24 -0
- package/src/rappi/index.ts +11 -0
- package/src/rappi/outbound.ts +2 -2
- package/src/rappi/pause.ts +98 -0
- package/src/server/index.ts +1 -0
- package/src/server/jobs.ts +64 -4
- package/dist/chunk-AYYBRQJV.js.map +0 -1
- package/dist/chunk-RVBTARIY.js.map +0 -1
- package/dist/chunk-XUAFXNOH.js.map +0 -1
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from "../core/adapter";
|
|
2
|
+
import type { MarketplaceAvailability } from "../core/pause-port";
|
|
3
|
+
import { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from "./outbound";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the
|
|
7
|
+
* software PUSHES the merchant's status to the Ordering Application.
|
|
8
|
+
*
|
|
9
|
+
* `POST /v1/merchantUpdate` (host: the Ordering Application, OAuth2 `od.all`)
|
|
10
|
+
* "sent with only the `merchantStatus` field ... will force the opening or
|
|
11
|
+
* closing of the merchant within the Ordering Application"; `merchantStatus`
|
|
12
|
+
* is `AVAILABLE | UNAVAILABLE`, "only use this type when you must close
|
|
13
|
+
* (disable) the merchant due to an unexpected event and you don't know when
|
|
14
|
+
* the service will be re-established"; 204 (200 "for compatibility"), 400,
|
|
15
|
+
* 401, 403, 404, 503 (openapi.yaml v1.7.1, README "Pausing a store").
|
|
16
|
+
*
|
|
17
|
+
* A SWITCH, with no id and no end, so offered only when the host opts in
|
|
18
|
+
* (`pauseByStoreSwitch`; see `../core/pause-port.ts`). ESTIMATED: the path
|
|
19
|
+
* (the spec files this webhook under the key `/v1/menuUpdated` while its own
|
|
20
|
+
* description and route table say `POST /v1/merchantUpdate`; the latter is
|
|
21
|
+
* sent), that 99Food implements it at all, and that the token names the
|
|
22
|
+
* merchant (Open Delivery authenticates per merchant, so the body names none).
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** Set the merchant's status. */
|
|
26
|
+
export function openDeliverySetMerchantStatus(
|
|
27
|
+
ctx: AdapterCallContext,
|
|
28
|
+
bases: NinetyNineFoodApiBaseUrls,
|
|
29
|
+
status: "AVAILABLE" | "UNAVAILABLE",
|
|
30
|
+
): Promise<OutboundResult> {
|
|
31
|
+
return answered(async () => {
|
|
32
|
+
const auth = await bearer(ctx, bases);
|
|
33
|
+
if (!("token" in auth)) return auth;
|
|
34
|
+
const response = await ctx.http({
|
|
35
|
+
method: "POST",
|
|
36
|
+
url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
|
|
37
|
+
headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json" },
|
|
38
|
+
body: JSON.stringify({ merchantStatus: status }),
|
|
39
|
+
});
|
|
40
|
+
if (response.status !== 401) return outboundResultOf(response);
|
|
41
|
+
ctx.tokens.delete(tokenKey(ctx));
|
|
42
|
+
return { kind: "retry", reason: "99Food refused the token" };
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 99Food's availability capability: Open Delivery's merchant status, a switch. */
|
|
47
|
+
export function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {
|
|
48
|
+
return {
|
|
49
|
+
kind: "switch",
|
|
50
|
+
pause: async (ctx, request) => {
|
|
51
|
+
const result = await openDeliverySetMerchantStatus(ctx, bases, "UNAVAILABLE");
|
|
52
|
+
return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
|
|
53
|
+
},
|
|
54
|
+
resume: (ctx) => openDeliverySetMerchantStatus(ctx, bases, "AVAILABLE"),
|
|
55
|
+
};
|
|
56
|
+
}
|
package/src/core/adapter.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { MarketplaceCatalogue } from "./catalogue-port";
|
|
2
|
+
import type { MarketplaceAvailability } from "./pause-port";
|
|
2
3
|
import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -42,8 +43,11 @@ export interface MarketplaceCredentials {
|
|
|
42
43
|
|
|
43
44
|
/** What the host's HTTP client takes. */
|
|
44
45
|
export interface MarketplaceHttpRequest {
|
|
45
|
-
/**
|
|
46
|
-
|
|
46
|
+
/**
|
|
47
|
+
* `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.
|
|
48
|
+
* `DELETE` since FUT-4851: iFood removes an interruption with it.
|
|
49
|
+
*/
|
|
50
|
+
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
47
51
|
url: string;
|
|
48
52
|
headers: Record<string, string>;
|
|
49
53
|
body?: string;
|
|
@@ -180,6 +184,12 @@ export interface MarketplaceAdapter {
|
|
|
180
184
|
* marketplace cannot be published to, and the host says so.
|
|
181
185
|
*/
|
|
182
186
|
readonly catalogue?: MarketplaceCatalogue;
|
|
187
|
+
/**
|
|
188
|
+
* OPTIONAL. Closing the store on this marketplace for a while, and opening
|
|
189
|
+
* it again (FUT-4851). Absent: the marketplace cannot be paused through an
|
|
190
|
+
* API, and the host says so.
|
|
191
|
+
*/
|
|
192
|
+
readonly availability?: MarketplaceAvailability;
|
|
183
193
|
/** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
|
|
184
194
|
appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
|
|
185
195
|
}
|
package/src/core/engine.ts
CHANGED
|
@@ -58,6 +58,18 @@ import {
|
|
|
58
58
|
} from "./integration";
|
|
59
59
|
import { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from "./menu-links";
|
|
60
60
|
import { runOutbound, type OutboundAttempt, type OutboundOutcome } from "./outbound";
|
|
61
|
+
import {
|
|
62
|
+
availabilityState,
|
|
63
|
+
pauseStore,
|
|
64
|
+
resumeStore,
|
|
65
|
+
type PauseStoreInput,
|
|
66
|
+
type PauseStoreResult,
|
|
67
|
+
type ResumeOutcome,
|
|
68
|
+
type StoreAvailabilityView,
|
|
69
|
+
} from "./pause";
|
|
70
|
+
import { runAvailability, type AvailabilityOutcome } from "./pause-job";
|
|
71
|
+
import type { AvailabilityJobPayload } from "./pause-store";
|
|
72
|
+
import { sweepAvailability, type AvailabilitySweepResult } from "./pause-sweep";
|
|
61
73
|
import type { OutboundJobPayload } from "./outbound-queue";
|
|
62
74
|
import {
|
|
63
75
|
normalizeEvent,
|
|
@@ -208,6 +220,25 @@ export interface MarketplaceEngine {
|
|
|
208
220
|
}): Promise<CatalogueDocumentResult>;
|
|
209
221
|
/** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */
|
|
210
222
|
runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* The kitchen paused (or renewed its pause): close the store until `until`
|
|
226
|
+
* on every live connection whose marketplace can be paused (FUT-4851).
|
|
227
|
+
* Idempotent: the `until` already standing does nothing; any other, an
|
|
228
|
+
* earlier one included, renews the closure.
|
|
229
|
+
*/
|
|
230
|
+
pauseStore(input: PauseStoreInput): Promise<PauseStoreResult>;
|
|
231
|
+
/** The kitchen's pause is over: delete every closure the engine created, and nothing else. */
|
|
232
|
+
resumeStore(input: {
|
|
233
|
+
clientId: string;
|
|
234
|
+
now?: Date;
|
|
235
|
+
}): Promise<{ marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] }>;
|
|
236
|
+
/** Where the store's pause stands on each marketplace, for the screen. */
|
|
237
|
+
availabilityState(clientId: string): Promise<StoreAvailabilityView[]>;
|
|
238
|
+
/** Bring one marketplace in line with the last ask (the `marketplace.availability` job's body). */
|
|
239
|
+
runAvailability(payload: AvailabilityJobPayload, attempt: OutboundAttempt): Promise<AvailabilityOutcome>;
|
|
240
|
+
/** Expire, re-queue and give up on store pauses (the `marketplace.availability-sweep` job's body). */
|
|
241
|
+
sweepAvailability(now?: Date): Promise<AvailabilitySweepResult>;
|
|
211
242
|
}
|
|
212
243
|
|
|
213
244
|
/**
|
|
@@ -279,5 +310,11 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
|
|
|
279
310
|
catalogueState: (input) => readCatalogueState(ctx, input),
|
|
280
311
|
catalogueDocument: (input) => readCatalogueDocument(ctx, input),
|
|
281
312
|
runCatalogue: (payload, attempt) => runCatalogue(ctx, payload, attempt),
|
|
313
|
+
|
|
314
|
+
pauseStore: (input) => pauseStore(ctx, input),
|
|
315
|
+
resumeStore: (input) => resumeStore(ctx, input),
|
|
316
|
+
availabilityState: (clientId) => availabilityState(ctx, clientId),
|
|
317
|
+
runAvailability: (payload, attempt) => runAvailability(ctx, payload, attempt),
|
|
318
|
+
sweepAvailability: (now) => sweepAvailability(ctx, now ?? ports.clock.now()),
|
|
282
319
|
};
|
|
283
320
|
}
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import type { AdapterCallContext, OutboundResult } from "./adapter";
|
|
2
|
+
import { readOutboundConnection } from "./integration";
|
|
3
|
+
import type { OutboundAttempt } from "./outbound";
|
|
4
|
+
import type { MarketplaceAvailability, StorePauseRef, StorePauseResult } from "./pause-port";
|
|
5
|
+
import {
|
|
6
|
+
STORE_PAUSE_LEASE_MS,
|
|
7
|
+
detailOf,
|
|
8
|
+
newAttemptKey,
|
|
9
|
+
pauseTable,
|
|
10
|
+
readPause,
|
|
11
|
+
holdsSomething,
|
|
12
|
+
type AvailabilityJobPayload,
|
|
13
|
+
type StorePauseFailureCode,
|
|
14
|
+
type StorePauseRow,
|
|
15
|
+
} from "./pause-store";
|
|
16
|
+
import { ended, heldIds, refOf, retire, retiredOf, retiredValue, withRetired } from "./pause-retired";
|
|
17
|
+
import type { EngineContext } from "./ports";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The `marketplace.availability` job: bring one marketplace in line with the
|
|
21
|
+
* host's last ask for one store (FUT-4851).
|
|
22
|
+
*
|
|
23
|
+
* The job re-reads the record before every call and after it, so the last ask
|
|
24
|
+
* wins: a resume that lands while a pause call is in flight finds the closure
|
|
25
|
+
* that call created recorded, and deletes it on the next step. A run holds a
|
|
26
|
+
* short lease on the record, so two runs never call one marketplace for one
|
|
27
|
+
* store at once. The answer rule is the outbound engine's: 2xx done, a final
|
|
28
|
+
* 4xx FAILED with the marketplace's words, anything else retried by the queue
|
|
29
|
+
* until the last attempt, which stamps `*_UNANSWERED`.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** What one run did. */
|
|
33
|
+
export type AvailabilityOutcome =
|
|
34
|
+
| { kind: "skipped"; reason: string }
|
|
35
|
+
| { kind: "done"; state: StorePauseRow["state"] }
|
|
36
|
+
| { kind: "failed"; code: StorePauseFailureCode };
|
|
37
|
+
|
|
38
|
+
/** Thrown so the queue retries. Its message is what the job log reads. */
|
|
39
|
+
export class AvailabilityRetryError extends Error {
|
|
40
|
+
constructor(message: string) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.name = "AvailabilityRetryError";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** How many steps one run takes at most: a pause, its retirement, a flip to resume and its deletes. */
|
|
47
|
+
const MAX_STEPS = 8;
|
|
48
|
+
|
|
49
|
+
interface Run {
|
|
50
|
+
ctx: EngineContext;
|
|
51
|
+
availability: MarketplaceAvailability;
|
|
52
|
+
call: AdapterCallContext;
|
|
53
|
+
merchantId: string;
|
|
54
|
+
attempt: OutboundAttempt;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
type Step = { settled: false } | { settled: true; outcome: AvailabilityOutcome };
|
|
58
|
+
const AGAIN: Step = { settled: false };
|
|
59
|
+
|
|
60
|
+
async function write(ctx: EngineContext, where: Record<string, unknown>, data: Record<string, unknown>): Promise<number> {
|
|
61
|
+
const table = pauseTable(await ctx.ports.db());
|
|
62
|
+
return (await table.updateMany({ where, data })).count;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* FAILED with a code, predicated on the ask the step acted on still standing.
|
|
67
|
+
* `detail` is the marketplace's own words (a refusal's) or null: an engine
|
|
68
|
+
* sentence never reaches the row a host renders; `log` goes to the logger.
|
|
69
|
+
* Returns whether it moved.
|
|
70
|
+
*/
|
|
71
|
+
async function failRow(
|
|
72
|
+
ctx: EngineContext,
|
|
73
|
+
now: Date,
|
|
74
|
+
row: StorePauseRow,
|
|
75
|
+
code: StorePauseFailureCode,
|
|
76
|
+
failure: { detail: string | null; log: string },
|
|
77
|
+
): Promise<boolean> {
|
|
78
|
+
const moved = await write(
|
|
79
|
+
ctx,
|
|
80
|
+
{ id: row.id, wanted: row.wanted },
|
|
81
|
+
{
|
|
82
|
+
state: "FAILED",
|
|
83
|
+
failureCode: code,
|
|
84
|
+
failureDetail: failure.detail === null || failure.detail === "" ? null : detailOf(failure.detail),
|
|
85
|
+
failedAt: now,
|
|
86
|
+
},
|
|
87
|
+
);
|
|
88
|
+
if (moved === 0) return false;
|
|
89
|
+
ctx.ports.logger.error(`marketplace.availability: ${row.provider} for ${row.clientId} failed: ${code} (${failure.log})`);
|
|
90
|
+
ctx.ports.publishChanged(row.clientId);
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function fail(run: Run, row: StorePauseRow, code: StorePauseFailureCode, failure: { detail: string | null; log: string }): Promise<Step> {
|
|
95
|
+
const moved = await failRow(run.ctx, run.call.now, row, code, failure);
|
|
96
|
+
return moved ? { settled: true, outcome: { kind: "failed", code } } : AGAIN;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A refusal fails at once with the marketplace's words; a retry throws until the last attempt, which fails. */
|
|
100
|
+
async function unanswered(
|
|
101
|
+
run: Run,
|
|
102
|
+
row: StorePauseRow,
|
|
103
|
+
result: Exclude<OutboundResult, { kind: "accepted" }>,
|
|
104
|
+
codes: { refused: StorePauseFailureCode; unanswered: StorePauseFailureCode },
|
|
105
|
+
): Promise<Step> {
|
|
106
|
+
if (result.kind === "refused") {
|
|
107
|
+
return fail(run, row, codes.refused, { detail: result.message, log: `refused ${result.status}: ${result.message}` });
|
|
108
|
+
}
|
|
109
|
+
if (run.attempt.attempt < run.attempt.maxAttempts) {
|
|
110
|
+
throw new AvailabilityRetryError(`${row.provider} for ${row.clientId}: ${result.reason}`);
|
|
111
|
+
}
|
|
112
|
+
return fail(run, row, codes.unanswered, { detail: null, log: result.reason });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const PAUSE_CODES = { refused: "PAUSE_REFUSED", unanswered: "PAUSE_UNANSWERED" } as const;
|
|
116
|
+
const RESUME_CODES = { refused: "RESUME_REFUSED", unanswered: "RESUME_UNANSWERED" } as const;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Whether the marketplace holds a closure to exactly this end. An earlier end
|
|
120
|
+
* is renewed like a later one: the store is never closed on a marketplace
|
|
121
|
+
* longer than the kitchen's own pause (the owner, 2026-11-12).
|
|
122
|
+
*/
|
|
123
|
+
const upToDate = (row: StorePauseRow): boolean =>
|
|
124
|
+
row.sentUntil !== null && row.until !== null && row.sentUntil.getTime() === row.until.getTime();
|
|
125
|
+
|
|
126
|
+
/** The closure the engine holds and still stands: an interruption's id, or a switch it turned off. */
|
|
127
|
+
const holds = (row: StorePauseRow): boolean => row.externalId !== null || row.sentUntil !== null;
|
|
128
|
+
|
|
129
|
+
async function calledSafely<T extends StorePauseResult | OutboundResult>(call: () => Promise<T>): Promise<T | { kind: "retry"; reason: string }> {
|
|
130
|
+
try {
|
|
131
|
+
return await call();
|
|
132
|
+
} catch (error) {
|
|
133
|
+
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** What a create under the row's key carried, for recognising its closure. */
|
|
138
|
+
const sentOf = (row: StorePauseRow, until: Date | null) =>
|
|
139
|
+
row.attemptKey !== null && until !== null ? { until, reason: row.reason ?? "", timeZone: row.timeZone ?? "UTC" } : null;
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Write a fresh key and the end it will carry BEFORE the call, predicated on
|
|
143
|
+
* no key being in doubt: a resume that lands meanwhile then knows a closure
|
|
144
|
+
* may exist, and a switch is never turned on before the engine tried to turn
|
|
145
|
+
* it off. False when the row moved under us.
|
|
146
|
+
*/
|
|
147
|
+
async function claimKey(run: Run, row: StorePauseRow): Promise<string | null> {
|
|
148
|
+
const key = newAttemptKey();
|
|
149
|
+
const moved = await write(run.ctx, { id: row.id, attemptKey: null, wanted: "PAUSED" }, { attemptKey: key, attemptUntil: row.until });
|
|
150
|
+
return moved > 0 ? key : null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Close the store, or move the end of the closure the engine holds. */
|
|
154
|
+
async function sendPause(run: Run, row: StorePauseRow): Promise<Step> {
|
|
155
|
+
const until = row.until as Date;
|
|
156
|
+
const key = row.attemptKey ?? (await claimKey(run, row));
|
|
157
|
+
if (key === null) return AGAIN;
|
|
158
|
+
const request = { merchantId: run.merchantId, until, reason: row.reason ?? "", key, timeZone: row.timeZone ?? "UTC", keep: heldIds(row) };
|
|
159
|
+
const extend = run.availability.extend;
|
|
160
|
+
const ref: StorePauseRef = { merchantId: run.merchantId, externalId: row.externalId, key: null, sent: null };
|
|
161
|
+
const result = await calledSafely(() =>
|
|
162
|
+
holds(row) && extend ? extend(run.call, ref, request) : run.availability.pause(run.call, request),
|
|
163
|
+
);
|
|
164
|
+
if (result.kind === "refused") {
|
|
165
|
+
// A final refusal created nothing: no key is left in doubt.
|
|
166
|
+
await write(run.ctx, { id: row.id, attemptKey: key }, { attemptKey: null, attemptUntil: null });
|
|
167
|
+
return unanswered(run, row, result, PAUSE_CODES);
|
|
168
|
+
}
|
|
169
|
+
// Otherwise the key stays on the row: a create whose answer was lost is found under it.
|
|
170
|
+
if (result.kind !== "paused") return unanswered(run, row, result, PAUSE_CODES);
|
|
171
|
+
// A new closure replaced the one the engine held: the old one, with its end, joins the list to delete.
|
|
172
|
+
const replaced = row.externalId !== null && result.externalId !== row.externalId;
|
|
173
|
+
const retired = replaced
|
|
174
|
+
? withRetired(run.ctx, row, { by: "id", value: row.externalId as string, end: row.sentUntil })
|
|
175
|
+
: retiredOf(row);
|
|
176
|
+
await write(
|
|
177
|
+
run.ctx,
|
|
178
|
+
{ id: row.id },
|
|
179
|
+
{ externalId: result.externalId, sentUntil: result.until, attemptKey: null, attemptUntil: null, retiredExternalIds: retiredValue(retired) },
|
|
180
|
+
);
|
|
181
|
+
return AGAIN;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* A key whose create carried another end than the one now asked, on an
|
|
186
|
+
* interruption: the closure its lost answer may have created joins the list
|
|
187
|
+
* to delete (by the key, with that end), and the new closure is created
|
|
188
|
+
* first, so the store is never open in between. A switch has one closure:
|
|
189
|
+
* the next OFF is simply sent again, never an ON in the middle of a pause.
|
|
190
|
+
*/
|
|
191
|
+
async function resolveStaleKey(run: Run, row: StorePauseRow): Promise<Step | null> {
|
|
192
|
+
if (run.availability.kind === "switch") return null;
|
|
193
|
+
if (row.attemptKey === null || row.attemptUntil === null || row.attemptUntil.getTime() === row.until?.getTime()) return null;
|
|
194
|
+
const retired = withRetired(run.ctx, row, { by: "key", value: row.attemptKey, end: row.attemptUntil });
|
|
195
|
+
await write(
|
|
196
|
+
run.ctx,
|
|
197
|
+
{ id: row.id, attemptKey: row.attemptKey },
|
|
198
|
+
{ attemptKey: null, attemptUntil: null, retiredExternalIds: retiredValue(retired) },
|
|
199
|
+
);
|
|
200
|
+
return AGAIN;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function stepPause(run: Run, current: StorePauseRow): Promise<Step> {
|
|
204
|
+
let row = current;
|
|
205
|
+
if (row.until === null) return fail(run, row, "PAUSE_REFUSED", { detail: null, log: "no end on the record" });
|
|
206
|
+
const stale = await resolveStaleKey(run, row);
|
|
207
|
+
if (stale) return stale;
|
|
208
|
+
// The new closure first; only then are the replaced ones deleted, so the store is never open in between.
|
|
209
|
+
if (!upToDate(row)) return sendPause(run, row);
|
|
210
|
+
if (row.retiredExternalIds !== null) {
|
|
211
|
+
const left = await retire(run, row);
|
|
212
|
+
await write(run.ctx, { id: row.id }, { retiredExternalIds: retiredValue(left) });
|
|
213
|
+
row = (await readPause(run.ctx, row.clientId, row.provider)) ?? row;
|
|
214
|
+
}
|
|
215
|
+
const moved = await write(
|
|
216
|
+
run.ctx,
|
|
217
|
+
{ id: row.id, wanted: "PAUSED", until: row.until },
|
|
218
|
+
{ state: "PAUSED", pausedAt: row.pausedAt ?? run.call.now, failureCode: null, failureDetail: null, failedAt: null },
|
|
219
|
+
);
|
|
220
|
+
// The ask moved under us: the next step reads it.
|
|
221
|
+
if (moved === 0) return AGAIN;
|
|
222
|
+
run.ctx.ports.publishChanged(row.clientId);
|
|
223
|
+
return { settled: true, outcome: { kind: "done", state: "PAUSED" } };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** The next closure of ours to delete, and what deleting it clears; null when nothing of ours stands. */
|
|
227
|
+
interface NextDelete {
|
|
228
|
+
ref: StorePauseRef;
|
|
229
|
+
clear: Record<string, null | string>;
|
|
230
|
+
/** A closure a renewal replaced: a final refusal drops it rather than failing the resume. */
|
|
231
|
+
replaced?: boolean;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function nextDelete(row: StorePauseRow, kind: MarketplaceAvailability["kind"]): NextDelete | null {
|
|
235
|
+
if (kind === "switch") {
|
|
236
|
+
// A switch has one closure: the store the engine turned off (or may have, while an answer is in doubt).
|
|
237
|
+
if (row.sentUntil === null && row.attemptKey === null) return null;
|
|
238
|
+
return {
|
|
239
|
+
ref: { merchantId: "", externalId: null, key: row.attemptKey, sent: sentOf(row, row.attemptUntil) },
|
|
240
|
+
clear: { sentUntil: null, attemptKey: null, attemptUntil: null, externalId: null },
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
if (row.externalId !== null) {
|
|
244
|
+
return { ref: { merchantId: "", externalId: row.externalId, key: null, sent: null }, clear: { externalId: null, sentUntil: null } };
|
|
245
|
+
}
|
|
246
|
+
const [retired, ...rest] = retiredOf(row);
|
|
247
|
+
if (retired !== undefined) return { ref: refOf(retired, row, ""), clear: { retiredExternalIds: retiredValue(rest) }, replaced: true };
|
|
248
|
+
if (row.attemptKey !== null) {
|
|
249
|
+
return {
|
|
250
|
+
ref: { merchantId: "", externalId: null, key: row.attemptKey, sent: sentOf(row, row.attemptUntil), keep: heldIds(row) },
|
|
251
|
+
clear: { attemptKey: null, attemptUntil: null, sentUntil: null },
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Drop, without a call, the replaced closures whose own end has passed. Returns the row as it now stands. */
|
|
258
|
+
async function pruneEnded(run: Run, row: StorePauseRow): Promise<StorePauseRow> {
|
|
259
|
+
const list = retiredOf(row);
|
|
260
|
+
const live = list.filter((entry) => !ended(entry, run.call.now));
|
|
261
|
+
if (live.length === list.length) return row;
|
|
262
|
+
await write(run.ctx, { id: row.id }, { retiredExternalIds: retiredValue(live) });
|
|
263
|
+
return { ...row, retiredExternalIds: retiredValue(live) };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function stepResume(run: Run, current: StorePauseRow): Promise<Step> {
|
|
267
|
+
const row = await pruneEnded(run, current);
|
|
268
|
+
const next = nextDelete(row, run.availability.kind);
|
|
269
|
+
if (next === null) {
|
|
270
|
+
await write(
|
|
271
|
+
run.ctx,
|
|
272
|
+
{ id: row.id, wanted: "OPEN" },
|
|
273
|
+
{ state: "OPEN", sentUntil: null, resumedAt: run.call.now, failureCode: null, failureDetail: null, failedAt: null },
|
|
274
|
+
);
|
|
275
|
+
run.ctx.ports.publishChanged(row.clientId);
|
|
276
|
+
return { settled: true, outcome: { kind: "done", state: "OPEN" } };
|
|
277
|
+
}
|
|
278
|
+
const ref = { ...next.ref, merchantId: run.merchantId };
|
|
279
|
+
const result = await calledSafely(() => run.availability.resume(run.call, ref));
|
|
280
|
+
const dropped = result.kind === "refused" && next.replaced === true;
|
|
281
|
+
if (dropped) {
|
|
282
|
+
run.ctx.ports.logger.warn(
|
|
283
|
+
`marketplace.availability: ${row.provider} for ${row.clientId}: a replaced closure's delete was refused ` +
|
|
284
|
+
`(${result.status}: ${result.message}); dropped, it ends on its own`,
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
if (result.kind !== "accepted" && !dropped) return unanswered(run, row, result, RESUME_CODES);
|
|
288
|
+
// Cleared whatever the ask now is: the closure is gone, and a pause asked meanwhile creates a new one.
|
|
289
|
+
await write(run.ctx, { id: row.id }, next.clear);
|
|
290
|
+
return AGAIN;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** The call context, or the reason the connection cannot be used. */
|
|
294
|
+
async function callContext(ctx: EngineContext, row: StorePauseRow): Promise<{ call: AdapterCallContext; merchantId: string } | string> {
|
|
295
|
+
const db = await ctx.ports.db();
|
|
296
|
+
const integration = (await db.marketplaceIntegration.findUnique({
|
|
297
|
+
where: { clientId_provider: { clientId: row.clientId, provider: row.provider } },
|
|
298
|
+
select: { externalMerchantId: true },
|
|
299
|
+
})) as { externalMerchantId: string | null } | null;
|
|
300
|
+
if (!integration?.externalMerchantId) return "no merchant id on the connection";
|
|
301
|
+
try {
|
|
302
|
+
const connection = await readOutboundConnection(ctx, row.clientId, row.provider);
|
|
303
|
+
if (!connection) return "no credentials on file";
|
|
304
|
+
return {
|
|
305
|
+
merchantId: integration.externalMerchantId,
|
|
306
|
+
call: { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
|
|
307
|
+
};
|
|
308
|
+
} catch (error) {
|
|
309
|
+
return `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Take the record's lease; the instant written, or null when another run holds it. */
|
|
314
|
+
async function lease(ctx: EngineContext, row: StorePauseRow, now: Date): Promise<Date | null> {
|
|
315
|
+
const until = new Date(now.getTime() + STORE_PAUSE_LEASE_MS);
|
|
316
|
+
const taken = await write(ctx, { id: row.id, OR: [{ leaseUntil: null }, { leaseUntil: { lt: now } }] }, { leaseUntil: until });
|
|
317
|
+
return taken > 0 ? until : null;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async function steps(run: Run, first: StorePauseRow): Promise<AvailabilityOutcome> {
|
|
321
|
+
let row: StorePauseRow | null = first;
|
|
322
|
+
for (let step = 0; step < MAX_STEPS && row; step += 1) {
|
|
323
|
+
const result = row.wanted === "PAUSED" ? await stepPause(run, row) : await stepResume(run, row);
|
|
324
|
+
if (result.settled) return result.outcome;
|
|
325
|
+
row = await readPause(run.ctx, first.clientId, first.provider);
|
|
326
|
+
}
|
|
327
|
+
return { kind: "skipped", reason: "the ask kept changing; the next run or the sweep finishes it" };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async function runOnce(ctx: EngineContext, payload: AvailabilityJobPayload, attempt: OutboundAttempt): Promise<AvailabilityOutcome> {
|
|
331
|
+
const row = await readPause(ctx, payload.clientId, payload.provider);
|
|
332
|
+
if (!row) return { kind: "skipped", reason: "no pause record" };
|
|
333
|
+
// An OPEN row that still holds something (a call whose answer was lost under a resume) is finished, not skipped.
|
|
334
|
+
const settled = row.state === "FAILED" || (row.state === "OPEN" && !holdsSomething(row));
|
|
335
|
+
if (settled) return { kind: "skipped", reason: `the record is ${row.state}` };
|
|
336
|
+
const availability = ctx.registry.get(row.provider)?.availability;
|
|
337
|
+
const now = ctx.ports.clock.now();
|
|
338
|
+
if (!availability) {
|
|
339
|
+
await failRow(ctx, now, row, "UNSUPPORTED", { detail: null, log: "the adapter has no availability capability" });
|
|
340
|
+
return { kind: "failed", code: "UNSUPPORTED" };
|
|
341
|
+
}
|
|
342
|
+
const held = await lease(ctx, row, now);
|
|
343
|
+
if (held === null) {
|
|
344
|
+
if (attempt.attempt < attempt.maxAttempts) throw new AvailabilityRetryError(`${row.provider} for ${row.clientId}: another run holds it`);
|
|
345
|
+
return { kind: "skipped", reason: "another run holds the record" };
|
|
346
|
+
}
|
|
347
|
+
try {
|
|
348
|
+
const opened = await callContext(ctx, row);
|
|
349
|
+
if (typeof opened === "string") {
|
|
350
|
+
await failRow(ctx, now, row, "NOT_CONNECTED", { detail: null, log: opened });
|
|
351
|
+
return { kind: "failed", code: "NOT_CONNECTED" };
|
|
352
|
+
}
|
|
353
|
+
return await steps({ ctx, availability, attempt, ...opened }, row);
|
|
354
|
+
} finally {
|
|
355
|
+
// Only this run's own lease: one that expired and was taken by another run is that run's.
|
|
356
|
+
await write(ctx, { id: row.id, leaseUntil: held }, { leaseUntil: null });
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Run one queued availability call. Throws {@link AvailabilityRetryError} for
|
|
362
|
+
* an answer worth retrying before the last attempt; any other throw (an
|
|
363
|
+
* adapter bug, a database error) is rethrown for the queue to retry, and on
|
|
364
|
+
* the last attempt ends FAILED as unanswered.
|
|
365
|
+
*/
|
|
366
|
+
export async function runAvailability(
|
|
367
|
+
ctx: EngineContext,
|
|
368
|
+
payload: AvailabilityJobPayload,
|
|
369
|
+
attempt: OutboundAttempt,
|
|
370
|
+
): Promise<AvailabilityOutcome> {
|
|
371
|
+
try {
|
|
372
|
+
return await runOnce(ctx, payload, attempt);
|
|
373
|
+
} catch (error) {
|
|
374
|
+
if (error instanceof AvailabilityRetryError || attempt.attempt < attempt.maxAttempts) throw error;
|
|
375
|
+
const row = await readPause(ctx, payload.clientId, payload.provider);
|
|
376
|
+
if (!row) return { kind: "skipped", reason: "no pause record" };
|
|
377
|
+
const code = row.wanted === "PAUSED" ? "PAUSE_UNANSWERED" : "RESUME_UNANSWERED";
|
|
378
|
+
await failRow(ctx, ctx.ports.clock.now(), row, code, { detail: null, log: error instanceof Error ? error.message : String(error) });
|
|
379
|
+
return { kind: "failed", code };
|
|
380
|
+
}
|
|
381
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { AdapterCallContext, OutboundResult } from "./adapter";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The adapter port's OPTIONAL availability capability: closing a store on a
|
|
5
|
+
* marketplace for a while, and opening it again (FUT-4851).
|
|
6
|
+
*
|
|
7
|
+
* The owner's rules (2026-11-12), translated:
|
|
8
|
+
*
|
|
9
|
+
* 1. "When the kitchen is paused, the store is paused on every connected
|
|
10
|
+
* marketplace. The interruption carries the kitchen's estimated reopening
|
|
11
|
+
* time as its end, is renewed while the kitchen stays paused, and is
|
|
12
|
+
* deleted the moment the pause is over. The store is never closed on a
|
|
13
|
+
* marketplace longer than the kitchen's own pause."
|
|
14
|
+
* 2. The debounce is the host's; the engine receives pause(until) and resume.
|
|
15
|
+
* 3. "Never reopen a store the owner closed by hand on the marketplace, and
|
|
16
|
+
* never close one beyond what the kitchen's pause asked": the engine only
|
|
17
|
+
* deletes what IT created.
|
|
18
|
+
*
|
|
19
|
+
* Marketplaces close a store in one of two shapes, stated by the adapter as
|
|
20
|
+
* {@link MarketplaceAvailability.kind}:
|
|
21
|
+
*
|
|
22
|
+
* - `interruption`: the marketplace keeps a closure with its OWN id and an
|
|
23
|
+
* END (iFood's interruptions). The engine stores the id and deletes only
|
|
24
|
+
* that id; a closure the owner made by hand is another id and is never
|
|
25
|
+
* touched. If every call after the pause is lost, the marketplace still
|
|
26
|
+
* opens the store at the end it was given.
|
|
27
|
+
* - `switch`: a store-wide on/off with no id and no end (Rappi's store
|
|
28
|
+
* availability, Open Delivery's `merchantStatus`). The engine turns a store
|
|
29
|
+
* on only if its own record says it turned it off, and turns it on again by
|
|
30
|
+
* itself once the `until` it was given has passed without a renewal. What a
|
|
31
|
+
* switch cannot tell apart: an owner who ALSO closed the store by hand while
|
|
32
|
+
* the kitchen's pause stood is reopened with it. That is why a switch
|
|
33
|
+
* adapter offers the capability only when its host opts in.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** What a pause asks of one marketplace. */
|
|
37
|
+
export interface StorePauseRequest {
|
|
38
|
+
/** The store on the marketplace: the connection's `externalMerchantId`. */
|
|
39
|
+
merchantId: string;
|
|
40
|
+
/** When the store should open again on its own: the kitchen's estimated reopening time. */
|
|
41
|
+
until: Date;
|
|
42
|
+
/** The host's words for the closure, shown to the merchant where the marketplace shows one. */
|
|
43
|
+
reason: string;
|
|
44
|
+
/**
|
|
45
|
+
* A stable key for THIS closure, the same on every retry of it. An adapter
|
|
46
|
+
* that can name its own closure sends it; one that can list closures finds
|
|
47
|
+
* the closure a lost answer already created, by the key or, where the
|
|
48
|
+
* marketplace assigns its own id, by the end and the reason it carries, so
|
|
49
|
+
* a retry never creates a second one.
|
|
50
|
+
*/
|
|
51
|
+
key: string;
|
|
52
|
+
/** The store's IANA time zone, for a marketplace that reads times as the store's wall clock. */
|
|
53
|
+
timeZone: string;
|
|
54
|
+
/**
|
|
55
|
+
* OPTIONAL. The marketplace ids the engine already holds (the current
|
|
56
|
+
* closure, the replaced ones it is about to delete): a closure found again
|
|
57
|
+
* for this create is never one of them.
|
|
58
|
+
*/
|
|
59
|
+
keep?: readonly string[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The closure the engine holds on one marketplace, as a resume or an extend names it. */
|
|
63
|
+
export interface StorePauseRef {
|
|
64
|
+
merchantId: string;
|
|
65
|
+
/** The marketplace's own id for the closure; null for a switch, or when the create's answer was lost. */
|
|
66
|
+
externalId: string | null;
|
|
67
|
+
/** The key the closure was created under; null once nothing of ours is in doubt. */
|
|
68
|
+
key: string | null;
|
|
69
|
+
/**
|
|
70
|
+
* What the create under `key` carried, for a marketplace that names a
|
|
71
|
+
* closure with its own id: the closure whose end and description are these
|
|
72
|
+
* is the one a lost answer created. Null with no key in doubt.
|
|
73
|
+
*/
|
|
74
|
+
sent: { until: Date; reason: string; timeZone: string } | null;
|
|
75
|
+
/**
|
|
76
|
+
* OPTIONAL. The marketplace ids the engine already holds (the current
|
|
77
|
+
* closure, the replaced ones): a closure found under `key` is never one of
|
|
78
|
+
* them, so deleting a lost create can never delete the closure that stands.
|
|
79
|
+
*/
|
|
80
|
+
keep?: readonly string[];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** One pause or extend's answer. */
|
|
84
|
+
export type StorePauseResult =
|
|
85
|
+
/** The store is closed on the marketplace until `until`. `externalId` is null for a switch. */
|
|
86
|
+
| { kind: "paused"; externalId: string | null; until: Date }
|
|
87
|
+
| Exclude<OutboundResult, { kind: "accepted" }>;
|
|
88
|
+
|
|
89
|
+
/** A marketplace's way of closing a store for a while. */
|
|
90
|
+
export interface MarketplaceAvailability {
|
|
91
|
+
/** How the marketplace holds a closure: an `interruption` with its own id and end, or a store-wide `switch`. */
|
|
92
|
+
readonly kind: "interruption" | "switch";
|
|
93
|
+
/**
|
|
94
|
+
* Close the store until `request.until`. Idempotent under `request.key`
|
|
95
|
+
* where the marketplace allows it (a stable id, or a list before the create).
|
|
96
|
+
*/
|
|
97
|
+
pause(ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult>;
|
|
98
|
+
/**
|
|
99
|
+
* OPTIONAL. Move the end of the closure the engine holds. Absent: the engine
|
|
100
|
+
* creates a new closure with the later end and then deletes the old one, so
|
|
101
|
+
* the store is never open in between.
|
|
102
|
+
*/
|
|
103
|
+
extend?(ctx: AdapterCallContext, ref: StorePauseRef, request: StorePauseRequest): Promise<StorePauseResult>;
|
|
104
|
+
/**
|
|
105
|
+
* Open the store: delete THIS closure, and nothing else. A closure already
|
|
106
|
+
* gone (it ended, or a person removed it) is `accepted`: there is nothing of
|
|
107
|
+
* ours left to delete.
|
|
108
|
+
*/
|
|
109
|
+
resume(ctx: AdapterCallContext, ref: StorePauseRef): Promise<OutboundResult>;
|
|
110
|
+
}
|