@12-apps/marketplace 1.3.0 → 1.5.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 +122 -1
- 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-CCWMqt2g.d.ts} +275 -3
- package/dist/{chunk-XUAFXNOH.js → chunk-FKUEFVVA.js} +396 -4
- package/dist/chunk-FKUEFVVA.js.map +1 -0
- package/dist/{chunk-RVBTARIY.js → chunk-RGMSD7S7.js} +1 -1
- package/dist/chunk-RGMSD7S7.js.map +1 -0
- package/dist/{chunk-AYYBRQJV.js → chunk-UONWZIBO.js} +43 -3
- package/dist/chunk-UONWZIBO.js.map +1 -0
- package/dist/chunk-WN2EK4KX.js +15 -0
- package/dist/chunk-WN2EK4KX.js.map +1 -0
- package/dist/{engine-CZsP8KWd.d.ts → engine-C3uq_BJd.d.ts} +252 -2
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +44 -2
- package/dist/ifood/index.js +441 -1
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +342 -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 +19 -2
- package/src/core/catalogue-read-port.ts +151 -0
- package/src/core/catalogue-read.ts +51 -0
- package/src/core/engine.ts +46 -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/catalogue-read.ts +187 -0
- package/src/ifood/catalogue-snapshot.ts +246 -0
- package/src/ifood/index.ts +9 -0
- package/src/ifood/pause.ts +257 -0
- package/src/index.ts +39 -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,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
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { AdapterCallContext, OutboundResult } from "./adapter";
|
|
2
|
+
import type { MarketplaceAvailability, StorePauseRef } from "./pause-port";
|
|
3
|
+
import type { StorePauseRow } from "./pause-store";
|
|
4
|
+
import type { EngineContext } from "./ports";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The closures a renewal replaced, still to be deleted (FUT-4851).
|
|
8
|
+
*
|
|
9
|
+
* A renewal creates the new closure first and deletes the old one after, so
|
|
10
|
+
* the store is never open in between; an old closure whose delete has not
|
|
11
|
+
* answered yet waits here. Each entry keeps the END the marketplace was given,
|
|
12
|
+
* because past it the closure is over by itself: it is then dropped without a
|
|
13
|
+
* call. A final refusal drops it too (the marketplace says there is nothing it
|
|
14
|
+
* will delete), and the list is capped at {@link RETIRED_CAP}, the oldest
|
|
15
|
+
* dropped with a log line, so a delete that keeps failing never makes every
|
|
16
|
+
* run call more.
|
|
17
|
+
*
|
|
18
|
+
* An entry names the closure by the marketplace's id or, for a create whose
|
|
19
|
+
* answer was lost, by the key it went out under (found again by the end and
|
|
20
|
+
* the reason it carried). Stored as `id:<id>@<end>` / `key:<key>@<end>`,
|
|
21
|
+
* space-separated, oldest first, in `retired_external_ids`.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** One replaced closure still to delete. */
|
|
25
|
+
interface RetiredClosure {
|
|
26
|
+
by: "id" | "key";
|
|
27
|
+
value: string;
|
|
28
|
+
/** The end the marketplace was given; null when unknown (kept until a delete answers). */
|
|
29
|
+
end: Date | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** At most this many replaced closures are kept. */
|
|
33
|
+
const RETIRED_CAP = 10;
|
|
34
|
+
|
|
35
|
+
function parse(token: string): RetiredClosure | null {
|
|
36
|
+
const at = token.lastIndexOf("@");
|
|
37
|
+
const head = at === -1 ? token : token.slice(0, at);
|
|
38
|
+
const end = at === -1 ? null : new Date(token.slice(at + 1));
|
|
39
|
+
const valid = end !== null && !Number.isNaN(end.getTime()) ? end : null;
|
|
40
|
+
if (head.startsWith("key:")) return { by: "key", value: head.slice(4), end: valid };
|
|
41
|
+
const value = head.startsWith("id:") ? head.slice(3) : head;
|
|
42
|
+
return value === "" ? null : { by: "id", value, end: valid };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The replaced closures on a record, oldest first. */
|
|
46
|
+
export function retiredOf(row: Pick<StorePauseRow, "retiredExternalIds">): RetiredClosure[] {
|
|
47
|
+
return (row.retiredExternalIds ?? "")
|
|
48
|
+
.split(" ")
|
|
49
|
+
.filter((token) => token !== "")
|
|
50
|
+
.map(parse)
|
|
51
|
+
.filter((entry): entry is RetiredClosure => entry !== null);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The column's value for a list. */
|
|
55
|
+
export function retiredValue(list: readonly RetiredClosure[]): string | null {
|
|
56
|
+
if (list.length === 0) return null;
|
|
57
|
+
return list.map((entry) => `${entry.by}:${entry.value}${entry.end ? `@${entry.end.toISOString()}` : ""}`).join(" ");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The list with one more entry, capped: the oldest beyond the cap is dropped and logged. */
|
|
61
|
+
export function withRetired(ctx: EngineContext, row: StorePauseRow, entry: RetiredClosure): RetiredClosure[] {
|
|
62
|
+
const list = [...retiredOf(row), entry];
|
|
63
|
+
const dropped = list.splice(0, Math.max(0, list.length - RETIRED_CAP));
|
|
64
|
+
for (const gone of dropped) {
|
|
65
|
+
ctx.ports.logger.warn(
|
|
66
|
+
`marketplace.availability: ${row.provider} for ${row.clientId}: more than ${RETIRED_CAP} replaced closures; ` +
|
|
67
|
+
`${gone.by} ${gone.value} is no longer deleted (it ends on its own${gone.end ? ` at ${gone.end.toISOString()}` : ""})`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
return list;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Whether a closure's own end has passed: it is over, nothing to delete. */
|
|
74
|
+
export const ended = (entry: RetiredClosure, now: Date): boolean => entry.end !== null && entry.end.getTime() <= now.getTime();
|
|
75
|
+
|
|
76
|
+
/** The ids the engine holds on the marketplace for this record: never what a key matches. */
|
|
77
|
+
export function heldIds(row: StorePauseRow): string[] {
|
|
78
|
+
const replaced = retiredOf(row).filter((entry) => entry.by === "id").map((entry) => entry.value);
|
|
79
|
+
return row.externalId === null ? replaced : [row.externalId, ...replaced];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The ref one entry is deleted by. */
|
|
83
|
+
export function refOf(entry: RetiredClosure, row: StorePauseRow, merchantId: string): StorePauseRef {
|
|
84
|
+
if (entry.by === "id") return { merchantId, externalId: entry.value, key: null, sent: null };
|
|
85
|
+
const sent = entry.end ? { until: entry.end, reason: row.reason ?? "", timeZone: row.timeZone ?? "UTC" } : null;
|
|
86
|
+
return { merchantId, externalId: null, key: entry.value, sent, keep: heldIds(row) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* During a pause, a lost create whose end is the one the current closure
|
|
91
|
+
* carries (to the second) cannot be told apart from it by end and reason:
|
|
92
|
+
* it is kept, not deleted, and goes with the resume (which deletes the
|
|
93
|
+
* current closure first) or when its end passes.
|
|
94
|
+
*/
|
|
95
|
+
const sameEndAsCurrent = (entry: RetiredClosure, row: StorePauseRow): boolean =>
|
|
96
|
+
entry.by === "key" &&
|
|
97
|
+
entry.end !== null &&
|
|
98
|
+
row.sentUntil !== null &&
|
|
99
|
+
Math.floor(entry.end.getTime() / 1000) === Math.floor(row.sentUntil.getTime() / 1000);
|
|
100
|
+
|
|
101
|
+
interface RetireEnv {
|
|
102
|
+
ctx: EngineContext;
|
|
103
|
+
availability: MarketplaceAvailability;
|
|
104
|
+
call: AdapterCallContext;
|
|
105
|
+
merchantId: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Delete every replaced closure: one past its end is dropped without a call;
|
|
110
|
+
* a delete that answered, or was refused for good, leaves the list; one with
|
|
111
|
+
* no answer stays for the next run or the sweep. Never throws for the
|
|
112
|
+
* marketplace's answer, so it never blocks a renewal. Returns the list left.
|
|
113
|
+
*/
|
|
114
|
+
export async function retire(env: RetireEnv, row: StorePauseRow): Promise<RetiredClosure[]> {
|
|
115
|
+
const left: RetiredClosure[] = [];
|
|
116
|
+
for (const entry of retiredOf(row)) {
|
|
117
|
+
if (ended(entry, env.call.now)) continue;
|
|
118
|
+
if (sameEndAsCurrent(entry, row) || (await stillOwed(env, row, entry))) left.push(entry);
|
|
119
|
+
}
|
|
120
|
+
return left;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Delete one entry; true when it stays on the list (no answer), false when it leaves (done, or refused for good). */
|
|
124
|
+
async function stillOwed(env: RetireEnv, row: StorePauseRow, entry: RetiredClosure): Promise<boolean> {
|
|
125
|
+
let result: OutboundResult;
|
|
126
|
+
try {
|
|
127
|
+
result = await env.availability.resume(env.call, refOf(entry, row, env.merchantId));
|
|
128
|
+
} catch (error) {
|
|
129
|
+
result = { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
130
|
+
}
|
|
131
|
+
if (result.kind === "accepted") return false;
|
|
132
|
+
const refused = result.kind === "refused";
|
|
133
|
+
const why = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
|
|
134
|
+
env.ctx.ports.logger.warn(
|
|
135
|
+
`marketplace.availability: ${row.provider} for ${row.clientId}: the replaced closure ${entry.by} ${entry.value} ` +
|
|
136
|
+
`was not deleted (${why})${refused ? "; dropped" : "; the sweep retries it"}`,
|
|
137
|
+
);
|
|
138
|
+
return !refused;
|
|
139
|
+
}
|