Skip to content

Commit c5fd012

Browse files
fix(cloud-connection): install-local answers an artifact the resolver refuses with its 422 at the declared-rename step, not a 503 (#34573)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi96QpUuH77yeiDEFd5Vi6Pg1)_ Fixes #34432 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:install-local 的「声明式重命名」步骤(2c″)遇到解析器拒收的组合包(`packages` 不是数组、或某个包条目带已退役的 `indexes[].unique: true`)时,改为回答解析器自己的 422 与错误码,不再回答 503「数据库不可用、请重试」。 - 为什么改:包作者拿到的是错误归因,重试永远不会成功;同一份字节在 isolated 姿态的 2b 步骤已经回答 422,两个步骤口径不一致。 - 风险与回滚:只改 `@objectstack/cloud-connection` 一个文件的拒收答复,不写入任何数据;真正读不到表时仍回 503;未声明状态的异常(如包之间的依赖环)原样抛出。回滚即还原本 PR。 - 先看:`packages/cloud-connection/src/marketplace-install-local-plugin.ts` 的 `evaluateDeclaredRenames` 开头新增的预解析块,以及抽出的 `declaredRefusalAnswer`(2b 与 2c″ 共用);再看新测试 `marketplace-install-local-resolver-refusal-34432.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/cloud-connection exec vitest run src/marketplace-install-local-resolver-refusal-34432.test.ts`,预期 5 个用例全绿(两条 422、一条 503 对照、一条 200 对照、一条依赖环原样抛出)。 - 需要你做的:无,席位落地。 ## What changes Step 2c″ of `POST /api/v1/marketplace/install-local` (`evaluateDeclaredRenames`) caught every throw out of `planDeclaredRenames` and answered it `503 SERVICE_UNAVAILABLE` "… could not be read … Retry once the database answers". That included the artifact resolver's declared `422` refusal of a composed body. The step now: - resolves the bodies the plan reads before any table is read, through the plan's own fold (`packageUpgradeSideOf`: the `resolveStackCollection` reads of `objects`, `objectExtensions` and `data`; the installed body too on a re-install); - answers a refusal there with that refusal's own declared status and code (`422 INVALID_ARTIFACT_PACKAGES` / `INVALID_ARTIFACT_PACKAGE_ENTRY`) and writes nothing; - rethrows an undeclared throw out of the resolver (its dependency-cycle error, a bare `Error`), and does not relabel it; - keeps the `503` for a throw out of the plan itself, which is now only the table read. The reader is the one step 2b (#34428) answers the same refusal with. It is extracted within the file as `declaredRefusalAnswer(manifestId, err)`, so the two steps share one implementation and answer the same bytes with the same status, code and sentence. Step 2b's behaviour is byte-identical: same predicate (`declaredStatus === undefined || status >= 500` ⇒ rethrow), same body, same status. Changeset: `@objectstack/cloud-connection` patch. ## Tests New file `packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts`. It drives the real install route handler, under the `single` posture, with the route-handler harness that #34428 used (runtime mocked without the step-1c collectors): - `packages: 'not-a-list'` ⇒ `422`, `error.code` `INVALID_ARTIFACT_PACKAGES`. Nothing is registered, there is no ledger entry, and the driver is never asked to read a table. - A package entry with a retired bare `indexes[].unique: true` ⇒ `422`, `INVALID_ARTIFACT_PACKAGE_ENTRY`. Nothing is written. - CONTROL: a well-formed composed artifact whose renamed field's table read throws ⇒ `503 SERVICE_UNAVAILABLE`, and nothing is written. - CONTROL: the same artifact over a readable table ⇒ `200`. - A dependency cycle between two packages (an undeclared resolver throw) ⇒ rethrown out of the handler, not answered `503`. No existing test was changed. <details><summary>Ablation (fix removed ⇒ red), via scripts/ablation-replace.mjs</summary> Mutation: ` packageUpgradeSideOf(converted);` ⇒ ` /* ABLATION-34432 */` in `marketplace-install-local-plugin.ts`, at commit e6e6b07. The anchor count went 1 ⇒ 0 and the blob went 8302cb3 ⇒ 07061200e185. The test imports the plugin by relative path (source, not `dist/`), so no rebuild sits in the loop. - `Tests 3 failed | 2 passed (5)`: both 422 pins received `503 SERVICE_UNAVAILABLE` with the card's exact sentence ("the tables its declared rename(s) carry could not be read (A release artifact's `packages` must be an array …) … Retry once the database answers."). The cycle pin received the `503` answer ("… could not be read ([Kernel] Circular dependency detected: com.example.suite.core) …") and no throw. - Both controls stayed green. - Restore: `blob after restore 8302cb3 == blob at HEAD`, and `git diff HEAD` is empty. </details> <details><summary>Package suite and typecheck at the final head</summary> After the closure rebuild (`pnpm --filter '@objectstack/cloud-connection...' build`) at 18b6049: - `pnpm --filter @objectstack/cloud-connection typecheck`: exit 0. `tsconfig.test.json --listFiles` includes the new test file. - `pnpm --filter @objectstack/cloud-connection exec vitest run --maxWorkers=2`: `Test Files 89 passed (89)`, `Tests 1295 passed (1295)`. - Lock: `VERDICT command-exit 0`. </details> ## Acceptance notes - **Where this step is reached first.** The harness mocks `@objectstack/runtime` without `collectJobsWithoutBody` / `collectHooksWithoutBody`. That stands for a runtime that predates the step-1c code judgements, and on such a runtime 2c″ is the first step to resolve the packages. With the real runtime the same two bodies are resolved first at step 1c (`unrunnableCode` ⇒ `collectBundleJobs` ⇒ `resolveArtifactCollections`), and the resolver's refusal leaves the handler as a throw. I measured this by running the same pins once over the real runtime: the throw comes out of `handleInstall` at the `collectJobs(manifest)` call. The Hono transport's error seam (`declaredEnvelopeForThrow`) then answers it `422` with the resolver's code and reports a transport escape. That last part is read from `plugin-hono-server/src/adapter.ts`, not measured. So on a current runtime the client already saw the `422`, and this PR changes the 2c″ answer for the older-runtime composition. Step 1c answering the refusal itself, as 2b and now 2c″ do, is outside this card. - **What the 503 still covers.** A throw out of `planDeclaredRenames` after the bodies resolved is answered as the table read. That is the driver's introspection, plus any fault of the plan's own code, which this step has always answered `503`. Telling those two apart needs a marker at the driver call inside `marketplace-install-declared-renames.ts`, which is outside this card's file surface. - **Read superset.** On a fresh install the pre-resolution also reads `data`, which the plan alone does not read. A composed body the resolver refuses only through `data` is now refused here, before any write. Before, the `manifest` service refused it at register, on the same bytes. - A dependency cycle between packages of one artifact is a bare `Error` by `resolveArtifactPackageOrder`'s documented contract (`artifact-collections.ts` header). It is rethrown here and, by the transport seam, answered `500 INTERNAL_ERROR` with no cause. Filed: #34574. - On a re-install the pre-resolution also folds the installed copy (`packageUpgradeSideOf(installed)`). When today's resolver refuses that stored copy, the answer is a 422 that names the incoming package ("Package 'X' cannot be installed"), and that side has no pin of its own. Before this PR the same case answered 503, and step 2c′ folds the installed copy again unguarded, so this is no new dead end, only a misattributed message. Filed: #34583. ## Verification Gates were run after the last commit, one at a time, each with stdin closed. The derived list is `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at 18b6049 (3 paths, 71 commands). Reconciliation is `--ran` with `Run reconciliation — 71 derived, 71 run, 0 NOT-MEASURED, 0 UNRUN.`. <details><summary>Gate results</summary> All 71 exit 0. `check:dual-build-cjs-loads` first answered exit 3 (PREREQUISITE NOT MET, no `dist/`) and was re-run green after a whole-workspace build (`turbo run build --filter=!@objectstack/docs --concurrency=2`, lock VERDICT command-exit 0): `124 published require entry point(s) across 72 package(s) load`. ```text node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:cli-command-ids :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:durability-log-level :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:error-status-conformance :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:init-service-contract :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:object-def-param-keys :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:optional-error-sink :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:route-envelope :: exit 0 pnpm check:settings-bind-window :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:startup-registry-verdict :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` </details> <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRXuRn93HphKp7kXEz --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d7980d1 commit c5fd012

3 files changed

Lines changed: 313 additions & 13 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/cloud-connection': patch
3+
---
4+
5+
fix(cloud-connection): install-local answers a composed artifact the resolver refuses with the resolver's 422 at the declared-rename step, not a 503 telling the author to retry
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The declared-rename step of `POST /api/v1/marketplace/install-local` (step 2c″) reads every package body of a composed artifact through the artifact resolver. When the resolver refused the artifact, the step answered `503 SERVICE_UNAVAILABLE`: "the tables its declared rename(s) carry could not be read … Retry once the database answers." Examples are a `packages` that is not a list, or a package entry that carries a retired bare `indexes[].unique: true`. A retry never helps, and the author looked for the fault in the wrong place.
11+
12+
The step now resolves the bodies before it reads any table. A refusal answers with the resolver's own declared status and code: `422 INVALID_ARTIFACT_PACKAGES` or `INVALID_ARTIFACT_PACKAGE_ENTRY`, with the resolver's sentence. Nothing is written. This is the answer the `isolated`-posture unique-scope gate already gives for the same bytes, through the same reader. An undeclared throw out of the resolver, such as a dependency cycle between two packages of one artifact, is rethrown and is not relabelled. The 503 now means only that a table could not be read.
13+
14+
The door reaches this step first only on a runtime that predates the install-time code judgements (`collectJobsWithoutBody`, `collectHooksWithoutBody`). A runtime that carries them resolves the packages earlier, so its answer does not change.

‎packages/cloud-connection/src/marketplace-install-local-plugin.ts‎

Lines changed: 67 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,39 @@ function isDeclaredRegisterRefusal(err: unknown): boolean {
474474
return declared !== undefined && declared >= 400 && declared < 500;
475475
}
476476

477+
/**
478+
* [#34407, #34432] The answer to a package body the artifact resolver refuses
479+
* before any write (`resolveStackCollection` → `resolveArtifactPackageEntries`:
480+
* `INVALID_ARTIFACT_PACKAGES`, `INVALID_ARTIFACT_PACKAGE_ENTRY`,
481+
* `DUPLICATE_ARTIFACT_PACKAGE`, each an ADR-0112 envelope with its declared
482+
* `status: 422`): that refusal's own declared status and code, the resolver's
483+
* sentence, and that nothing was written. The one reader of such a refusal on
484+
* this door's pre-write steps — the D5e gate (2b) and the declared renames
485+
* (2c″) both read the bodies through the resolver, so the same bytes are
486+
* answered the same way whichever step reads them first.
487+
*
488+
* `undefined` for a throw that declares no status below 500 — an undeclared
489+
* throw (the resolver's own dependency-cycle error among them) or a declared
490+
* 5xx: the caller rethrows it, never relabels it.
491+
*/
492+
function declaredRefusalAnswer(
493+
manifestId: string,
494+
err: unknown,
495+
): { status: number; body: { success: false; error: { code: string; message: string } } } | undefined {
496+
const refusal = resolveThrownHttpError(err);
497+
if (refusal.declaredStatus === undefined || refusal.status >= 500) return undefined;
498+
return {
499+
status: refusal.status,
500+
body: {
501+
success: false,
502+
error: {
503+
code: refusal.code,
504+
message: `Package '${manifestId}' cannot be installed: ${String((err as any)?.message ?? err)} Nothing was installed or written.`,
505+
},
506+
},
507+
};
508+
}
509+
477510
/**
478511
* [#21490] The one `protocol` verb this plugin calls: the runner of the
479512
* uninstall cleanups domain plugins register through
@@ -3123,20 +3156,15 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
31233156
// `packages` the resolver refuses (ADR-0112 `code` + its declared
31243157
// 4xx status, the refusal the `manifest` service raises on the same
31253158
// bytes) is answered here, before anything is written — never
3126-
// thrown out of the door. An undeclared throw stays a throw.
3159+
// thrown out of the door ({@link declaredRefusalAnswer}). An
3160+
// undeclared throw stays a throw.
31273161
let gate: ReturnType<MarketplaceInstallLocalPlugin['evaluateGlobalUniqueGate']>;
31283162
try {
31293163
gate = this.evaluateGlobalUniqueGate(manifest, previousEntry, body, userId);
3130-
} catch (err: any) {
3131-
const refusal = resolveThrownHttpError(err);
3132-
if (refusal.declaredStatus === undefined || refusal.status >= 500) throw err;
3133-
return c.json({
3134-
success: false,
3135-
error: {
3136-
code: refusal.code,
3137-
message: `Package '${manifestId}' cannot be installed: ${String(err?.message ?? err)} Nothing was installed or written.`,
3138-
},
3139-
}, refusal.status);
3164+
} catch (err: unknown) {
3165+
const refused = declaredRefusalAnswer(manifestId, err);
3166+
if (!refused) throw err;
3167+
return c.json(refused.body, refused.status);
31403168
}
31413169
if (gate.blocked) {
31423170
ctx.logger?.warn?.(
@@ -3204,7 +3232,10 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
32043232
// the physical table by the driver's own rule
32053233
// ({@link evaluateDeclaredRenames}); a declaration it cannot
32063234
// honour is refused `422 VALIDATION_ERROR`, naming the field, the
3207-
// old key and the reason. Asked before 2c′, so a refusal no token
3235+
// old key and the reason; [#34432] a body the artifact resolver
3236+
// refuses is answered with that refusal's own status and code, as
3237+
// at 2b, and only a table that could not be read answers 503.
3238+
// Asked before 2c′, so a refusal no token
32083239
// answers is never preceded by a 409 asking for one. The carry
32093240
// itself runs right before step 3, the last moment the running
32103241
// version still serves the old key.
@@ -4566,6 +4597,12 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
45664597
* - **A refusal**: `422 VALIDATION_ERROR` (this door's body refusal),
45674598
* each in `details.refusals` with its object, field, old key(s) and
45684599
* reason. No token answers it: the package must change.
4600+
* - **A body the artifact resolver refuses** (a composed artifact whose
4601+
* `packages` is not a list, or one of whose entries the entry contract
4602+
* refuses): that refusal's own declared status and code
4603+
* ({@link declaredRefusalAnswer}, step 2b's reader), before any table is
4604+
* read. An undeclared throw out of the resolver is rethrown, never
4605+
* relabelled.
45694606
* - **A reading that failed** (the table could not be read): `503
45704607
* SERVICE_UNAVAILABLE`, never taken for "nothing to carry".
45714608
* - Otherwise the tables to carry, which step 2f carries.
@@ -4575,7 +4612,24 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
45754612
manifestId: string,
45764613
converted: unknown,
45774614
installed: unknown,
4578-
): Promise<{ refusal?: { body: Record<string, unknown>; status: 422 | 503 }; tables: InstallRenameTable[] }> => {
4615+
): Promise<{ refusal?: { body: Record<string, unknown>; status: number }; tables: InstallRenameTable[] }> => {
4616+
// [#34432] The bodies the plan reads, resolved FIRST through the fold
4617+
// the plan reads them by ({@link packageUpgradeSideOf}: the
4618+
// `resolveStackCollection` reads of `objects`, `objectExtensions` and
4619+
// `data`), so a body the resolver refuses is told apart from a table
4620+
// that could not be read: the resolver is deterministic over the same
4621+
// bytes, so the plan below never meets its refusal, and what the plan
4622+
// throws is answered as the table read's. Without this, the
4623+
// resolver's 422 was answered as the 503 below and its author was told
4624+
// to retry once the database answers.
4625+
try {
4626+
packageUpgradeSideOf(converted);
4627+
if (installed !== null && installed !== undefined) packageUpgradeSideOf(installed);
4628+
} catch (err: unknown) {
4629+
const refused = declaredRefusalAnswer(manifestId, err);
4630+
if (!refused) throw err;
4631+
return { tables: [], refusal: refused };
4632+
}
45794633
let plan: { tables: InstallRenameTable[]; refusals: InstallRenameRefusal[] };
45804634
try {
45814635
plan = await planDeclaredRenames(ctx, manifestId, converted, installed);
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#34432] Step 2c″ of the install door (the declared renames) reads every
5+
* package body of a composed artifact through the artifact resolver, as the
6+
* `isolated`-posture D5e gate (2b) does. A body the resolver refuses is
7+
* answered with that refusal's own declared status and code — the resolver's
8+
* `422 INVALID_ARTIFACT_PACKAGES` / `INVALID_ARTIFACT_PACKAGE_ENTRY` — and
9+
* nothing is written. Before, every throw out of the rename plan was answered
10+
* `503 SERVICE_UNAVAILABLE` "Retry once the database answers", so an author
11+
* whose bundle is malformed was told the database was down.
12+
*
13+
* Driven through the real `POST /api/v1/marketplace/install-local` handler
14+
* under the `single` posture, where the D5e gate reads no body, over a runtime
15+
* that predates the step-1c code judgements (`@objectstack/runtime` is mocked
16+
* without `collectJobsWithoutBody` / `collectHooksWithoutBody`, as in
17+
* `marketplace-install-local-composed-top-level-reads.test.ts`), so 2c″ is the
18+
* first step to resolve the packages. (A runtime that carries those
19+
* judgements resolves the packages at step 1c first, and the resolver's
20+
* refusal leaves the door as a throw.) The controls pin the rest of the
21+
* contract: a table that really could not be read still answers 503, and an
22+
* undeclared throw out of the resolver (its own dependency-cycle error) is
23+
* rethrown, never relabelled.
24+
*/
25+
26+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
27+
import { mkdtempSync, rmSync } from 'node:fs';
28+
import { join } from 'node:path';
29+
import { tmpdir } from 'node:os';
30+
31+
vi.mock('@objectstack/runtime', () => ({
32+
SeedLoaderService: class {
33+
async load() { return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; }
34+
async buildDependencyGraph(objects: string[]) { return { objects }; }
35+
},
36+
resolveSeedLocaleForLoad: async () => undefined,
37+
appDefaultSeedLocale: () => undefined,
38+
describeSeedLocale: () => 'none',
39+
}));
40+
41+
import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js';
42+
import { declareInstallerPlatformOwner, installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js';
43+
import { LocalManifestSource } from './local-manifest-source.js';
44+
45+
type Handler = (c: any) => Promise<any>;
46+
type Row = Record<string, any>;
47+
48+
const ROUTE = '/api/v1/marketplace/install-local';
49+
const SUITE = 'com.example.suite';
50+
51+
/** An object whose field declares a rename, so step 2c″ asks the driver to read its table. */
52+
const LEAD = { name: 'crm_lead', label: 'Lead', fields: { account_name: { type: 'text', label: 'Account', renamedFrom: ['company'] } } };
53+
const ACCOUNT = { name: 'crm_account', label: 'Account', fields: { name: { type: 'text', label: 'Name' } } };
54+
55+
const entry = (id: string, objects: Row[], dependencies?: Record<string, string>): Row => ({
56+
manifest: { id, name: id, version: '1.0.0', type: 'module', ...(dependencies ? { dependencies } : {}), objects },
57+
});
58+
59+
/** A composed artifact: `packages[]` and no top-level `objects`, so every reader goes through the resolver. */
60+
const composed = (packages: unknown): Row => ({ id: SUITE, name: 'Suite', version: '1.0.0', type: 'app', packages });
61+
const WELL_FORMED = (): Row[] => [entry(`${SUITE}.core`, [ACCOUNT]), entry(`${SUITE}.leads`, [LEAD])];
62+
63+
function makeRawApp() {
64+
const routes = new Map<string, Handler>();
65+
return {
66+
routes,
67+
get: (p: string, h: Handler) => routes.set(`GET ${p}`, h),
68+
post: (p: string, h: Handler) => routes.set(`POST ${p}`, h),
69+
delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h),
70+
};
71+
}
72+
73+
function makeC(reqBody: any) {
74+
return {
75+
req: {
76+
url: `http://localhost:3000${ROUTE}`,
77+
raw: new Request(`http://localhost:3000${ROUTE}`),
78+
json: async () => reqBody,
79+
param: () => undefined,
80+
header: () => undefined,
81+
query: () => undefined,
82+
},
83+
json: vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })),
84+
};
85+
}
86+
87+
/**
88+
* A driver with the declared-rename members the door asks. Its plan reads no
89+
* table and carries nothing; `planThrows` makes the table read fail the way a
90+
* database that does not answer fails it (an undeclared throw).
91+
*/
92+
function fakeDriver(opts: { planThrows?: boolean } = {}) {
93+
return {
94+
planDeclaredRenames: vi.fn(async () => {
95+
if (opts.planThrows) throw new Error('connect ECONNREFUSED');
96+
return { carries: [], refusals: [] };
97+
}),
98+
carryDeclaredRenames: vi.fn(async () => []),
99+
reverseDeclaredRenames: vi.fn(async () => undefined),
100+
};
101+
}
102+
103+
async function boot(dir: string, driver: ReturnType<typeof fakeDriver>) {
104+
const rawApp = makeRawApp();
105+
const hooks = new Map<string, any>();
106+
const register = vi.fn();
107+
const services: Record<string, any> = {
108+
manifest: { register },
109+
auth: installerAuthService(),
110+
objectql: withInstallerGrants({
111+
syncSchemas: async () => undefined,
112+
getDriverForObject: () => driver,
113+
registry: { getObject: () => undefined },
114+
}),
115+
metadata: {},
116+
};
117+
const ctx = {
118+
hook: (e: string, h: any) => hooks.set(e, h),
119+
getService: (name: string) => {
120+
if (name === 'http-server') return { getRawApp: () => rawApp };
121+
const svc = services[name];
122+
if (svc === undefined) throw new Error(`no ${name}`);
123+
return svc;
124+
},
125+
registerService: (name: string, svc: unknown) => { services[name] = svc; },
126+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
127+
};
128+
const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir });
129+
await plugin.start(ctx as any);
130+
await hooks.get('kernel:ready')?.();
131+
// The door registers its own plugin manifest at boot; only the install's registrations count.
132+
register.mockClear();
133+
return {
134+
install: (reqBody: Row) => rawApp.routes.get(`POST ${ROUTE}`)!(makeC(reqBody)),
135+
register,
136+
};
137+
}
138+
139+
let dir: string;
140+
let posture: string | undefined;
141+
let restoreOwner: () => void;
142+
beforeEach(() => {
143+
dir = mkdtempSync(join(tmpdir(), 'mil-resolver-refusal-'));
144+
posture = process.env.OS_TENANCY_POSTURE;
145+
process.env.OS_TENANCY_POSTURE = 'single';
146+
restoreOwner = declareInstallerPlatformOwner('admin');
147+
});
148+
afterEach(() => {
149+
restoreOwner();
150+
rmSync(dir, { recursive: true, force: true });
151+
if (posture === undefined) delete process.env.OS_TENANCY_POSTURE;
152+
else process.env.OS_TENANCY_POSTURE = posture;
153+
vi.restoreAllMocks();
154+
});
155+
156+
/** Nothing registered, no ledger entry, and the table never read. */
157+
function expectNothingWritten(rt: Awaited<ReturnType<typeof boot>>, driver: ReturnType<typeof fakeDriver>) {
158+
expect(rt.register).not.toHaveBeenCalled();
159+
expect(new LocalManifestSource(dir).read(SUITE).entry).toBeNull();
160+
expect(driver.planDeclaredRenames).not.toHaveBeenCalled();
161+
expect(driver.carryDeclaredRenames).not.toHaveBeenCalled();
162+
}
163+
164+
describe('#34432 — step 2c″ answers a body the artifact resolver refuses with that refusal, under the single posture', () => {
165+
it('a `packages` that is not a list answers 422 INVALID_ARTIFACT_PACKAGES, and nothing is written', async () => {
166+
const driver = fakeDriver();
167+
const rt = await boot(dir, driver);
168+
169+
const res = await rt.install({ manifest: composed('not-a-list') });
170+
171+
expect(res.status, JSON.stringify(res.payload)).toBe(422);
172+
expect(res.payload.success).toBe(false);
173+
expect(res.payload.error.code).toBe('INVALID_ARTIFACT_PACKAGES');
174+
expectNothingWritten(rt, driver);
175+
});
176+
177+
it('a package entry carrying a retired bare `indexes[].unique: true` answers 422 INVALID_ARTIFACT_PACKAGE_ENTRY, and nothing is written', async () => {
178+
const driver = fakeDriver();
179+
const rt = await boot(dir, driver);
180+
const retired = { ...ACCOUNT, indexes: [{ fields: ['name'], unique: true }] };
181+
182+
const res = await rt.install({ manifest: composed([entry(`${SUITE}.core`, [retired]), entry(`${SUITE}.leads`, [LEAD])]) });
183+
184+
expect(res.status, JSON.stringify(res.payload)).toBe(422);
185+
expect(res.payload.success).toBe(false);
186+
expect(res.payload.error.code).toBe('INVALID_ARTIFACT_PACKAGE_ENTRY');
187+
expectNothingWritten(rt, driver);
188+
});
189+
});
190+
191+
describe('#34432 — controls: the 503 stays the unread table\'s, and an undeclared throw stays a throw', () => {
192+
it('CONTROL: a well-formed composed artifact whose renamed field\'s table cannot be read still answers 503 SERVICE_UNAVAILABLE', async () => {
193+
const driver = fakeDriver({ planThrows: true });
194+
const rt = await boot(dir, driver);
195+
196+
const res = await rt.install({ manifest: composed(WELL_FORMED()) });
197+
198+
expect(res.status, JSON.stringify(res.payload)).toBe(503);
199+
expect(res.payload.error.code).toBe('SERVICE_UNAVAILABLE');
200+
expect(driver.planDeclaredRenames).toHaveBeenCalledTimes(1);
201+
expect(rt.register).not.toHaveBeenCalled();
202+
expect(new LocalManifestSource(dir).read(SUITE).entry).toBeNull();
203+
});
204+
205+
it('CONTROL: the same artifact over a table that reads installs', async () => {
206+
const driver = fakeDriver();
207+
const rt = await boot(dir, driver);
208+
209+
const res = await rt.install({ manifest: composed(WELL_FORMED()) });
210+
211+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
212+
expect(driver.planDeclaredRenames).toHaveBeenCalledTimes(1);
213+
});
214+
215+
it('an undeclared throw out of the resolver (a dependency cycle between two packages) is rethrown, never answered 503', async () => {
216+
const driver = fakeDriver();
217+
const rt = await boot(dir, driver);
218+
const cyclic = [
219+
entry(`${SUITE}.core`, [ACCOUNT], { [`${SUITE}.leads`]: '*' }),
220+
entry(`${SUITE}.leads`, [LEAD], { [`${SUITE}.core`]: '*' }),
221+
];
222+
223+
const outcome = await rt.install({ manifest: composed(cyclic) }).then(
224+
(res: any) => ({ answered: res }),
225+
(err: unknown) => ({ thrown: err as Error }),
226+
);
227+
228+
expect('answered' in outcome ? JSON.stringify(outcome.answered.payload) : 'thrown').toBe('thrown');
229+
expect((outcome as { thrown: Error }).thrown.message).toContain('Circular dependency');
230+
expectNothingWritten(rt, driver);
231+
});
232+
});

0 commit comments

Comments
 (0)