@tokenoftrust/storefront-runner 6.17.1 → 7.0.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.
@@ -123,6 +123,42 @@ export async function installMayProcess(
123
123
  return row?.ok === 1;
124
124
  }
125
125
 
126
+ /** Why an install on this tenant cannot be its processor. */
127
+ export type ProcessorIneligibility = "install-inactive" | "webhook-endpoint-missing" | "processor-scope-missing";
128
+
129
+ /**
130
+ * Why `installId` cannot be the processor for `tenantId`: `not-found` when the tenant has no such
131
+ * unmanaged install, otherwise each unmet condition of {@link installMayProcess}. An eligible install
132
+ * yields an empty list.
133
+ */
134
+ export async function processorIneligibility(
135
+ db: Pick<FulfillmentDatabase, "get">,
136
+ tenantId: string,
137
+ installId: string,
138
+ ): Promise<"not-found" | ProcessorIneligibility[]> {
139
+ const row = await db.get<{ status: string; webhook_endpoint: string | null; scopes: string | null }>(
140
+ `SELECT status, webhook_endpoint, scopes FROM app_installs WHERE install_id = ? AND tenant_id = ? AND managed_kind IS NULL`,
141
+ [installId, tenantId],
142
+ );
143
+ if (!row) return "not-found";
144
+ const reasons: ProcessorIneligibility[] = [];
145
+ if (row.status !== "active") reasons.push("install-inactive");
146
+ if (!row.webhook_endpoint) reasons.push("webhook-endpoint-missing");
147
+ let scopes: unknown = [];
148
+ try {
149
+ scopes = JSON.parse(row.scopes ?? "[]");
150
+ } catch (error) {
151
+ if (!(error instanceof SyntaxError)) throw error;
152
+ }
153
+ if (!Array.isArray(scopes) || !scopes.includes(PROCESSOR_SCOPE)) reasons.push("processor-scope-missing");
154
+ return reasons;
155
+ }
156
+
157
+ /** A processor refusal: `install-not-found` only when the tenant has no such install. */
158
+ export type SetProcessorRefusal =
159
+ | { ok: false; code: "install-not-found" | "conflict" | "location-invalid" }
160
+ | { ok: false; code: "install-not-processor"; reasons: ProcessorIneligibility[] };
161
+
126
162
  /**
127
163
  * Sets or clears the (tenant, stage, location) processor. Switching or clearing releases the
128
164
  * previous install's active and held assignments routed through that location on that stage in
@@ -132,14 +168,17 @@ export async function installMayProcess(
132
168
  export async function setProcessor(
133
169
  db: FulfillmentDatabase,
134
170
  input: { tenantId: string; stage: CommerceStage; locationId?: string; installId: string | null; actorId: string; now: string },
135
- ): Promise<{ ok: true; installId: string | null } | { ok: false; code: "install-not-found" | "conflict" | "location-invalid" }> {
171
+ ): Promise<{ ok: true; installId: string | null } | SetProcessorRefusal> {
136
172
  const locationId = input.locationId ?? DEFAULT_LOCATION;
137
173
  if (!LOCATION_ID.test(locationId)) return { ok: false, code: "location-invalid" };
138
174
  for (let attempt = 0; attempt < 3; attempt++) {
139
175
  const current = await readProcessor(db, input.tenantId, input.stage, locationId);
140
176
  if ((current?.installId ?? null) === input.installId) return { ok: true, installId: input.installId };
141
177
  if (input.installId !== null && !(await installMayProcess(db, input.tenantId, input.installId))) {
142
- return { ok: false, code: "install-not-found" };
178
+ const why = await processorIneligibility(db, input.tenantId, input.installId);
179
+ if (why === "not-found") return { ok: false, code: "install-not-found" };
180
+ if (why.length) return { ok: false, code: "install-not-processor", reasons: why };
181
+ continue;
143
182
  }
144
183
  let first: SqlStatement;
145
184
  if (input.installId === null) {
@@ -17,7 +17,7 @@ import type { Queryable } from "../catalog/d1/catalog.js";
17
17
  import { prepareOrderContactKeys, sealOrderContact } from "../orders/vault/orderContactVault.js";
18
18
  import { readOrderContactCommand, type OrderContactCommand } from "../orders/vault/orderContact.js";
19
19
  import { grantConsent, grantedByHash } from "../integrations/apps/appContactConsents.js";
20
- import { readProcessor, setProcessor } from "./assignmentStore.js";
20
+ import { readProcessor, setProcessor, type ProcessorIneligibility } from "./assignmentStore.js";
21
21
  import { FulfillmentService, type FulfillmentActor, type SourceOrderSnapshot } from "./fulfillmentService.js";
22
22
  import { carrierPolicyForTenant, type CarrierPolicy } from "./readiness.js";
23
23
  import type { FulfillmentDatabase } from "./store.js";
@@ -55,13 +55,16 @@ export interface SyntheticScope {
55
55
  export type SyntheticRefusal =
56
56
  | "install-not-found"
57
57
  | "install-not-test"
58
+ | "install-not-processor"
58
59
  | "conflict"
59
60
  | "order-not-found"
60
61
  | "vault-key-unavailable"
61
62
  | "contact-refused"
62
63
  | (string & {});
63
64
 
64
- export type SyntheticResult<T> = { ok: true; value: T } | { ok: false; code: SyntheticRefusal; holds?: readonly string[] };
65
+ export type SyntheticResult<T> =
66
+ | { ok: true; value: T }
67
+ | { ok: false; code: SyntheticRefusal; holds?: readonly string[]; reasons?: readonly ProcessorIneligibility[] };
65
68
 
66
69
  /** The RFC-reserved recipient sealed for every synthetic order. Index picks the 555-01xx line. */
67
70
  export function syntheticRecipient(orderId: string, index = 0): OrderContactCommand {
@@ -95,7 +98,8 @@ function actor(scope: SyntheticScope): FulfillmentActor {
95
98
 
96
99
  /**
97
100
  * Bind `installId` as the tenant's preview processor and grant it preview recipient consent. The
98
- * install must belong to the tenant, be unmanaged, and have env `test`.
101
+ * install must belong to the tenant, be unmanaged, and have env `test`; an install that exists but
102
+ * cannot process (`install-not-processor`) names each unmet condition in `reasons`.
99
103
  */
100
104
  export async function bindTestProcessor(
101
105
  deps: SyntheticOrderDeps,
@@ -118,7 +122,7 @@ export async function bindTestProcessor(
118
122
  actorId: scope.actorId,
119
123
  now: now.toISOString(),
120
124
  });
121
- if (!bound.ok) return { ok: false, code: bound.code };
125
+ if (!bound.ok) return bound.code === "install-not-processor" ? bound : { ok: false, code: bound.code };
122
126
 
123
127
  const live = await deps.db.first(
124
128
  `SELECT 1 AS live FROM app_contact_consents
@@ -59,7 +59,7 @@ function isUniqueViolation(error: unknown): boolean {
59
59
 
60
60
  export type GrantOutcome =
61
61
  | { ok: true; consent: ConsentView }
62
- | { ok: false; code: "install-not-found" | "conflict" };
62
+ | { ok: false; code: "install-not-found" | "install-inactive" | "conflict" };
63
63
 
64
64
  export async function grantConsent(
65
65
  db: Queryable,
@@ -76,7 +76,13 @@ export async function grantConsent(
76
76
  consentId, input.installId, input.tenantId, input.stage, input.grantedBy, grantedAt, input.expiresAt,
77
77
  input.installId, input.tenantId,
78
78
  );
79
- if (rows.length !== 1) return { ok: false, code: "install-not-found" };
79
+ if (rows.length !== 1) {
80
+ const exists = await db.first(
81
+ `SELECT 1 AS present FROM app_installs WHERE install_id = ? AND tenant_id = ?`,
82
+ input.installId, input.tenantId,
83
+ );
84
+ return { ok: false, code: exists ? "install-inactive" : "install-not-found" };
85
+ }
80
86
  } catch (error) {
81
87
  if (isUniqueViolation(error)) return { ok: false, code: "conflict" };
82
88
  throw error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.17.1",
3
+ "version": "7.0.0",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",
@@ -2,11 +2,11 @@ export interface CatalogSize {
2
2
  readonly products: number;
3
3
  readonly bytes: number;
4
4
  }
5
- export type CatalogScaleLevel = "ok" | "warn" | "d1-required";
5
+ export type CatalogScaleLevel = "ok" | "warn" | "large";
6
6
 
7
7
  export declare const CATALOG_SCALE_WARN: Readonly<CatalogSize>;
8
- export declare const CATALOG_SCALE_D1_REQUIRED: Readonly<CatalogSize>;
8
+ export declare const CATALOG_SCALE_LARGE: Readonly<CatalogSize>;
9
9
  export declare function catalogScaleLevel(size: CatalogSize): CatalogScaleLevel;
10
10
  export declare function catalogScaleFinding(
11
11
  size: CatalogSize,
12
- ): { level: "warn" | "d1-required"; message: string } | null;
12
+ ): { level: "warn" | "large"; message: string } | null;
@@ -1,70 +1,76 @@
1
1
  /**
2
2
  * Catalog scale thresholds: the one place the platform says how large a store's own
3
- * `content/catalog/` may grow before each serving path stops being safe (ADR 0033).
3
+ * `content/catalog/` may grow before a release gets slow or heavy (ADR 0033).
4
4
  *
5
5
  * Two measures, because either can be the one that bites:
6
6
  * - products: the count of `catalog/products/*.json` files;
7
7
  * - bytes: the raw size of every file under `catalog/`.
8
8
  *
9
- * Evidence (synthetic Giant-shaped tenants, measured 2026-11-16 by
10
- * `apps/storefront/src/lib/catalog/tot/catalogScale.test.ts`):
11
- * - the listing projection parses in ~150 ms and ~47 MB of heap at 10,000 products;
12
- * - reading the files one by one costs ~55 MB of heap at 5,000 products and ~111 MB at
13
- * 10,000 against the Worker's 128 MB;
14
- * - a store of 3,571 files / 42 MB failed to render in the materializer's wrangler-dev
15
- * Worker (fb-1794371798042-4rqyh4), which is why bytes are a line of their own.
9
+ * Evidence (synthetic Giant-shaped tenants):
10
+ * - Listing projection, measured 2026-11-16 by `catalogScale.test.ts`: ~150 ms and ~47 MB of
11
+ * heap to parse at 10,000 products, so the hosted preview read path fits well inside the
12
+ * Worker's 128 MB isolate. Reading the files one by one costs ~111 MB at 10,000.
13
+ * - Static materialize (`materialize-tenant.mjs`, apps/storefront build + wrangler dev render),
14
+ * measured 2026-11-16 on a developer laptop (darwin arm64, Node 24) against the `catalog.e2e.test` fixture tenant:
15
+ *
16
+ * products catalog files routes wall time
17
+ * 2,000 21 MB 2,746 170 s
18
+ * 3,500 37 MB 5,026 394 s
19
+ * 5,000 53 MB 6,827 658 s
20
+ * 7,000 74 MB 10,027 1,265 s
21
+ *
22
+ * It completed at every size with every route rendered: no size here fails to materialize, so
23
+ * nothing is refused. The cost is publish time, which grows faster than the catalog.
24
+ * fb-1794371798042-4rqyh4 reported a 3,571-file / 42 MB release that rendered 6 routes; that did
25
+ * not reproduce here, so its cause is not catalog size alone.
16
26
  */
17
27
 
18
28
  /** A catalog at or past either line gets a non-blocking finding naming the next line. */
19
29
  export const CATALOG_SCALE_WARN = Object.freeze({ products: 3000, bytes: 25_000_000 });
20
30
 
21
- /** A catalog at or past either line must declare `catalog.serving: "d1"` to be materialized. */
22
- export const CATALOG_SCALE_D1_REQUIRED = Object.freeze({ products: 5000, bytes: 40_000_000 });
31
+ /** At or past either line a release took over ten minutes to materialize in the measurement above. */
32
+ export const CATALOG_SCALE_LARGE = Object.freeze({ products: 5000, bytes: 40_000_000 });
23
33
 
24
34
  /**
25
35
  * @param {{ products: number, bytes: number }} size
26
- * @returns {"ok" | "warn" | "d1-required"}
36
+ * @returns {"ok" | "warn" | "large"}
27
37
  */
28
38
  export function catalogScaleLevel({ products, bytes }) {
29
- if (products >= CATALOG_SCALE_D1_REQUIRED.products || bytes >= CATALOG_SCALE_D1_REQUIRED.bytes) return "d1-required";
39
+ if (products >= CATALOG_SCALE_LARGE.products || bytes >= CATALOG_SCALE_LARGE.bytes) return "large";
30
40
  if (products >= CATALOG_SCALE_WARN.products || bytes >= CATALOG_SCALE_WARN.bytes) return "warn";
31
41
  return "ok";
32
42
  }
33
43
 
34
44
  const mb = (bytes) => `${(bytes / 1_000_000).toFixed(1)} MB`;
35
45
 
36
- const REMEDY =
37
- "ask Token of Trust to serve this catalog from the D1 projection (`catalog.serving` is a platform " +
38
- "setting, not a .tot/config.json key; public and static renders never read D1, ADR 0013), " +
39
- "or split the catalog";
40
-
41
46
  /**
42
- * The finding text for a catalog at `warn` or `d1-required`, or null when it is `ok`. Names the
43
- * count, the size, the next line and the remedy, and says what each CDN does at the line.
47
+ * The finding text for a catalog at `warn` or `large`, or null when it is `ok`. Names the count,
48
+ * the size, the measured publish time and the next line, and says what each CDN does.
44
49
  *
45
50
  * @param {{ products: number, bytes: number }} size
46
- * @returns {{ level: "warn" | "d1-required", message: string } | null}
51
+ * @returns {{ level: "warn" | "large"; message: string } | null}
47
52
  */
48
53
  export function catalogScaleFinding(size) {
49
54
  const level = catalogScaleLevel(size);
50
55
  if (level === "ok") return null;
51
56
  const have = `${size.products} products, ${mb(size.bytes)} of catalog files`;
52
57
  const cdns =
53
- "Cloudflare preview and publication read the catalog inside the Worker's 128 MB isolate; " +
54
- "CloudFront static publication renders on a build machine, whose preview Worker bundles the catalog.";
58
+ "Cloudflare preview reads the catalog from one listing projection inside the Worker; " +
59
+ "CloudFront static publication renders every page on a build machine.";
55
60
  if (level === "warn") {
56
61
  return {
57
62
  level,
58
63
  message:
59
- `catalog is ${have}; past ${CATALOG_SCALE_D1_REQUIRED.products} products or ` +
60
- `${mb(CATALOG_SCALE_D1_REQUIRED.bytes)} a file-served catalog may not render. ` +
61
- `${cdns} To stay ahead of it: ${REMEDY}.`,
64
+ `catalog is ${have}. Static publication of a catalog this size took about 6 minutes at ` +
65
+ `3,500 products in measurement, and past ${CATALOG_SCALE_LARGE.products} products or ` +
66
+ `${mb(CATALOG_SCALE_LARGE.bytes)} it took over 10 minutes. ${cdns}`,
62
67
  };
63
68
  }
64
69
  return {
65
70
  level,
66
71
  message:
67
- `catalog is ${have}, past the ${CATALOG_SCALE_D1_REQUIRED.products}-product / ` +
68
- `${mb(CATALOG_SCALE_D1_REQUIRED.bytes)} line for file-served catalogs. ${cdns} Fix: ${REMEDY}.`,
72
+ `catalog is ${have}, past the ${CATALOG_SCALE_LARGE.products}-product / ` +
73
+ `${mb(CATALOG_SCALE_LARGE.bytes)} line. Static publication took 11 minutes at 5,000 products ` +
74
+ `and 21 minutes at 7,000 in measurement, growing faster than the catalog. ${cdns}`,
69
75
  };
70
76
  }