Skip to content

Commit a32d50b

Browse files
test(runtime): the protocol uninstall door leaves no handler of the package it uninstalls bound (#33844)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbTGhxJSYAmQXU7efVdNqrpw)_ Fixes #33624 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:只加一个测试文件,钉住"协议卸载门 `DELETE /api/v1/packages/ID` 卸载后,该包的脚本动作和 body hook 不再在引擎上运行"。没有改任何运行时代码。 - **为什么改**:卡片怀疑这扇门不调用 `unbindAppArtifactHandlers`,处理器会挂到重启。实测证伪:这扇门能卸的包(经 `POST /packages` 创作的包)的处理器挂在 `metadata-service` 名下,卸载时由重载同步撤掉;由运行时绑定器以 `app:ID` 绑定的包(install-local 安装或代码包)会被这扇门以 422 只读拒绝,根本卸不掉。所以方案 A 不需要,卡片随本测试关闭。 - **风险与回滚**:零运行时风险,只新增测试;回滚即删除该测试文件。 - **先看**:`packages/runtime/src/domains/packages-uninstall-handlers-withdrawn.test.ts`(两个用例:创作包卸载后动作 404、hook 不再触发、对照包仍运行;绑定器包被 422 拒绝、处理器随包保留)。 - **两分钟验证**:`pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/domains/packages-uninstall-handlers-withdrawn.test.ts`,预期 2 passed。 - **需要你做的**:无,席位落地。 ## What changes One test file, no runtime code. It answers the card's Step 1 (measure) on a real kernel, through the dispatcher's routes, and pins the answer: **the premise does not reproduce**, so the card closes with this measurement (the card's own rule: "If it does not reproduce, close this card with the measurement"). Fix A (a `runtime.package-handlers` uninstall cleanup) is not taken; no uninstall response's `cleanups` list changes. ### The measurement (origin/main d7e1a5a, this branch adds only the pin) Composition: `ObjectKernel` + SQL driver (better-sqlite3 in memory) + the real `ObjectQLPlugin` (engine, registry, protocol, authored resync) + the runtime `AppPlugin` (default action runner) + `HttpDispatcher.dispatch` for every call. 1. **A package this door can uninstall** is a writable base: installed with `POST /api/v1/packages`, its script action and body hook saved under it with `PUT /api/v1/meta/action|hook/NAME?package=ID`. Their handlers are bound under the environment's authored owner `metadata-service`, never under `app:ID`. After `DELETE /api/v1/packages/ID` answers `200` (`registryRemoved: true`, the action and hook rows in `persisted.deleted`): - the engine lists no holder of the action key (`[]`, was `['metadata-service']`); - `POST /api/v1/actions/OBJECT/NAME/RID` answers `404 RESOURCE_NOT_FOUND` and the body did not run; - a `POST /api/v1/data/OBJECT` write carries only the CONTROL package's stamp (`|q`, was `|p|q`); - CONTROL: another authored package's action and hook still run. 2. **A package the runtime binder bound under `app:ID`**, registered through the `manifest` service with `source: 'marketplace'` and bound by `bindAppArtifactHandlers` with install-local's own options (what `MarketplaceInstallLocalPlugin`'s install does): the door answers `422 WRITABLE_PACKAGE_REQUIRED` before anything moves (`isWritablePackage` is false for any id in the engine's `manifests`; a code boot lands there too). The package stays installed, so its handler and hook stay bound and run, which is correct; its own door (`DELETE /api/v1/marketplace/install-local/ID`) unbinds them. So the binder's owners never reach this door. ### What withdraws the authored handlers (the area's question about the `metadata:reloaded` announcement from #33546) Two paths each withdraw them before the door answers; either one is enough on its own: - the announcement `DELETE` makes (`announcePackageReload(…, 'uninstalled')`, `packages.ts`), whose `metadata:reloaded` subscriber in `ObjectQLPlugin` runs `resyncAuthoredHooks` + `resyncAuthoredActions` (a full teardown and rebind of the `metadata-service` set from the stored rows); - the protocol's per-row delete events (`onMetadataMutation`, `state: 'deleted'`), which run the same resyncs, fire-and-forget. The announcement is the one the door awaits, so it is what makes the answer deterministic (see Acceptance notes). ### H2 (shared cleanup registry) It exists and both doors walk it: `deletePackage` runs `runUninstallCleanups` at `packages/metadata-protocol/src/protocol-package-uninstall.ts:385`; install-local's door runs it through `protocol.runUninstallCleanups` (`packages/cloud-connection/src/marketplace-install-local-plugin.ts:3718` → `:4107`). The runtime registers `runtime.package-jobs` (`app-artifact-handlers.ts:2453`), `runtime.package-state` and `runtime.package-datasources` there. No `runtime.package-handlers` exists, and with the measurement above none is needed. ## Tests - New: `packages/runtime/src/domains/packages-uninstall-handlers-withdrawn.test.ts`, 2 cases, green. - CONTROL through the install-local door: `packages/cloud-connection/src/marketplace-install-local-uninstall-handlers.test.ts` (the real route handler on a real kernel) 6/6 green on this tree: its uninstall leaves no handler under `app:ID`. ### Ablations (one-time, not kept) Each leg mutated on disk through `scripts/ablation-replace.mjs`, objectql legs rebuilt and proved in `dist/` with `scripts/ablation-dist-preflight.mjs`, restored (`git status --porcelain` empty, `--absent` on the rebuilt `dist/`): | Leg | Mutation | Result | |:--|:--|:--| | 1 | no uninstall announcement (packages.ts) | green: the delete-event resync still withdraws them | | 2 | no resync on `state: 'deleted'` mutation events (objectql plugin.ts) | green: the announcement alone withdraws them | | 3 | legs 1 + 2 together | **red**: `no handler is left under the uninstalled package's action: expected [ 'metadata-service' ] to deeply equal []` | | 4 | no read-only refusal on `DELETE` (packages.ts) | **red**: `expected [ 200, undefined ] to deeply equal [ 422, 'WRITABLE_PACKAGE_REQUIRED' ]` | ## Acceptance notes - With the announcement ablated the case stays green only because the fire-and-forget delete-event resync finishes before the door answers on this in-memory store; the announcement is the awaited, deterministic path. Not a defect on main (both paths are present), noted for whoever ever touches either. - Leg 4 shows the one shape where fix A would matter: were the read-only refusal ever lifted for a registered manifest, the door would answer `200` for a package whose handlers the binder holds under `app:ID`. Today that shape is unreachable (ADR-0070 refusal), so nothing is filed. ## Verification Local readings: see the os-dev-report comment on #33624 for the gate list with exit codes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5 --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2dd0e06 commit a32d50b

1 file changed

Lines changed: 237 additions & 0 deletions

File tree

Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* What `DELETE /api/v1/packages/:id` (the protocol uninstall door) leaves
5+
* bound on the engine: nothing of a package it uninstalls.
6+
*
7+
* ## The question
8+
*
9+
* The install-local uninstall door withdraws a package's script-action
10+
* handlers, body hooks and functions from the engine through
11+
* `unbindAppArtifactHandlers`, the inverse of the runtime binder that bound
12+
* them under `app:<id>`. This door calls no such inverse, so it read as if an
13+
* uninstalled package's handlers stayed bound here until a restart.
14+
*
15+
* ## Measured: they do not
16+
*
17+
* Two kinds of package hold handlers on the engine, and neither is left
18+
* running by this door:
19+
*
20+
* 1. A package this door can uninstall is a writable base — authored through
21+
* `POST /packages` and the metadata door. Its script actions and body
22+
* hooks are bound under the environment's authored-handler owner
23+
* (`metadata-service`) by `ObjectQLPlugin`'s authored resync, never under
24+
* `app:<id>`. The door deletes the package's `sys_metadata` rows and then
25+
* announces the withdrawal (`metadata:reloaded`, `app/ID`); the resync
26+
* that announcement runs tears the authored set down and binds only the
27+
* rows that remain. By the time the door answers, the uninstalled
28+
* package's action is refused `404` with nothing run, its hook no longer
29+
* fires, and the engine holds no handler under the key. Another authored
30+
* package's action and hook (the CONTROL) still run.
31+
* 2. A package the runtime binder bound under `app:<id>` — an install-local
32+
* install (`manifest.register`, then `bindAppArtifactHandlers` with the
33+
* door's own options, as `MarketplaceInstallLocalPlugin` does) or a code
34+
* boot — is a registered manifest, which this door refuses as read-only
35+
* (`422 WRITABLE_PACKAGE_REQUIRED`, ADR-0070) before anything moves. The
36+
* package stays installed, so its handler and hook stay bound and run, as
37+
* they must; its uninstall belongs to its own door, which unbinds them.
38+
*
39+
* So the binder's owners never reach this door, and the door needs no handler
40+
* cleanup of its own.
41+
*
42+
* ## The composition
43+
*
44+
* A real `ObjectKernel` with the SQL driver (better-sqlite3 `:memory:`), the
45+
* real `ObjectQLPlugin` (engine, registry, protocol, authored resync) and the
46+
* runtime's `AppPlugin` (the default action runner a script body runs
47+
* through), with an `HttpDispatcher` over that kernel: every call below goes
48+
* through `dispatch`, the routes a server mounts. `OS_HOME` is redirected to a
49+
* temp dir: the doors write a real package-state file under it.
50+
*
51+
* The negative controls (red with the announcement, or the read-only refusal,
52+
* ablated) are one-time ablations cited in the PR, not permanent cases.
53+
*/
54+
55+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
56+
import { mkdtempSync, rmSync } from 'node:fs';
57+
import { tmpdir } from 'node:os';
58+
import { join } from 'node:path';
59+
import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core';
60+
import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql';
61+
import { SqlDriver } from '@objectstack/driver-sql';
62+
import { resolveThrownHttpError } from '@objectstack/types';
63+
import { AppPlugin } from '../app-plugin.js';
64+
import { HttpDispatcher } from '../http-dispatcher.js';
65+
import { bindAppArtifactHandlers } from '../app-artifact-handlers.js';
66+
// Paid at collection, not inside a clocked case: the dispatcher's package domain
67+
// reaches it through a dynamic import (check:test-source-alias).
68+
import '@objectstack/metadata';
69+
70+
const HOST = 'com.qa.uh.host';
71+
const TICKET = 'qa_uh_ticket';
72+
/** The authored package under uninstall. */
73+
const P = 'com.qa.uh.p';
74+
/** The CONTROL: another authored package, never uninstalled. */
75+
const Q = 'com.qa.uh.q';
76+
/** A package bound by the runtime binder under `app:<id>`, the way install-local's install leaves it. */
77+
const BOUND = 'com.qa.uh.bound';
78+
79+
const CALLER = {
80+
userId: 'u_admin', tenantId: 'org_qa', isSystem: false, positions: [], permissions: [],
81+
systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'],
82+
};
83+
84+
const js = (source: string) => ({ language: 'js', source, capabilities: [] });
85+
/** A script action on the ticket whose body answers who ran. */
86+
const action = (name: string, by: string) => ({ name, label: name, objectName: TICKET, type: 'script', body: js(`return { by: '${by}' };`) });
87+
/** A body hook on the ticket that appends `by` to the row's `stamped_by`. */
88+
const hook = (name: string, by: string) => ({
89+
name,
90+
object: TICKET,
91+
events: ['beforeInsert'],
92+
body: js(`const d = ctx.input && ctx.input.data ? ctx.input.data : ctx.input; d.stamped_by = (d.stamped_by || '') + '|${by}';`),
93+
});
94+
95+
const hostStack: any = {
96+
manifest: { id: HOST, name: 'qa_uh_host', version: '1.0.0', type: 'app', namespace: 'qauhhost' },
97+
objects: [{
98+
name: TICKET,
99+
label: 'Ticket',
100+
sharingModel: 'public_read_write',
101+
fields: { name: { type: 'text', label: 'Name' }, stamped_by: { type: 'text', label: 'Stamped by' } },
102+
}],
103+
};
104+
105+
const envSnapshot = { OS_HOME: process.env.OS_HOME };
106+
let home: string;
107+
let kernel: ObjectKernel;
108+
let ql: ObjectQL;
109+
let dispatcher: HttpDispatcher;
110+
111+
beforeAll(async () => {
112+
home = mkdtempSync(join(tmpdir(), 'os-uninstall-handlers-'));
113+
process.env.OS_HOME = home;
114+
kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never);
115+
await kernel.use({
116+
name: 'test.uninstall-handlers.driver',
117+
type: 'standard',
118+
version: '1.0.0',
119+
async init(ctx: PluginContext) {
120+
ctx.registerService('driver.default', new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any));
121+
},
122+
} as Plugin);
123+
await kernel.use(new ObjectQLPlugin());
124+
await kernel.use(new AppPlugin(hostStack, undefined, { skipSeedData: true }));
125+
await kernel.bootstrap();
126+
ql = kernel.getService<ObjectQL>('objectql');
127+
ql.registry.logLevel = 'silent';
128+
dispatcher = new HttpDispatcher(kernel as any, undefined, { enforceProjectMembership: false });
129+
(dispatcher as any).timedResolveExecutionContext = async () => ({ ...CALLER });
130+
}, 60_000);
131+
132+
afterAll(async () => {
133+
await Promise.race([kernel?.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
134+
if (envSnapshot.OS_HOME === undefined) delete process.env.OS_HOME;
135+
else process.env.OS_HOME = envSnapshot.OS_HOME;
136+
rmSync(home, { recursive: true, force: true });
137+
});
138+
139+
/** One request through the dispatcher's routes, answered as the wire answers it. */
140+
async function http(method: string, path: string, body?: unknown, query: Record<string, string> = {}) {
141+
const raw = new Request(`http://localhost/api/v1${path}`, {
142+
method,
143+
headers: { 'content-type': 'application/json' },
144+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
145+
});
146+
try {
147+
const out: any = await dispatcher.dispatch(method, path, body, query, { request: raw } as any, '/api/v1');
148+
const answer = JSON.parse(JSON.stringify(out.response?.body ?? null));
149+
return { status: out.response?.status as number, code: answer?.error?.code as string | undefined, data: answer?.data, body: answer };
150+
} catch (e) {
151+
const thrown = resolveThrownHttpError(e);
152+
return { status: thrown.status, code: thrown.code as string | undefined, data: undefined, body: undefined };
153+
}
154+
}
155+
156+
/** `POST /data/TICKET`, then what every hook that fired appended to the row. */
157+
async function insertTicket(name: string): Promise<{ id: string; stamped: string }> {
158+
const res = await http('POST', `/data/${TICKET}`, { name });
159+
expect(res.status, JSON.stringify(res.body)).toBe(201);
160+
const id = String(res.data?.id);
161+
const rows = (await ql.find(TICKET, { where: { id }, fields: ['id', 'stamped_by'], context: { isSystem: true } })) as Array<Record<string, unknown>>;
162+
return { id, stamped: String(rows[0]?.stamped_by ?? '') };
163+
}
164+
165+
/** `POST /actions/TICKET/NAME/RID`. */
166+
const run = (name: string, recordId: string) => http('POST', `/actions/${TICKET}/${name}/${recordId}`, {});
167+
168+
/** The owners holding a handler under `TICKET`'s action `name`, from the engine's listing. */
169+
const holdersOf = (name: string) => ql.listRegisteredActions()
170+
.filter((row) => row.objectName === TICKET && row.actionName === name)
171+
.map((row) => row.package);
172+
173+
/** An authored package: installed through `POST /packages`, an action and a body hook saved under it through the metadata door. */
174+
async function authorPackage(id: string, by: string) {
175+
const installed = await http('POST', '/packages', { manifest: { id, name: id.replace(/\./g, '_'), version: '1.0.0', type: 'app', namespace: `qauh${by}` } });
176+
expect(installed.status, JSON.stringify(installed.body)).toBe(201);
177+
const savedAction = await http('PUT', `/meta/action/qa_uh_run_${by}`, action(`qa_uh_run_${by}`, by), { package: id });
178+
expect(savedAction.status, JSON.stringify(savedAction.body)).toBe(200);
179+
const savedHook = await http('PUT', `/meta/hook/qa_uh_stamp_${by}`, hook(`qa_uh_stamp_${by}`, by), { package: id });
180+
expect(savedHook.status, JSON.stringify(savedHook.body)).toBe(200);
181+
}
182+
183+
describe('`DELETE /api/v1/packages/:id` leaves nothing of the package it uninstalls bound on the engine', () => {
184+
it('an authored package: once the door answers, its action is refused with nothing run, its hook no longer fires; the CONTROL package still runs', async () => {
185+
await authorPackage(P, 'p');
186+
await authorPackage(Q, 'q');
187+
const before = await insertTicket('before');
188+
// Preconditions: both packages' handlers are bound and run.
189+
expect(before.stamped.split('|').filter(Boolean).sort()).toEqual(['p', 'q']);
190+
expect(holdersOf('qa_uh_run_p')).toEqual(['metadata-service']);
191+
expect((await run('qa_uh_run_p', before.id)).data).toEqual({ by: 'p' });
192+
193+
const deleted = await http('DELETE', `/packages/${P}`);
194+
expect(deleted.status, JSON.stringify(deleted.body)).toBe(200);
195+
expect(deleted.data?.registryRemoved).toBe(true);
196+
197+
// ⭐ No restart, no wait: the door's own answer already found them gone.
198+
expect(holdersOf('qa_uh_run_p'), 'no handler is left under the uninstalled package\'s action').toEqual([]);
199+
const after = await run('qa_uh_run_p', before.id);
200+
expect([after.status, after.code]).toEqual([404, 'RESOURCE_NOT_FOUND']);
201+
expect(after.data, 'the uninstalled package\'s body did not run').toBeUndefined();
202+
const written = await insertTicket('after');
203+
expect(written.stamped, 'only the remaining package\'s hook fired').toBe('|q');
204+
205+
// CONTROL: the other authored package is untouched.
206+
expect(holdersOf('qa_uh_run_q')).toEqual(['metadata-service']);
207+
expect((await run('qa_uh_run_q', written.id)).data).toEqual({ by: 'q' });
208+
}, 60_000);
209+
210+
it('a package the runtime binder bound under `app:<id>` is refused `422` before anything moves, so its handlers stay bound with it', async () => {
211+
// What install-local's install leaves: the registration through the
212+
// `manifest` service, then the runtime binder with the door's options.
213+
const manifest = {
214+
id: BOUND, name: 'qa_uh_bound', version: '1.0.0', type: 'app', namespace: 'qauhbound',
215+
actions: [action('qa_uh_run_bound', 'bound')],
216+
hooks: [hook('qa_uh_stamp_bound', 'bound')],
217+
};
218+
await kernel.getService<{ register(artifact: unknown, options?: { source?: 'code' | 'marketplace' }): unknown }>('manifest')
219+
.register(manifest, { source: 'marketplace' });
220+
const bound = bindAppArtifactHandlers(ql as any, manifest, {
221+
appId: BOUND, logger: { info() {}, warn() {}, error() {}, debug() {} } as any,
222+
source: 'MarketplaceInstallLocal', withholdHooksWithoutBody: true,
223+
});
224+
expect([bound.actions, bound.hooks], 'precondition: its action and hook are bound').toEqual([1, 1]);
225+
expect(holdersOf('qa_uh_run_bound')).toEqual([`app:${BOUND}`]);
226+
227+
const deleted = await http('DELETE', `/packages/${BOUND}`);
228+
expect([deleted.status, deleted.code]).toEqual([422, 'WRITABLE_PACKAGE_REQUIRED']);
229+
230+
// Nothing moved: still installed, so still running.
231+
expect(ql.registry.getPackage(BOUND)).toBeDefined();
232+
expect(holdersOf('qa_uh_run_bound')).toEqual([`app:${BOUND}`]);
233+
const written = await insertTicket('bound');
234+
expect(written.stamped).toContain('|bound');
235+
expect((await run('qa_uh_run_bound', written.id)).data).toEqual({ by: 'bound' });
236+
}, 60_000);
237+
});

0 commit comments

Comments
 (0)