|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#30962] The host seam for package lifecycle state — the platform half (F2) |
| 5 | + * of cloud#3636, under the maintainer's ruling 「AAAA + 三条验收(推荐)」. |
| 6 | + * |
| 7 | + * A hosted container loses the file under `OS_HOME` when it is replaced, so a |
| 8 | + * host supplies the store (`createPackageStateStorePlugin`). The card's three |
| 9 | + * acceptance lines, each pinned through the shipped pieces — a real |
| 10 | + * `ObjectKernel`, the real `ObjectQLPlugin` and `AppPlugin`, and the real |
| 11 | + * `HttpDispatcher` answering the package doors: |
| 12 | + * |
| 13 | + * 1. A host-injected store sees every enable/disable write and seeds boot. |
| 14 | + * 2. A refusing store makes the door fail visibly, with in-memory state |
| 15 | + * unchanged. |
| 16 | + * 3. Without injection, behaviour is unchanged: the file is written as before, |
| 17 | + * and its write failure still only warns. |
| 18 | + * |
| 19 | + * The negative pins (2, and the file half of 3) were each ablated once — the |
| 20 | + * forbidden behaviour put back and watched go red — and the outputs are cited |
| 21 | + * in the PR, not kept as permanent cases. |
| 22 | + */ |
| 23 | + |
| 24 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 25 | +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; |
| 26 | +import { tmpdir } from 'node:os'; |
| 27 | +import { join } from 'node:path'; |
| 28 | +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; |
| 29 | +import { ObjectQLPlugin } from '@objectstack/objectql'; |
| 30 | +import { resolveThrownHttpError } from '@objectstack/types'; |
| 31 | + |
| 32 | +import { AppPlugin } from './app-plugin.js'; |
| 33 | +import { HttpDispatcher } from './http-dispatcher.js'; |
| 34 | +import { |
| 35 | + PACKAGE_STATE_STORE_PLUGIN_NAME, |
| 36 | + PACKAGE_STATE_STORE_SERVICE, |
| 37 | + createPackageStateStorePlugin, |
| 38 | + type PackageStateStore, |
| 39 | +} from './package-state-host-store.js'; |
| 40 | +import { packageStateFileName, setPackageDisabled } from './package-state-store.js'; |
| 41 | + |
| 42 | +const ENVIRONMENT_ID = 'env_host_store'; |
| 43 | +const PKG = 'com.acme.reporting'; |
| 44 | +const OTHER = 'com.acme.billing'; |
| 45 | +const ADMIN = { |
| 46 | + userId: 'u_admin', tenantId: 'org_qa', isSystem: false, |
| 47 | + positions: [], permissions: [], systemPermissions: ['manage_metadata'], |
| 48 | +}; |
| 49 | + |
| 50 | +interface Row { enabled?: boolean; status?: string } |
| 51 | +interface Registry { |
| 52 | + installPackage(manifest: Record<string, unknown>, source: 'code' | 'marketplace' | 'authored'): unknown; |
| 53 | + getPackage(id: string): Row | undefined; |
| 54 | +} |
| 55 | + |
| 56 | +/** An in-memory host store that records every write, and can be told to refuse. */ |
| 57 | +class RecordingStore implements PackageStateStore { |
| 58 | + readonly disabled = new Map<string, Set<string>>(); |
| 59 | + readonly writes: Array<[string | undefined, string, boolean]> = []; |
| 60 | + readonly loads: Array<string | undefined> = []; |
| 61 | + refuseWrites = false; |
| 62 | + refuseLoads = false; |
| 63 | + |
| 64 | + async loadDisabledPackageIds(environmentId: string | undefined): Promise<Iterable<string>> { |
| 65 | + this.loads.push(environmentId); |
| 66 | + if (this.refuseLoads) throw new Error('hosted store offline'); |
| 67 | + return [...(this.disabled.get(environmentId ?? '') ?? [])]; |
| 68 | + } |
| 69 | + |
| 70 | + async setPackageDisabled(environmentId: string | undefined, packageId: string, disabled: boolean): Promise<void> { |
| 71 | + if (this.refuseWrites) throw new Error('hosted store offline'); |
| 72 | + this.writes.push([environmentId, packageId, disabled]); |
| 73 | + const ids = this.disabled.get(environmentId ?? '') ?? new Set<string>(); |
| 74 | + if (disabled) ids.add(packageId); |
| 75 | + else ids.delete(packageId); |
| 76 | + this.disabled.set(environmentId ?? '', ids); |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +let home: string; |
| 81 | +const envSnapshot = { OS_HOME: process.env.OS_HOME, OS_ENVIRONMENT_ID: process.env.OS_ENVIRONMENT_ID }; |
| 82 | +const kernels: ObjectKernel[] = []; |
| 83 | + |
| 84 | +beforeEach(() => { |
| 85 | + home = mkdtempSync(join(tmpdir(), 'os-host-package-state-')); |
| 86 | + process.env.OS_HOME = home; |
| 87 | + delete process.env.OS_ENVIRONMENT_ID; |
| 88 | +}); |
| 89 | + |
| 90 | +afterEach(async () => { |
| 91 | + for (const kernel of kernels.splice(0)) { |
| 92 | + if (kernel.getState() === 'running') await kernel.shutdown(); |
| 93 | + } |
| 94 | + vi.restoreAllMocks(); |
| 95 | + rmSync(home, { recursive: true, force: true }); |
| 96 | + if (envSnapshot.OS_HOME === undefined) delete process.env.OS_HOME; |
| 97 | + else process.env.OS_HOME = envSnapshot.OS_HOME; |
| 98 | + if (envSnapshot.OS_ENVIRONMENT_ID === undefined) delete process.env.OS_ENVIRONMENT_ID; |
| 99 | + else process.env.OS_ENVIRONMENT_ID = envSnapshot.OS_ENVIRONMENT_ID; |
| 100 | +}); |
| 101 | + |
| 102 | +const stateFile = (): string => join(home, 'package-state', packageStateFileName(ENVIRONMENT_ID, process.cwd())); |
| 103 | +const manifestFor = (id: string) => ({ id, name: id, version: '1.0.0', type: 'module' }); |
| 104 | + |
| 105 | +/** |
| 106 | + * Boot an empty environment, with `extra` plugins composed AFTER `AppPlugin` |
| 107 | + * in `use()` order — so a store that still seeds proves the declared ordering, |
| 108 | + * not the slot it was given. |
| 109 | + */ |
| 110 | +async function boot(extra: Plugin[] = []): Promise<{ kernel: ObjectKernel; registry: Registry }> { |
| 111 | + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); |
| 112 | + kernels.push(kernel); |
| 113 | + await kernel.use(new ObjectQLPlugin({})); |
| 114 | + await kernel.use(new AppPlugin({}, { environmentId: ENVIRONMENT_ID, organizationId: 'org_qa' })); |
| 115 | + for (const plugin of extra) await kernel.use(plugin); |
| 116 | + await kernel.bootstrap(); |
| 117 | + return { kernel, registry: kernel.getService<{ registry: Registry }>('objectql').registry }; |
| 118 | +} |
| 119 | + |
| 120 | +const codeOf = (body: any): unknown => (body?.error && typeof body.error === 'object' ? body.error.code : body?.code); |
| 121 | + |
| 122 | +/** What the runtime dispatcher answers the admin on `PATCH /packages/:id/<verb>`. */ |
| 123 | +async function patch(kernel: ObjectKernel, id: string, verb: 'enable' | 'disable') { |
| 124 | + const path = `/packages/${encodeURIComponent(id)}/${verb}`; |
| 125 | + const dispatcher = new HttpDispatcher(kernel as any, undefined, { enforceProjectMembership: false }); |
| 126 | + (dispatcher as any).timedResolveExecutionContext = async () => ({ ...ADMIN }); |
| 127 | + const request = new Request(`http://localhost/api/v1${path}`, { |
| 128 | + method: 'PATCH', headers: { 'content-type': 'application/json' }, body: '{}', |
| 129 | + }); |
| 130 | + try { |
| 131 | + const out: any = await dispatcher.dispatch('PATCH', path, {}, {}, { request, environmentId: ENVIRONMENT_ID } as any, '/api/v1'); |
| 132 | + return { status: out.response?.status as number | undefined, code: codeOf(out.response?.body), message: out.response?.body?.error?.message as string | undefined }; |
| 133 | + } catch (e) { |
| 134 | + const thrown = resolveThrownHttpError(e); |
| 135 | + return { status: thrown.status as number | undefined, code: thrown.code as unknown, message: undefined }; |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +describe('[#30962] a host-injected package-state store', () => { |
| 140 | + it('seeds the boot from the host store — not from the file — even when composed after AppPlugin', async () => { |
| 141 | + const store = new RecordingStore(); |
| 142 | + store.disabled.set(ENVIRONMENT_ID, new Set([PKG])); |
| 143 | + // The file says the OPPOSITE: a host store must be the only source. |
| 144 | + setPackageDisabled(ENVIRONMENT_ID, OTHER, true); |
| 145 | + |
| 146 | + const { registry } = await boot([createPackageStateStorePlugin(store)]); |
| 147 | + registry.installPackage(manifestFor(PKG), 'authored'); |
| 148 | + registry.installPackage(manifestFor(OTHER), 'authored'); |
| 149 | + |
| 150 | + expect(store.loads).toEqual([ENVIRONMENT_ID]); |
| 151 | + expect(registry.getPackage(PKG)).toMatchObject({ enabled: false, status: 'disabled' }); |
| 152 | + expect(registry.getPackage(OTHER)).toMatchObject({ enabled: true }); |
| 153 | + }); |
| 154 | + |
| 155 | + it('sees every enable and disable write, and the file under OS_HOME is never written', async () => { |
| 156 | + const store = new RecordingStore(); |
| 157 | + const { kernel, registry } = await boot([createPackageStateStorePlugin(store)]); |
| 158 | + registry.installPackage(manifestFor(PKG), 'authored'); |
| 159 | + |
| 160 | + expect(await patch(kernel, PKG, 'disable')).toMatchObject({ status: 200 }); |
| 161 | + expect(registry.getPackage(PKG)?.enabled).toBe(false); |
| 162 | + expect(await patch(kernel, PKG, 'enable')).toMatchObject({ status: 200 }); |
| 163 | + expect(registry.getPackage(PKG)?.enabled).toBe(true); |
| 164 | + |
| 165 | + expect(store.writes).toEqual([ |
| 166 | + [ENVIRONMENT_ID, PKG, true], |
| 167 | + [ENVIRONMENT_ID, PKG, false], |
| 168 | + ]); |
| 169 | + expect(existsSync(join(home, 'package-state'))).toBe(false); |
| 170 | + }); |
| 171 | + |
| 172 | + it('a disable written to the host store is what the NEXT boot seeds', async () => { |
| 173 | + const store = new RecordingStore(); |
| 174 | + const first = await boot([createPackageStateStorePlugin(store)]); |
| 175 | + first.registry.installPackage(manifestFor(PKG), 'authored'); |
| 176 | + expect(await patch(first.kernel, PKG, 'disable')).toMatchObject({ status: 200 }); |
| 177 | + await first.kernel.shutdown(); |
| 178 | + |
| 179 | + // A replaced container: a fresh OS_HOME, the same host store. |
| 180 | + process.env.OS_HOME = mkdtempSync(join(home, 'replaced-')); |
| 181 | + const second = await boot([createPackageStateStorePlugin(store)]); |
| 182 | + second.registry.installPackage(manifestFor(PKG), 'authored'); |
| 183 | + expect(second.registry.getPackage(PKG)).toMatchObject({ enabled: false, status: 'disabled' }); |
| 184 | + }); |
| 185 | + |
| 186 | + it('a refusing store fails the disable door visibly, and the package stays enabled', async () => { |
| 187 | + const store = new RecordingStore(); |
| 188 | + const { kernel, registry } = await boot([createPackageStateStorePlugin(store)]); |
| 189 | + registry.installPackage(manifestFor(PKG), 'authored'); |
| 190 | + store.refuseWrites = true; |
| 191 | + |
| 192 | + const answer = await patch(kernel, PKG, 'disable'); |
| 193 | + |
| 194 | + expect(answer).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' }); |
| 195 | + expect(answer.message).toMatch(/^Package 'com\.acme\.reporting' was not disabled: the package-state store refused/); |
| 196 | + expect(registry.getPackage(PKG)).toMatchObject({ enabled: true, status: 'installed' }); |
| 197 | + expect(store.disabled.get(ENVIRONMENT_ID)).toBeUndefined(); |
| 198 | + expect(existsSync(join(home, 'package-state'))).toBe(false); |
| 199 | + }); |
| 200 | + |
| 201 | + it('a refusing store fails the enable door visibly, and the package stays disabled', async () => { |
| 202 | + const store = new RecordingStore(); |
| 203 | + const { kernel, registry } = await boot([createPackageStateStorePlugin(store)]); |
| 204 | + registry.installPackage(manifestFor(PKG), 'authored'); |
| 205 | + expect(await patch(kernel, PKG, 'disable')).toMatchObject({ status: 200 }); |
| 206 | + store.refuseWrites = true; |
| 207 | + |
| 208 | + const answer = await patch(kernel, PKG, 'enable'); |
| 209 | + |
| 210 | + expect(answer).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' }); |
| 211 | + expect(registry.getPackage(PKG)).toMatchObject({ enabled: false, status: 'disabled' }); |
| 212 | + expect([...(store.disabled.get(ENVIRONMENT_ID) ?? [])]).toEqual([PKG]); |
| 213 | + }); |
| 214 | + |
| 215 | + it('an unknown package still answers 404 and writes nothing to the store', async () => { |
| 216 | + const store = new RecordingStore(); |
| 217 | + const { kernel } = await boot([createPackageStateStorePlugin(store)]); |
| 218 | + |
| 219 | + expect(await patch(kernel, 'com.acme.absent', 'disable')).toMatchObject({ status: 404 }); |
| 220 | + expect(await patch(kernel, 'com.acme.absent', 'enable')).toMatchObject({ status: 404 }); |
| 221 | + expect(store.writes).toEqual([]); |
| 222 | + }); |
| 223 | + |
| 224 | + it('a host store whose boot read throws fails the boot, naming the store', async () => { |
| 225 | + const store = new RecordingStore(); |
| 226 | + store.refuseLoads = true; |
| 227 | + |
| 228 | + await expect(boot([createPackageStateStorePlugin(store)])).rejects.toThrow( |
| 229 | + new RegExp(`package-state store \\(${PACKAGE_STATE_STORE_PLUGIN_NAME.replace(/\./g, '\\.')}\\) could not read`), |
| 230 | + ); |
| 231 | + }); |
| 232 | + |
| 233 | + it('a store registered under the service name by a plugin AppPlugin is not ordered after is refused at start', async () => { |
| 234 | + const store = new RecordingStore(); |
| 235 | + const late: Plugin = { |
| 236 | + name: 'qa.host-registers-its-own-store', |
| 237 | + init: (ctx: PluginContext) => { ctx.registerService(PACKAGE_STATE_STORE_SERVICE, store); }, |
| 238 | + }; |
| 239 | + |
| 240 | + await expect(boot([late])).rejects.toThrow(/createPackageStateStorePlugin/); |
| 241 | + }); |
| 242 | + |
| 243 | + it('createPackageStateStorePlugin refuses a store missing either method', () => { |
| 244 | + expect(() => createPackageStateStorePlugin({ loadDisabledPackageIds: () => [] } as never)).toThrow(TypeError); |
| 245 | + expect(() => createPackageStateStorePlugin(null as never)).toThrow(TypeError); |
| 246 | + }); |
| 247 | +}); |
| 248 | + |
| 249 | +describe('[#30962] without a host store, behaviour is unchanged', () => { |
| 250 | + it('the disable and enable doors write the file under OS_HOME exactly as before', async () => { |
| 251 | + const { kernel, registry } = await boot(); |
| 252 | + registry.installPackage(manifestFor(PKG), 'authored'); |
| 253 | + |
| 254 | + expect(await patch(kernel, PKG, 'disable')).toMatchObject({ status: 200 }); |
| 255 | + expect(readFileSync(stateFile(), 'utf8')).toBe(`{\n "disabled": [\n "${PKG}"\n ]\n}\n`); |
| 256 | + expect(registry.getPackage(PKG)?.enabled).toBe(false); |
| 257 | + |
| 258 | + expect(await patch(kernel, PKG, 'enable')).toMatchObject({ status: 200 }); |
| 259 | + expect(readFileSync(stateFile(), 'utf8')).toBe(`{\n "disabled": []\n}\n`); |
| 260 | + expect(registry.getPackage(PKG)?.enabled).toBe(true); |
| 261 | + }); |
| 262 | + |
| 263 | + it('a file that cannot be written still only warns: the disable lands in memory and answers 200', async () => { |
| 264 | + const { kernel, registry } = await boot(); |
| 265 | + registry.installPackage(manifestFor(PKG), 'authored'); |
| 266 | + // An OS_HOME that is a FILE: the state directory under it cannot be made. |
| 267 | + const blocked = join(home, 'not-a-directory'); |
| 268 | + writeFileSync(blocked, ''); |
| 269 | + process.env.OS_HOME = blocked; |
| 270 | + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); |
| 271 | + |
| 272 | + expect(await patch(kernel, PKG, 'disable')).toMatchObject({ status: 200 }); |
| 273 | + expect(registry.getPackage(PKG)).toMatchObject({ enabled: false, status: 'disabled' }); |
| 274 | + expect(warn).toHaveBeenCalledWith('[handlePackages] failed to persist disable state', expect.objectContaining({ id: PKG })); |
| 275 | + }); |
| 276 | +}); |
0 commit comments