@12-apps/marketplace 1.0.0 → 1.1.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 +35 -5
- package/README.md +2 -2
- package/dist/{adapter-CgCAYBSJ.d.ts → adapter-BggtVFf9.d.ts} +6 -0
- package/dist/{chunk-OEKTWUQH.js → chunk-7BYVGNU5.js} +1 -1
- package/dist/chunk-7BYVGNU5.js.map +1 -0
- package/dist/{chunk-6OODIO3E.js → chunk-DVIRN42O.js} +325 -13
- package/dist/chunk-DVIRN42O.js.map +1 -0
- package/dist/{chunk-BEMTRJYM.js → chunk-NGNEL4HS.js} +4 -4
- package/dist/{chunk-BEMTRJYM.js.map → chunk-NGNEL4HS.js.map} +1 -1
- package/dist/{engine-DDE0mnTu.d.ts → engine-KrgZ4pA4.d.ts} +61 -17
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +4 -2
- package/dist/ifood/index.js +10 -2
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +81 -169
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +7 -0
- package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
- package/src/core/acceptance.ts +30 -14
- package/src/core/adapter.ts +6 -0
- package/src/core/cancellation-outcome.ts +92 -0
- package/src/core/cancellation.ts +46 -15
- package/src/core/decisions.ts +82 -19
- package/src/core/outbound-sweep.ts +87 -8
- package/src/core/outbound.ts +83 -7
- package/src/core/ports.ts +32 -0
- package/src/core/state.ts +6 -1
- package/src/ifood/index.ts +9 -0
- package/src/index.ts +1 -0
- package/src/server/jobs.ts +3 -2
- package/dist/chunk-6OODIO3E.js.map +0 -1
- package/dist/chunk-OEKTWUQH.js.map +0 -1
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
-- @domains: marketplace
|
|
2
|
+
-- @12-apps/marketplace: why a store's cancellation request FAILED (FUT-4758).
|
|
3
|
+
-- Additive and replay-safe, like the engine's first migration: one nullable
|
|
4
|
+
-- column, its CHECK, and an index for the expiry of requests still waiting.
|
|
5
|
+
--
|
|
6
|
+
-- `cancellation_failure_reason` is REFUSED (the marketplace said no, or every
|
|
7
|
+
-- attempt failed) or TIMEOUT (no answer inside the marketplace's window). NULL
|
|
8
|
+
-- whenever `cancellation_status` is not FAILED, and on rows from before it.
|
|
9
|
+
|
|
10
|
+
ALTER TABLE "marketplace_acceptances" ADD COLUMN IF NOT EXISTS "cancellation_failure_reason" TEXT;
|
|
11
|
+
|
|
12
|
+
DO $$ BEGIN
|
|
13
|
+
ALTER TABLE "marketplace_acceptances" ADD CONSTRAINT "marketplace_acceptances_cancellation_failure_reason_check"
|
|
14
|
+
CHECK ("cancellation_failure_reason" IS NULL
|
|
15
|
+
OR "cancellation_failure_reason" IN ('REFUSED', 'TIMEOUT'));
|
|
16
|
+
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
|
17
|
+
|
|
18
|
+
-- The expiry reads only requests still waiting on the marketplace.
|
|
19
|
+
CREATE INDEX IF NOT EXISTS "marketplace_acceptances_cancellation_waiting_idx"
|
|
20
|
+
ON "marketplace_acceptances"("cancellation_requested_at")
|
|
21
|
+
WHERE "cancellation_status" IN ('PENDING', 'REQUESTED');
|
package/src/core/acceptance.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { NO_STANDING_REQUEST } from "./cancellation";
|
|
2
|
+
import { rejectConfirmed, tellCancellationConfirmed } from "./cancellation-outcome";
|
|
1
3
|
import type { EngineContext } from "./ports";
|
|
2
4
|
import type { MarketplaceProvider } from "./types";
|
|
3
5
|
|
|
@@ -125,13 +127,16 @@ export async function expireLapsedAcceptances(
|
|
|
125
127
|
): Promise<ExpirySweepResult> {
|
|
126
128
|
const db = await ctx.ports.db();
|
|
127
129
|
const lapsed = (await db.marketplaceAcceptance.findMany({
|
|
128
|
-
|
|
130
|
+
// An order whose cancellation request waits is left to that request: its
|
|
131
|
+
// answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host
|
|
132
|
+
// never hears EXPIRED and then the confirmation for one order.
|
|
133
|
+
where: { status: "AWAITING", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
|
|
129
134
|
select: { id: true, clientId: true, orderId: true },
|
|
130
135
|
})) as { id: string; clientId: string; orderId: string }[];
|
|
131
136
|
if (lapsed.length === 0) return { expired: 0, tenants: 0 };
|
|
132
137
|
|
|
133
138
|
const result = await db.marketplaceAcceptance.updateMany({
|
|
134
|
-
where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING" },
|
|
139
|
+
where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING", ...NO_STANDING_REQUEST },
|
|
135
140
|
data: { status: "EXPIRED", acknowledgedAt: now },
|
|
136
141
|
});
|
|
137
142
|
|
|
@@ -158,10 +163,17 @@ export async function expireLapsedAcceptances(
|
|
|
158
163
|
*
|
|
159
164
|
* Terminal on the acceptance side whatever state it was in. A cancellation
|
|
160
165
|
* request the store made is answered: CONFIRMED, from PENDING, REQUESTED or
|
|
161
|
-
* FAILED (a refusal followed by a cancellation is still a cancellation)
|
|
162
|
-
*
|
|
166
|
+
* FAILED (a refusal followed by a cancellation is still a cancellation), and
|
|
167
|
+
* the host hears it through `onCancellationConfirmed` when it has one;
|
|
168
|
+
* otherwise, and for a cancellation the store never asked for,
|
|
169
|
+
* `onRefused(…, "CANCELLED")`. Returns false when no acceptance stands for this external order — a
|
|
163
170
|
* cancellation can outrun the placement it refers to.
|
|
164
171
|
*/
|
|
172
|
+
/** Whether the host takes a confirmed request through `onCancellationConfirmed` (FUT-4758). */
|
|
173
|
+
function hasConfirmHook(ctx: EngineContext): boolean {
|
|
174
|
+
return ctx.ports.order.onCancellationConfirmed !== undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
165
177
|
export async function cancelAcceptance(
|
|
166
178
|
ctx: EngineContext,
|
|
167
179
|
input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string; now?: Date },
|
|
@@ -173,24 +185,28 @@ export async function cancelAcceptance(
|
|
|
173
185
|
provider: input.provider,
|
|
174
186
|
externalOrderId: input.externalOrderId,
|
|
175
187
|
},
|
|
176
|
-
select: { orderId: true },
|
|
177
|
-
})) as { orderId: string } | null;
|
|
188
|
+
select: { orderId: true, cancellationStatus: true },
|
|
189
|
+
})) as { orderId: string; cancellationStatus: string | null } | null;
|
|
178
190
|
if (!row) return false;
|
|
179
191
|
|
|
180
192
|
// The two stamps commit together: a cancelled order never shows a request
|
|
181
193
|
// still PENDING. The host's cancel runs after; if it throws, the inbox row
|
|
182
194
|
// is FAILED and the retry sweep re-runs this, whose stamps are idempotent.
|
|
183
|
-
await ctx.ports.transaction(async (tx) => {
|
|
184
|
-
await tx.
|
|
185
|
-
|
|
186
|
-
data: { status: "REJECTED", acknowledgedAt: input.now ?? ctx.ports.clock.now() },
|
|
187
|
-
});
|
|
188
|
-
await tx.marketplaceAcceptance.updateMany({
|
|
195
|
+
const answered = await ctx.ports.transaction(async (tx) => {
|
|
196
|
+
await rejectConfirmed(tx, row.orderId, input.now ?? ctx.ports.clock.now());
|
|
197
|
+
const confirmed = await tx.marketplaceAcceptance.updateMany({
|
|
189
198
|
where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "REQUESTED", "FAILED"] } },
|
|
190
|
-
data: { cancellationStatus: "CONFIRMED" },
|
|
199
|
+
data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null },
|
|
191
200
|
});
|
|
201
|
+
return confirmed.count > 0;
|
|
192
202
|
});
|
|
193
|
-
|
|
203
|
+
// The store's own request, answered (FUT-4758): a host that cancels on the
|
|
204
|
+
// confirmation hears it as such; any other cancellation is the marketplace's.
|
|
205
|
+
// A redelivered confirmation of a request already answered tells a host
|
|
206
|
+
// with the callback nothing more (it heard the first one).
|
|
207
|
+
const storeAsked = answered || row.cancellationStatus === "CONFIRMED";
|
|
208
|
+
const told = storeAsked && (answered ? await tellCancellationConfirmed(ctx, input.clientId, row.orderId) : hasConfirmHook(ctx));
|
|
209
|
+
if (!told) await ctx.ports.order.onRefused(input.clientId, row.orderId, "CANCELLED");
|
|
194
210
|
ctx.ports.publishChanged(input.clientId);
|
|
195
211
|
return true;
|
|
196
212
|
}
|
package/src/core/adapter.ts
CHANGED
|
@@ -70,6 +70,12 @@ export interface MarketplaceCapabilities {
|
|
|
70
70
|
perOrderAppLink: boolean;
|
|
71
71
|
/** Confirming states a preparation time. */
|
|
72
72
|
confirmTakesPreparationTime: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* OPTIONAL. How long the marketplace takes, at most, to answer a store's
|
|
75
|
+
* cancellation request, in milliseconds: past it the outbound sweep fails
|
|
76
|
+
* the request as TIMEOUT. Absent: only the 24-hour give-up applies.
|
|
77
|
+
*/
|
|
78
|
+
cancellationAnswerWindowMs?: number;
|
|
73
79
|
}
|
|
74
80
|
|
|
75
81
|
/** One reason a store may give for refusing or cancelling an order. */
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { MarketplaceAdapter } from "./adapter";
|
|
2
|
+
import type { CancellationFailureReason, EngineContext, MarketplaceDb } from "./ports";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* How the store's own cancellation request ENDS, told to the host (FUT-4758).
|
|
6
|
+
*
|
|
7
|
+
* A host that requests first and cancels only on the marketplace's answer
|
|
8
|
+
* needs both ends: the confirmation, to run its cancel, and the failure, to
|
|
9
|
+
* put the pedido back in a person's hands. Both are optional order-port
|
|
10
|
+
* callbacks, so a 1.0.0 host compiles and behaves unchanged. Each is called by
|
|
11
|
+
* whichever path moved the row (the outbound job, the marketplace's event, the
|
|
12
|
+
* sweep's expiry), once, and a host failure is logged, never rethrown: the
|
|
13
|
+
* row's stamp has committed, and a host that fails its half must not undo it.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
async function tell(ctx: EngineContext, what: string, orderId: string, call: () => Promise<void>): Promise<void> {
|
|
17
|
+
try {
|
|
18
|
+
await call();
|
|
19
|
+
} catch (error) {
|
|
20
|
+
ctx.ports.logger.error(
|
|
21
|
+
`marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` +
|
|
22
|
+
(error instanceof Error ? error.message : String(error)),
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Whether the host REQUESTS FIRST and cancels on the marketplace's
|
|
29
|
+
* confirmation: it binds `onCancellationConfirmed` (FUT-4758). A host that
|
|
30
|
+
* does not keeps 1.0.0's behaviour exactly — the store's cancel is stamped
|
|
31
|
+
* REJECTED at request time and `onRefused` runs then.
|
|
32
|
+
*/
|
|
33
|
+
export function requestsFirst(ctx: EngineContext): boolean {
|
|
34
|
+
return ctx.ports.order.onCancellationConfirmed !== undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Move a row whose cancellation was just confirmed off the clock: REJECTED,
|
|
39
|
+
* acknowledged now when it was still AWAITING (the table's CHECK pairs the
|
|
40
|
+
* two); an accepted row keeps its acceptance instant.
|
|
41
|
+
*/
|
|
42
|
+
export async function rejectConfirmed(db: MarketplaceDb, orderId: string, now: Date): Promise<void> {
|
|
43
|
+
await db.marketplaceAcceptance.updateMany({
|
|
44
|
+
where: { orderId, status: "AWAITING" },
|
|
45
|
+
data: { status: "REJECTED", acknowledgedAt: now },
|
|
46
|
+
});
|
|
47
|
+
await db.marketplaceAcceptance.updateMany({
|
|
48
|
+
where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
|
|
49
|
+
data: { status: "REJECTED" },
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The store's confirmed request, told to the host: `onCancellationConfirmed`
|
|
55
|
+
* when bound, else `onRefused(…, "CANCELLED")` as in 1.0.0.
|
|
56
|
+
*/
|
|
57
|
+
export async function confirmedToHost(ctx: EngineContext, clientId: string, orderId: string): Promise<void> {
|
|
58
|
+
if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
|
|
59
|
+
await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The marketplace confirmed the store's request. Returns whether the host took it (it has the callback). */
|
|
63
|
+
export async function tellCancellationConfirmed(ctx: EngineContext, clientId: string, orderId: string): Promise<boolean> {
|
|
64
|
+
const hook = ctx.ports.order.onCancellationConfirmed;
|
|
65
|
+
if (!hook) return false;
|
|
66
|
+
await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The store's request failed, refused or timed out. */
|
|
71
|
+
export async function tellCancellationFailed(
|
|
72
|
+
ctx: EngineContext,
|
|
73
|
+
clientId: string,
|
|
74
|
+
orderId: string,
|
|
75
|
+
reason: CancellationFailureReason,
|
|
76
|
+
): Promise<void> {
|
|
77
|
+
const hook = ctx.ports.order.onCancellationFailed;
|
|
78
|
+
if (!hook) return;
|
|
79
|
+
await tell(ctx, `had its cancellation request fail (${reason})`, orderId, () =>
|
|
80
|
+
hook.call(ctx.ports.order, clientId, orderId, reason),
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** How long a request to this adapter may wait for its answer: the engine's override, else the adapter's own. */
|
|
85
|
+
export function cancellationWindowMs(ctx: EngineContext, adapter: MarketplaceAdapter): number | null {
|
|
86
|
+
return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The columns a request that FAILED for `reason` writes. */
|
|
90
|
+
export function failedRequestData(reason: CancellationFailureReason): Record<string, unknown> {
|
|
91
|
+
return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
|
|
92
|
+
}
|
package/src/core/cancellation.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
|
|
2
2
|
import type { CancellationReason, MarketplaceAdapter } from "./adapter";
|
|
3
|
+
import { failedRequestData, tellCancellationFailed } from "./cancellation-outcome";
|
|
3
4
|
import type { EngineContext } from "./ports";
|
|
4
5
|
import { resolveReason } from "./registry";
|
|
5
6
|
import type { MarketplaceProvider } from "./types";
|
|
@@ -9,13 +10,24 @@ import type { MarketplaceProvider } from "./types";
|
|
|
9
10
|
* the marketplace. Lives on the acceptance row:
|
|
10
11
|
*
|
|
11
12
|
* null ──refuse/cancel──▶ PENDING ──job 2xx──▶ REQUESTED ──event──▶ CONFIRMED
|
|
12
|
-
* │
|
|
13
|
+
* │ ├──job 4xx / last attempt / event──▶ FAILED (REFUSED) ──event──▶ CONFIRMED
|
|
14
|
+
* │ └──past the window (sweep)──▶ FAILED (TIMEOUT)
|
|
13
15
|
* └──event (the marketplace cancelled)──▶ CONFIRMED
|
|
14
16
|
*
|
|
15
17
|
* CONFIRMED is terminal; every write is predicated on the statuses it may come
|
|
16
|
-
* from, so an out-of-order event cannot undo it.
|
|
18
|
+
* from, so an out-of-order event cannot undo it. A FAILED request stands for
|
|
19
|
+
* nothing: the order may be decided again, or the cancellation asked again
|
|
20
|
+
* (FUT-4758: a refused or timed-out request leaves the order as it was).
|
|
17
21
|
*/
|
|
18
22
|
|
|
23
|
+
/** No request of the store's is waiting on the marketplace: never asked, or asked and FAILED. */
|
|
24
|
+
function noStandingRequest(cancellationStatus: string | null): boolean {
|
|
25
|
+
return cancellationStatus === null || cancellationStatus === "FAILED";
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The same, as the `where` a claim is predicated on. */
|
|
29
|
+
export const NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] } as const;
|
|
30
|
+
|
|
19
31
|
/** Why a decision (or a store cancellation) was refused. Vocabulary, not copy. */
|
|
20
32
|
export type DecisionProblemCode =
|
|
21
33
|
| "DUPLICATE"
|
|
@@ -64,7 +76,7 @@ export function notPendingProblem(
|
|
|
64
76
|
allowed: readonly string[] = ["AWAITING"],
|
|
65
77
|
): DecisionProblem | null {
|
|
66
78
|
if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
|
|
67
|
-
if (allowed.includes(row.status) && row.cancellationStatus
|
|
79
|
+
if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
|
|
68
80
|
const status = row.status as AcceptanceStatus;
|
|
69
81
|
return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
|
|
70
82
|
}
|
|
@@ -148,28 +160,47 @@ export function refusalData(plan: CancellationPlan, fromStatus: string, now: Dat
|
|
|
148
160
|
cancellationReasonCode: plan.reason?.code ?? null,
|
|
149
161
|
cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
|
|
150
162
|
cancellationRequestedAt: plan.status === "PENDING" ? now : null,
|
|
163
|
+
cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The columns the store's own cancellation REQUEST writes (FUT-4758): the
|
|
169
|
+
* request alone. The decision status stays as it is (AWAITING or ACCEPTED)
|
|
170
|
+
* while the marketplace answers, so a refused or timed-out request leaves the
|
|
171
|
+
* order acceptable and still on the acceptance clock; only the marketplace's
|
|
172
|
+
* confirmation moves it to REJECTED.
|
|
173
|
+
*/
|
|
174
|
+
export function requestData(plan: CancellationPlan, now: Date): Record<string, unknown> {
|
|
175
|
+
return {
|
|
176
|
+
cancellationStatus: plan.status,
|
|
177
|
+
cancellationReasonCode: plan.reason?.code ?? null,
|
|
178
|
+
cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
|
|
179
|
+
cancellationRequestedAt: plan.status === "PENDING" ? now : null,
|
|
180
|
+
cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null,
|
|
151
181
|
};
|
|
152
182
|
}
|
|
153
183
|
|
|
154
184
|
/**
|
|
155
|
-
* The marketplace refused the store's cancellation request. FAILED,
|
|
156
|
-
* PENDING or REQUESTED only: CONFIRMED is terminal, so a refusal arriving
|
|
157
|
-
* after the cancellation changes nothing.
|
|
185
|
+
* The marketplace refused the store's cancellation request. FAILED (REFUSED),
|
|
186
|
+
* from PENDING or REQUESTED only: CONFIRMED is terminal, so a refusal arriving
|
|
187
|
+
* after the cancellation changes nothing. The host hears it once, from the
|
|
188
|
+
* call that moved the row. Returns whether a row moved.
|
|
158
189
|
*/
|
|
159
190
|
export async function failCancellationRequest(
|
|
160
191
|
ctx: EngineContext,
|
|
161
192
|
input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
|
|
162
193
|
): Promise<boolean> {
|
|
163
194
|
const db = await ctx.ports.db();
|
|
195
|
+
const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };
|
|
196
|
+
const row = (await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } })) as { orderId: string } | null;
|
|
197
|
+
if (!row) return false;
|
|
164
198
|
const moved = await db.marketplaceAcceptance.updateMany({
|
|
165
|
-
where: {
|
|
166
|
-
|
|
167
|
-
provider: input.provider,
|
|
168
|
-
externalOrderId: input.externalOrderId,
|
|
169
|
-
cancellationStatus: { in: ["PENDING", "REQUESTED"] },
|
|
170
|
-
},
|
|
171
|
-
data: { cancellationStatus: "FAILED" },
|
|
199
|
+
where: { ...where, cancellationStatus: { in: ["PENDING", "REQUESTED"] } },
|
|
200
|
+
data: failedRequestData("REFUSED"),
|
|
172
201
|
});
|
|
173
|
-
if (moved.count
|
|
174
|
-
|
|
202
|
+
if (moved.count === 0) return false;
|
|
203
|
+
ctx.ports.publishChanged(input.clientId);
|
|
204
|
+
await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
|
|
205
|
+
return true;
|
|
175
206
|
}
|
package/src/core/decisions.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
|
|
2
2
|
import {
|
|
3
3
|
CLAIM_SELECT,
|
|
4
|
+
NO_STANDING_REQUEST,
|
|
4
5
|
notPendingProblem,
|
|
5
6
|
planCancellation,
|
|
6
7
|
refusalData,
|
|
8
|
+
requestData,
|
|
7
9
|
type CancellationPlan,
|
|
8
10
|
type ClaimRow,
|
|
9
11
|
type DecisionProblem,
|
|
10
12
|
type DecisionProblemCode,
|
|
11
13
|
} from "./cancellation";
|
|
14
|
+
import { requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
|
|
12
15
|
import { enqueueOutbound } from "./outbound-queue";
|
|
13
16
|
import type { EngineContext, MarketplaceAdmission, MarketplaceDb } from "./ports";
|
|
14
17
|
|
|
@@ -51,10 +54,14 @@ export type DecisionInput =
|
|
|
51
54
|
offendingSkus?: readonly string[];
|
|
52
55
|
};
|
|
53
56
|
|
|
54
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* One decided row. `status` is the row's status after the call: ACCEPTED or
|
|
59
|
+
* REJECTED, or — for a refusal of a host that requests first (FUT-4758) —
|
|
60
|
+
* the status it keeps (AWAITING, ACCEPTED) while `cancellation` waits.
|
|
61
|
+
*/
|
|
55
62
|
export interface DecidedRow {
|
|
56
63
|
orderId: string;
|
|
57
|
-
status:
|
|
64
|
+
status: AcceptanceStatus;
|
|
58
65
|
cancellation: CancellationStatus | null;
|
|
59
66
|
reasonCode: string | null;
|
|
60
67
|
offendingSkus: string[];
|
|
@@ -88,6 +95,8 @@ interface PlannedDecision {
|
|
|
88
95
|
row: ClaimRow;
|
|
89
96
|
data: Record<string, unknown>;
|
|
90
97
|
decided: DecidedRow;
|
|
98
|
+
/** A refusal that only REQUESTS the cancellation: the host cancels on the marketplace's confirmation. */
|
|
99
|
+
requestOnly: boolean;
|
|
91
100
|
}
|
|
92
101
|
|
|
93
102
|
/** Thrown inside the transaction to roll it back, carrying the reason. */
|
|
@@ -108,10 +117,11 @@ function duplicateProblems(decisions: readonly DecisionInput[]): DecisionProblem
|
|
|
108
117
|
});
|
|
109
118
|
}
|
|
110
119
|
|
|
111
|
-
function decidedOf(input: DecisionInput, plan: CancellationPlan | null): DecidedRow {
|
|
120
|
+
function decidedOf(input: DecisionInput, plan: CancellationPlan | null, keptStatus?: string): DecidedRow {
|
|
121
|
+
const decided: AcceptanceStatus = input.decision === "ACCEPT" ? "ACCEPTED" : "REJECTED";
|
|
112
122
|
return {
|
|
113
123
|
orderId: input.orderId,
|
|
114
|
-
status:
|
|
124
|
+
status: (keptStatus as AcceptanceStatus | undefined) ?? decided,
|
|
115
125
|
cancellation: plan?.status ?? null,
|
|
116
126
|
reasonCode: plan?.reason?.code ?? null,
|
|
117
127
|
offendingSkus: plan?.skus ?? [],
|
|
@@ -119,6 +129,15 @@ function decidedOf(input: DecisionInput, plan: CancellationPlan | null): Decided
|
|
|
119
129
|
}
|
|
120
130
|
|
|
121
131
|
/** Plan one decision against its row, or name what is wrong with it. */
|
|
132
|
+
/** The columns of a request that no longer stands, cleared. */
|
|
133
|
+
const CLEARED_REQUEST = {
|
|
134
|
+
cancellationStatus: null,
|
|
135
|
+
cancellationReasonCode: null,
|
|
136
|
+
cancellationOffendingSkus: null,
|
|
137
|
+
cancellationRequestedAt: null,
|
|
138
|
+
cancellationFailureReason: null,
|
|
139
|
+
} as const;
|
|
140
|
+
|
|
122
141
|
function planOne(
|
|
123
142
|
ctx: EngineContext,
|
|
124
143
|
input: DecisionInput,
|
|
@@ -130,12 +149,32 @@ function planOne(
|
|
|
130
149
|
const stale = notPendingProblem(row, path);
|
|
131
150
|
if (stale || !row) return stale ? [stale] : [];
|
|
132
151
|
if (input.decision === "ACCEPT") {
|
|
133
|
-
|
|
134
|
-
|
|
152
|
+
// An accept after a FAILED request (FUT-4758) leaves no request behind it.
|
|
153
|
+
const data = {
|
|
154
|
+
status: "ACCEPTED",
|
|
155
|
+
acknowledgedAt: now,
|
|
156
|
+
preparationMinutes: input.preparationMinutes ?? null,
|
|
157
|
+
...(row.cancellationStatus === null ? {} : CLEARED_REQUEST),
|
|
158
|
+
};
|
|
159
|
+
return { input, index, row, data, decided: decidedOf(input, null), requestOnly: false };
|
|
135
160
|
}
|
|
136
161
|
const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);
|
|
137
162
|
if (Array.isArray(plan)) return plan;
|
|
138
|
-
|
|
163
|
+
if (requestOnly(ctx, plan)) {
|
|
164
|
+
return { input, index, row, data: requestData(plan, now), decided: decidedOf(input, plan, row.status), requestOnly: true };
|
|
165
|
+
}
|
|
166
|
+
return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan), requestOnly: false };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Whether a refusal only REQUESTS the cancellation (FUT-4758): the host
|
|
171
|
+
* requests first (it binds `onCancellationConfirmed`), and there is a request
|
|
172
|
+
* to make — PENDING, or FAILED at once for a marketplace that cannot take it
|
|
173
|
+
* through its API (a person cancels in its app, and its event confirms). A
|
|
174
|
+
* provider with no adapter has nothing to ask: refused at once, as ever.
|
|
175
|
+
*/
|
|
176
|
+
function requestOnly(ctx: EngineContext, plan: CancellationPlan): boolean {
|
|
177
|
+
return requestsFirst(ctx) && plan.status !== null;
|
|
139
178
|
}
|
|
140
179
|
|
|
141
180
|
/** Admit every decision through the host, then claim every row, in one transaction. */
|
|
@@ -164,7 +203,7 @@ async function admitAndClaim(
|
|
|
164
203
|
if (refused.length > 0) throw new Rollback(refused);
|
|
165
204
|
for (const one of planned) {
|
|
166
205
|
const claimed = await tx.marketplaceAcceptance.updateMany({
|
|
167
|
-
where: { orderId: one.input.orderId, clientId, status: "AWAITING" },
|
|
206
|
+
where: { orderId: one.input.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
|
|
168
207
|
data: one.data,
|
|
169
208
|
});
|
|
170
209
|
if (claimed.count === 0) refused.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
|
|
@@ -178,14 +217,17 @@ async function admitAndClaim(
|
|
|
178
217
|
async function afterCommit(ctx: EngineContext, clientId: string, planned: readonly PlannedDecision[]): Promise<void> {
|
|
179
218
|
for (const one of planned) {
|
|
180
219
|
const { orderId } = one.input;
|
|
181
|
-
if (one.
|
|
220
|
+
if (one.input.decision === "ACCEPT") {
|
|
182
221
|
await enqueueOutbound(ctx, { clientId, orderId, action: "confirm" }, one.row.provider);
|
|
183
222
|
} else if (one.decided.cancellation === "PENDING") {
|
|
184
223
|
await enqueueOutbound(ctx, { clientId, orderId, action: "requestCancellation" }, one.row.provider);
|
|
185
224
|
}
|
|
186
225
|
try {
|
|
187
|
-
if (one.decided.status === "ACCEPTED") await ctx.ports.order.onAccepted(clientId, orderId);
|
|
188
|
-
else await ctx.ports.order.onRefused(clientId, orderId, "REJECTED");
|
|
226
|
+
if (one.decided.status === "ACCEPTED" && one.input.decision === "ACCEPT") await ctx.ports.order.onAccepted(clientId, orderId);
|
|
227
|
+
else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, "REJECTED");
|
|
228
|
+
// A request the marketplace cannot take through its API failed at once:
|
|
229
|
+
// the order stays, and a person cancels it in the marketplace's app.
|
|
230
|
+
else if (one.decided.cancellation === "FAILED") await tellCancellationFailed(ctx, clientId, orderId, "REFUSED");
|
|
189
231
|
} catch (error) {
|
|
190
232
|
ctx.ports.logger.error(
|
|
191
233
|
`marketplace.decide: order ${orderId} is ${one.decided.status} but the host's half failed: ` +
|
|
@@ -271,13 +313,22 @@ export async function decideOne(
|
|
|
271
313
|
}
|
|
272
314
|
|
|
273
315
|
/**
|
|
274
|
-
* The STORE
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
316
|
+
* The STORE asks to cancel an order — before or after accepting it. Stamps
|
|
317
|
+
* the request the marketplace must hear and queues it; the engine neither
|
|
318
|
+
* admits nor calls `onRefused`: it records and queues, and nothing else.
|
|
319
|
+
*
|
|
320
|
+
* REQUEST FIRST (FUT-4758), for a host that binds `onCancellationConfirmed`:
|
|
321
|
+
* only the request moves. The decision status stays AWAITING or ACCEPTED while
|
|
322
|
+
* the marketplace answers, so the host keeps the order as it was until then,
|
|
323
|
+
* and a refused or timed-out request (`onCancellationFailed`) leaves it
|
|
324
|
+
* acceptable. The marketplace's confirmation moves it to REJECTED. A FAILED
|
|
325
|
+
* request may be asked again. A host that binds no `onCancellationConfirmed`
|
|
326
|
+
* cancelled first and gets 1.0.0's stamps exactly: REJECTED at once.
|
|
327
|
+
*
|
|
328
|
+
* The returned row's `status` is the row's after the call.
|
|
278
329
|
*
|
|
279
330
|
* `stale` (ALREADY_DECIDED) when the marketplace already cancelled it, the
|
|
280
|
-
* clock lapsed (EXPIRED), or a request
|
|
331
|
+
* clock lapsed (EXPIRED), or a request is already waiting.
|
|
281
332
|
*/
|
|
282
333
|
export async function recordStoreCancellation(
|
|
283
334
|
ctx: EngineContext,
|
|
@@ -289,16 +340,28 @@ export async function recordStoreCancellation(
|
|
|
289
340
|
const plan = planCancellation(ctx.registry.get(row.provider), input, row, []);
|
|
290
341
|
if (Array.isArray(plan)) return resultOfProblem(plan[0]!);
|
|
291
342
|
|
|
343
|
+
return claimStoreCancellation(ctx, input, row, plan);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Stamp the store's cancellation (the request alone, or 1.0.0's REJECTED), queue it, and tell the host. */
|
|
347
|
+
async function claimStoreCancellation(
|
|
348
|
+
ctx: EngineContext,
|
|
349
|
+
input: { clientId: string; orderId: string; now?: Date },
|
|
350
|
+
row: ClaimRow,
|
|
351
|
+
plan: CancellationPlan,
|
|
352
|
+
): Promise<DecisionResult> {
|
|
292
353
|
const now = input.now ?? ctx.ports.clock.now();
|
|
293
354
|
const db = await ctx.ports.db();
|
|
355
|
+
const only = requestOnly(ctx, plan);
|
|
294
356
|
const claimed = await db.marketplaceAcceptance.updateMany({
|
|
295
|
-
where: { orderId: input.orderId, clientId: input.clientId, status: row.status,
|
|
296
|
-
data: refusalData(plan, row.status, now),
|
|
357
|
+
where: { orderId: input.orderId, clientId: input.clientId, status: row.status, ...NO_STANDING_REQUEST },
|
|
358
|
+
data: only ? requestData(plan, now) : refusalData(plan, row.status, now),
|
|
297
359
|
});
|
|
298
360
|
if (claimed.count === 0) return { kind: "stale", reason: "CONFLICT", status: null };
|
|
299
361
|
if (plan.status === "PENDING") {
|
|
300
362
|
await enqueueOutbound(ctx, { clientId: input.clientId, orderId: input.orderId, action: "requestCancellation" }, row.provider);
|
|
301
363
|
}
|
|
302
364
|
ctx.ports.publishChanged(input.clientId);
|
|
303
|
-
|
|
365
|
+
if (only && plan.status === "FAILED") await tellCancellationFailed(ctx, input.clientId, input.orderId, "REFUSED");
|
|
366
|
+
return { kind: "decided", ...decidedOf({ orderId: input.orderId, decision: "REJECT" }, plan, only ? row.status : undefined) };
|
|
304
367
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { NO_STANDING_REQUEST } from "./cancellation";
|
|
2
|
+
import { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
|
|
1
3
|
import { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from "./outbound-queue";
|
|
2
4
|
import type { EngineContext } from "./ports";
|
|
3
5
|
|
|
@@ -14,12 +16,27 @@ import type { EngineContext } from "./ports";
|
|
|
14
16
|
* - younger than {@link OUTBOUND_STALE_MS}: the original job may still be
|
|
15
17
|
* retrying, so it is left alone;
|
|
16
18
|
* - older than {@link OUTBOUND_GIVE_UP_MS}: a marketplace has long since
|
|
17
|
-
* settled the order on its own clock. A
|
|
18
|
-
* FAILED (a person finishes it on the marketplace, through
|
|
19
|
+
* settled the order on its own clock. A request still waiting that old is
|
|
20
|
+
* stamped FAILED, TIMEOUT (a person finishes it on the marketplace, through
|
|
21
|
+
* the app link),
|
|
19
22
|
* and an accept that old is never confirmed — which is also what keeps a
|
|
20
23
|
* host's ACCEPTED history from before this engine from being confirmed on
|
|
21
24
|
* the first pass.
|
|
22
25
|
*
|
|
26
|
+
* For a host that REQUESTS FIRST (it binds `onCancellationConfirmed`; a 1.0.0
|
|
27
|
+
* host keeps the re-queue and the give-up below, unchanged), and before
|
|
28
|
+
* anything else, a store's cancellation request still waiting (PENDING:
|
|
29
|
+
* never delivered, or REQUESTED: delivered and unanswered) past its
|
|
30
|
+
* marketplace's answer window — the engine's `cancellationWindowMs`, else the
|
|
31
|
+
* adapter's `cancellationAnswerWindowMs`, counted from the request — is FAILED
|
|
32
|
+
* as TIMEOUT, and the host hears it through `onCancellationFailed` (FUT-4758,
|
|
33
|
+
* the owner: "it cannot stay in that state with nothing happening"). The
|
|
34
|
+
* store then cancels in the marketplace's own app. A PENDING request's
|
|
35
|
+
* retries stop with it: the job re-reads the row and sends only from PENDING,
|
|
36
|
+
* a run that starts past the window ends TIMEOUT itself without calling, and
|
|
37
|
+
* this sweep re-queues no FAILED row. The window is read at the sweep's own
|
|
38
|
+
* cadence, so a request ends between the window and the window plus one pass.
|
|
39
|
+
*
|
|
23
40
|
* Re-queued under a key of its own per pass: a queue keeps a finished job's id
|
|
24
41
|
* and would swallow a re-queue under the job's plain key. The job itself is
|
|
25
42
|
* idempotent by the row, so a duplicate run calls nobody twice.
|
|
@@ -34,9 +51,15 @@ export const OUTBOUND_GIVE_UP_MS = 24 * 60 * 60_000;
|
|
|
34
51
|
/** What one sweep pass did. */
|
|
35
52
|
export interface OutboundSweepResult {
|
|
36
53
|
requeued: number;
|
|
54
|
+
/** Requests still waiting past {@link OUTBOUND_GIVE_UP_MS}, failed as TIMEOUT. */
|
|
37
55
|
givenUp: number;
|
|
56
|
+
/** Requests failed as TIMEOUT past their marketplace's answer window. */
|
|
57
|
+
timedOut: number;
|
|
38
58
|
}
|
|
39
59
|
|
|
60
|
+
/** A store's cancellation request still waiting on the marketplace. */
|
|
61
|
+
const WAITING = ["PENDING", "REQUESTED"];
|
|
62
|
+
|
|
40
63
|
interface OwedRow {
|
|
41
64
|
clientId: string;
|
|
42
65
|
orderId: string;
|
|
@@ -60,15 +83,69 @@ async function requeue(ctx: EngineContext, rows: readonly OwedRow[], action: Out
|
|
|
60
83
|
}
|
|
61
84
|
|
|
62
85
|
/** Re-queue every owed call older than the job's retry span; give up on the ancient ones. */
|
|
86
|
+
/**
|
|
87
|
+
* Fail as TIMEOUT every request in `rows` still waiting, one predicated write
|
|
88
|
+
* each, so a confirmation that lands meanwhile wins and its host hears nothing
|
|
89
|
+
* twice. Returns how many moved.
|
|
90
|
+
*/
|
|
91
|
+
export async function failAsTimeout(ctx: EngineContext, rows: readonly OwedRow[]): Promise<number> {
|
|
92
|
+
const db = await ctx.ports.db();
|
|
93
|
+
let failed = 0;
|
|
94
|
+
for (const row of rows) {
|
|
95
|
+
const moved = await db.marketplaceAcceptance.updateMany({
|
|
96
|
+
where: { orderId: row.orderId, clientId: row.clientId, cancellationStatus: { in: WAITING } },
|
|
97
|
+
data: failedRequestData("TIMEOUT"),
|
|
98
|
+
});
|
|
99
|
+
if (moved.count === 0) continue;
|
|
100
|
+
failed += 1;
|
|
101
|
+
ctx.ports.publishChanged(row.clientId);
|
|
102
|
+
await tellCancellationFailed(ctx, row.clientId, row.orderId, "TIMEOUT");
|
|
103
|
+
}
|
|
104
|
+
return failed;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Every request in `statuses` since before `cutoff`, for one provider or all. */
|
|
108
|
+
async function waitingSince(
|
|
109
|
+
ctx: EngineContext,
|
|
110
|
+
cutoff: Date,
|
|
111
|
+
statuses: readonly string[],
|
|
112
|
+
provider?: string,
|
|
113
|
+
): Promise<OwedRow[]> {
|
|
114
|
+
const db = await ctx.ports.db();
|
|
115
|
+
return (await db.marketplaceAcceptance.findMany({
|
|
116
|
+
where: { ...(provider ? { provider } : {}), cancellationStatus: { in: statuses }, cancellationRequestedAt: { lt: cutoff } },
|
|
117
|
+
select: OWED_SELECT,
|
|
118
|
+
})) as OwedRow[];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Fail every request still waiting past its marketplace's window; no window, only the give-up. */
|
|
122
|
+
async function expireUnanswered(ctx: EngineContext, now: Date): Promise<number> {
|
|
123
|
+
// Only for a host that requests first: a 1.0.0 host (it cancelled already)
|
|
124
|
+
// keeps the re-queue and the 24-hour give-up exactly as before.
|
|
125
|
+
if (!requestsFirst(ctx)) return 0;
|
|
126
|
+
let expired = 0;
|
|
127
|
+
for (const provider of ctx.registry.providers()) {
|
|
128
|
+
const adapter = ctx.registry.get(provider);
|
|
129
|
+
const window = adapter ? cancellationWindowMs(ctx, adapter) : null;
|
|
130
|
+
if (window === null) continue;
|
|
131
|
+
const cutoff = new Date(now.getTime() - window);
|
|
132
|
+
expired += await failAsTimeout(ctx, await waitingSince(ctx, cutoff, WAITING, provider));
|
|
133
|
+
}
|
|
134
|
+
return expired;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* One sweep pass: expire the requests nobody answered, give up on the very old,
|
|
139
|
+
* and re-queue what is still owed.
|
|
140
|
+
*/
|
|
63
141
|
export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<OutboundSweepResult> {
|
|
64
142
|
const db = await ctx.ports.db();
|
|
65
143
|
const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
|
|
66
144
|
const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
|
|
67
145
|
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
});
|
|
146
|
+
const timedOut = await expireUnanswered(ctx, now);
|
|
147
|
+
// 1.0.0 gave up on PENDING requests only; a host that requests first, on any still waiting.
|
|
148
|
+
const givenUp = await failAsTimeout(ctx, await waitingSince(ctx, giveUp, requestsFirst(ctx) ? WAITING : ["PENDING"]));
|
|
72
149
|
const cancellations = (await db.marketplaceAcceptance.findMany({
|
|
73
150
|
where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: stale, gte: giveUp } },
|
|
74
151
|
select: OWED_SELECT,
|
|
@@ -79,12 +156,14 @@ export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<Outb
|
|
|
79
156
|
confirmedAt: null,
|
|
80
157
|
confirmFailedAt: null,
|
|
81
158
|
acknowledgedAt: { lt: stale, gte: giveUp },
|
|
159
|
+
// An accept the store asked to cancel is not confirmed while the request waits.
|
|
160
|
+
...NO_STANDING_REQUEST,
|
|
82
161
|
},
|
|
83
162
|
select: OWED_SELECT,
|
|
84
163
|
})) as OwedRow[];
|
|
85
164
|
|
|
86
165
|
const requeued =
|
|
87
166
|
(await requeue(ctx, cancellations, "requestCancellation", now)) + (await requeue(ctx, confirms, "confirm", now));
|
|
88
|
-
if (
|
|
89
|
-
return { requeued, givenUp
|
|
167
|
+
if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
|
|
168
|
+
return { requeued, givenUp, timedOut };
|
|
90
169
|
}
|