Skip to content

Commit 1ce052a

Browse files
committed
wip(runtime): host-injectable package-state store
Claude-Session: https://claude.ai/code/session_01L9qibvSvYrx9SiZMbSoehj Co-Authored-By: Claude <noreply@anthropic.com>
1 parent acd190b commit 1ce052a

4 files changed

Lines changed: 381 additions & 30 deletions

File tree

‎packages/runtime/src/app-plugin.ts‎

Lines changed: 107 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { mergeSeedDatasets, readSeedDatasets, registerSeedReplayerOnce } from '.
3030
import { describeSeedLocale, resolveSeedLocaleForLoad } from './seed-locale.js';
3131
import { declareSeedSource, recordOrganizationReplay, type SeedLandingReport } from './seed-settlement.js';
3232
import { loadDisabledPackageIds } from './package-state-store.js';
33+
import { asPackageStateStore, PACKAGE_STATE_STORE_PLUGIN_NAME } from './package-state-host-store.js';
3334
import type { IFieldFileService, IMetadataService, IObjectQLEngine, II18nService } from '@objectstack/spec/contracts';
3435
import { FIELD_FILE_SERVICE } from '@objectstack/spec/contracts';
3536
import { normalizeFlowFunctionEntry, type NormalizedFlowFunction } from '@objectstack/spec/automation';
@@ -171,12 +172,19 @@ export class AppPlugin implements Plugin {
171172
* `start()`, and a database it refuses must be left as it found it — so this
172173
* plugin's `start()`, which loads the inline seed, runs only after the guard
173174
* has judged. Order-if-present: every other kernel is unchanged.
175+
*
176+
* The host's package-state store (`PACKAGE_STATE_STORE_PLUGIN_NAME`,
177+
* `./package-state-host-store.ts`, spelled as a literal for the same
178+
* reason): `init()` seeds the registry's disabled set from it, so it must
179+
* be registered first. Order-if-present: a kernel without it seeds from
180+
* the file under `OS_HOME`, as before.
174181
*/
175182
optionalDependencies = [
176183
'com.objectstack.engine.objectql',
177184
'com.objectstack.organization-ownership-boot-guard',
178185
'com.objectstack.auth',
179186
'com.objectstack.auth.identity-objects',
187+
'com.objectstack.package-state-store',
180188
];
181189
/**
182190
* The one init-time service this plugin CANNOT degrade without: a
@@ -233,6 +241,14 @@ export class AppPlugin implements Plugin {
233241
* disagree about which datasources this artifact registers from code — and
234242
* the residual-owner warning prints once, at whichever read comes first.
235243
*/
244+
/**
245+
* Which store the boot seed read: `'host'` (the registered
246+
* `package-state-store` service) or `'file'` (the file under `OS_HOME`),
247+
* `undefined` when there was no engine to seed. `start()` holds a `'file'`
248+
* seed against a host store that registered after it — see
249+
* {@link refuseLatePackageStateStore}.
250+
*/
251+
private packageStateSeedSource?: 'host' | 'file';
236252
private codeDatasourceOwners?: Array<{ datasource: any; owner: { packageId?: string; packageVersion?: string } }>;
237253
/**
238254
* [#23649] Set once {@link installDatasourceMapping} has handed the stack's
@@ -561,7 +577,7 @@ export class AppPlugin implements Plugin {
561577
// envs, and a package an operator had disabled came back ENABLED on
562578
// every restart. The seed must land before ANY registration path runs,
563579
// which is Phase 1, unconditionally.
564-
this.seedPersistedDisabledPackages(ctx);
580+
await this.seedPersistedDisabledPackages(ctx);
565581
if (this.empty) {
566582
ctx.logger.debug('[AppPlugin] empty env — no app payload, skipping init', {
567583
pluginName: this.name,
@@ -686,22 +702,64 @@ export class AppPlugin implements Plugin {
686702
* because that decomposition happens at the `manifest.register()` call at
687703
* the end of init.
688704
*
689-
* Best-effort — never block boot on this. Degrades silently on kernels
690-
* with no engine (metadata-only one-shot commands, mock-engine tests).
705+
* The store is the host's when one is registered as the
706+
* `package-state-store` service (`createPackageStateStorePlugin`,
707+
* `./package-state-host-store.ts`, ordered ahead of this plugin by
708+
* `optionalDependencies`), and the file under `OS_HOME` otherwise.
709+
*
710+
* The file read is best-effort, exactly as before: it never blocks boot.
711+
* A HOST store's read that throws fails the boot instead, because seeding
712+
* nothing would bring every module its operator switched off back on, and
713+
* nothing would look wrong (ADR-0025 §3.5 M1 makes the same call for the
714+
* installed-plugin loader: a disable that cannot be read is not read as
715+
* "nothing is disabled"). Degrades silently on kernels with no engine
716+
* (metadata-only one-shot commands, mock-engine tests).
691717
*/
692-
private seedPersistedDisabledPackages(ctx: PluginContext): void {
718+
private async seedPersistedDisabledPackages(ctx: PluginContext): Promise<void> {
719+
let setter: ((ids: Iterable<string>) => void) | undefined;
720+
let ql: { registry?: { setInitialDisabledPackageIds?: (ids: Iterable<string>) => void } } | undefined;
693721
try {
694-
const ql = ctx.getService<{ registry?: { setInitialDisabledPackageIds?: (ids: Iterable<string>) => void } }>('objectql');
695-
const setter = ql?.registry?.setInitialDisabledPackageIds;
696-
if (typeof setter === 'function') {
697-
const disabled = loadDisabledPackageIds(this.projectContext?.environmentId);
698-
if (disabled.size > 0) {
699-
setter.call(ql!.registry, disabled);
700-
ctx.logger.info('[AppPlugin] seeded persisted disabled packages', {
701-
environmentId: this.projectContext?.environmentId,
702-
disabled: Array.from(disabled),
703-
});
704-
}
722+
ql = ctx.getService<{ registry?: { setInitialDisabledPackageIds?: (ids: Iterable<string>) => void } }>('objectql');
723+
setter = ql?.registry?.setInitialDisabledPackageIds;
724+
} catch {
725+
// No engine on this kernel — nothing to seed.
726+
}
727+
if (typeof setter !== 'function') return;
728+
const hostStore = this.registeredPackageStateStore(ctx);
729+
this.packageStateSeedSource = hostStore ? 'host' : 'file';
730+
if (hostStore) {
731+
let disabled: Set<string>;
732+
try {
733+
disabled = new Set(
734+
Array.from(await hostStore.loadDisabledPackageIds(this.projectContext?.environmentId))
735+
.filter((id): id is string => typeof id === 'string'),
736+
);
737+
} catch (err) {
738+
throw new Error(
739+
`[AppPlugin] the host's package-state store (${PACKAGE_STATE_STORE_PLUGIN_NAME}) could not read `
740+
+ `which packages are disabled, so the boot stops rather than bring them back enabled: `
741+
+ `${(err as Error)?.message ?? String(err)}`,
742+
{ cause: err },
743+
);
744+
}
745+
if (disabled.size > 0) {
746+
setter.call(ql!.registry, disabled);
747+
ctx.logger.info('[AppPlugin] seeded persisted disabled packages', {
748+
environmentId: this.projectContext?.environmentId,
749+
store: 'host',
750+
disabled: Array.from(disabled),
751+
});
752+
}
753+
return;
754+
}
755+
try {
756+
const disabled = loadDisabledPackageIds(this.projectContext?.environmentId);
757+
if (disabled.size > 0) {
758+
setter.call(ql!.registry, disabled);
759+
ctx.logger.info('[AppPlugin] seeded persisted disabled packages', {
760+
environmentId: this.projectContext?.environmentId,
761+
disabled: Array.from(disabled),
762+
});
705763
}
706764
} catch (err) {
707765
ctx.logger.warn('[AppPlugin] failed to seed persisted package state', {
@@ -710,6 +768,39 @@ export class AppPlugin implements Plugin {
710768
}
711769
}
712770

771+
/**
772+
* The host's package-state store, or `undefined` when this kernel has
773+
* none. The service name is a literal so `check:init-service-contract`
774+
* can hold this init-time read to the `optionalDependencies` entry above.
775+
*/
776+
private registeredPackageStateStore(ctx: PluginContext) {
777+
let registered: unknown;
778+
try {
779+
registered = ctx.getService('package-state-store');
780+
} catch {
781+
return undefined;
782+
}
783+
return asPackageStateStore(registered);
784+
}
785+
786+
/**
787+
* A boot that seeded from the FILE, on a kernel where a host store is
788+
* registered by now, read the wrong store: the host's plugin initialized
789+
* after this one, so the disables it holds were never seeded while the
790+
* package doors will write to it. Refused by name, with the fix, rather
791+
* than served with two stores in play.
792+
*/
793+
private refuseLatePackageStateStore(ctx: PluginContext): void {
794+
if (this.packageStateSeedSource !== 'file') return;
795+
if (this.registeredPackageStateStore(ctx) === undefined) return;
796+
throw new Error(
797+
`[AppPlugin] a package-state store was registered as the 'package-state-store' service after this `
798+
+ `plugin's boot seed had already read the file under OS_HOME, so the packages that store holds as `
799+
+ `disabled would come back enabled. Register it with createPackageStateStorePlugin(store) from `
800+
+ `@objectstack/runtime, which is ordered ahead of AppPlugin.`,
801+
);
802+
}
803+
713804
/**
714805
* Install the engine's DEFAULT hook body runner (`engine.setDefaultBodyRunner`).
715806
*
@@ -1240,6 +1331,7 @@ export class AppPlugin implements Plugin {
12401331
}
12411332

12421333
start = async (ctx: PluginContext) => {
1334+
this.refuseLatePackageStateStore(ctx);
12431335
if (this.empty) {
12441336
ctx.logger.debug('[AppPlugin] empty env — no app payload, skipping start', {
12451337
pluginName: this.name,

‎packages/runtime/src/domains/packages.ts‎

Lines changed: 124 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,9 @@ import { repeatedQueryParamMessage, unknownQueryParamRefusalMessage } from '@obj
152152
// defect (#6928) this module exists to stop anyone writing again.
153153
import { parseBooleanParam } from '../query-param.js';
154154
import { setPackageDisabled } from '../package-state-store.js';
155+
// [#30962] The host seam for the same state: a store a host registers as the
156+
// `package-state-store` service replaces the file at every door below.
157+
import { asPackageStateStore, PACKAGE_STATE_STORE_SERVICE } from '../package-state-host-store.js';
155158
import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatcher.js';
156159
import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js';
157160
import { readDispatchedBody } from '../deferred-request-body.js';
@@ -753,6 +756,99 @@ interface PackageRowRegistryHost {
753756
};
754757
}
755758

759+
/**
760+
* [#30962] A host's package-state store refused a write (or its lookup
761+
* faulted). Raised by {@link writePackageState} only for a HOST store: the
762+
* file's own failure is rethrown as it is, so the file default's handling
763+
* stays exactly what it was.
764+
*/
765+
class HostPackageStateRefusal extends Error {
766+
constructor(readonly packageId: string, cause: unknown) {
767+
super((cause as Error)?.message ?? String(cause), { cause });
768+
this.name = 'HostPackageStateRefusal';
769+
}
770+
}
771+
772+
/**
773+
* [#30962] Write `packageId`'s disabled flag to this environment's package-state
774+
* store: the host's when one is registered as the `package-state-store`
775+
* service (`../package-state-host-store.ts`), the file under `OS_HOME`
776+
* otherwise. Resolved through the CLASSIFIED lookup, so a host store whose
777+
* factory throws refuses the write instead of reading as "no host store" and
778+
* landing the write in a file nobody reads.
779+
*/
780+
async function writePackageState(
781+
deps: DomainHandlerDeps,
782+
context: HttpProtocolContext,
783+
packageId: string,
784+
disabled: boolean,
785+
): Promise<void> {
786+
let host;
787+
try {
788+
host = asPackageStateStore(await deps.resolveServiceOrLoud(context, PACKAGE_STATE_STORE_SERVICE));
789+
} catch (err) {
790+
throw new HostPackageStateRefusal(packageId, err);
791+
}
792+
if (!host) {
793+
setPackageDisabled(context?.environmentId, packageId, disabled);
794+
return;
795+
}
796+
try {
797+
await host.setPackageDisabled(context?.environmentId, packageId, disabled);
798+
} catch (err) {
799+
throw new HostPackageStateRefusal(packageId, err);
800+
}
801+
}
802+
803+
/**
804+
* [#30962, cloud#3636 ruling acceptance line 1] The enable and disable doors'
805+
* answer to a host store that refused: nothing changed in memory (the doors
806+
* write BEFORE they switch the package), so the door says so, and that the
807+
* same request can be retried, instead of answering a switch the store does
808+
* not hold. The standard `SERVICE_UNAVAILABLE`: the store, not the request,
809+
* is what failed.
810+
*/
811+
function hostPackageStateRefused(
812+
deps: DomainHandlerDeps,
813+
refusal: HostPackageStateRefusal,
814+
verb: 'enabled' | 'disabled',
815+
): HttpDispatcherResult {
816+
return {
817+
handled: true,
818+
response: deps.error(
819+
`Package '${refusal.packageId}' was not ${verb}: the package-state store refused to record it, so `
820+
+ `nothing changed. Retry once the store accepts writes. (${refusal.message})`,
821+
503,
822+
{ code: 'SERVICE_UNAVAILABLE' },
823+
),
824+
};
825+
}
826+
827+
/**
828+
* [#30962] {@link writePackageState} for the doors whose package change has
829+
* ALREADY landed when they write (install, delete): the request is not undone
830+
* over the state store. A host store's refusal is logged at `error` here, once
831+
* per failed write, naming what is not durable; the file's failure is rethrown
832+
* to the caller's existing `warn`, unchanged.
833+
*/
834+
async function writePackageStateAfterChange(
835+
deps: DomainHandlerDeps,
836+
context: HttpProtocolContext,
837+
packageId: string,
838+
disabled: boolean,
839+
): Promise<void> {
840+
try {
841+
await writePackageState(deps, context, packageId, disabled);
842+
} catch (err) {
843+
if (!(err instanceof HostPackageStateRefusal)) throw err;
844+
console.error(
845+
`[handlePackages] the package-state store refused to record package '${packageId}' as `
846+
+ `${disabled ? 'disabled' : 'enabled'}: this process serves it that way, but the next boot reads the `
847+
+ `store and will not. Switch it again once the store accepts writes. (${err.message})`,
848+
);
849+
}
850+
}
851+
756852
/**
757853
* [#30377] An enable of a disabled package recomputes the roll-up summaries the
758854
* package adds to other packages' objects by extension (`ObjectQL`'s
@@ -1914,12 +2010,14 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin
19142010
// explicit action left there. #18058's «每一次 install 都持久化它返回
19152011
// 的状态» is unchanged; what changed is which state that is.
19162012
//
1917-
// Same best-effort try/catch as `PATCH /packages/:id/enable` below:
1918-
// the in-memory install already succeeded, so a state-file failure
1919-
// must not turn a 201 into a 500.
2013+
// Best-effort: the in-memory install already succeeded, so a
2014+
// state-store failure must not turn a 201 into a 500. [#30962] A
2015+
// host store's refusal is logged at `error` instead
2016+
// (`writePackageStateAfterChange`); only the enable and disable
2017+
// doors, which write before they switch, answer it.
19202018
const rowDisabled = pkg?.enabled === false;
19212019
try {
1922-
setPackageDisabled(_context?.environmentId, pkgId, rowDisabled);
2020+
await writePackageStateAfterChange(deps, _context, pkgId, rowDisabled);
19232021
} catch (err) {
19242022
console.warn('[handlePackages] failed to persist enableOnInstall', { id: pkgId, disabled: rowDisabled, error: (err as Error)?.message });
19252023
}
@@ -1936,14 +2034,20 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin
19362034
const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Enabling package "${id}"`);
19372035
if (walled) return walled;
19382036
const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused;
1939-
const pkg = registry.enablePackage(id);
1940-
if (!pkg) return { handled: true, response: deps.error(`Package '${id}' not found`, 404) };
1941-
await summaryRefreshSettled(qlService);
2037+
// [#30962] The state store FIRST, the registry second: a host store
2038+
// that refuses leaves the package exactly as it was, and the door
2039+
// answers the refusal (`hostPackageStateRefused`). The file keeps
2040+
// its best-effort `warn`, as before.
2041+
if (!registry.getPackage(id)) return { handled: true, response: deps.error(`Package '${id}' not found`, 404) };
19422042
try {
1943-
setPackageDisabled(_context?.environmentId, id, false);
2043+
await writePackageState(deps, _context, id, false);
19442044
} catch (err) {
2045+
if (err instanceof HostPackageStateRefusal) return hostPackageStateRefused(deps, err, 'enabled');
19452046
console.warn('[handlePackages] failed to persist enable state', { id, error: (err as Error)?.message });
19462047
}
2048+
const pkg = registry.enablePackage(id);
2049+
if (!pkg) return { handled: true, response: deps.error(`Package '${id}' not found`, 404) };
2050+
await summaryRefreshSettled(qlService);
19472051
return { handled: true, response: deps.success(pkg) };
19482052
}
19492053

@@ -1970,13 +2074,18 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin
19702074
? null
19712075
: requireWritablePackage(deps, qlService, id, 'disable');
19722076
if (readOnly) return readOnly;
1973-
const pkg = registry.disablePackage(id);
1974-
if (!pkg) return { handled: true, response: deps.error(`Package '${id}' not found`, 404) };
2077+
// [#30962] The state store FIRST, the registry second, exactly as
2078+
// the enable door above: a host store that refuses leaves the
2079+
// package enabled and served, and the door answers the refusal.
2080+
if (!registry.getPackage(id)) return { handled: true, response: deps.error(`Package '${id}' not found`, 404) };
19752081
try {
1976-
setPackageDisabled(_context?.environmentId, id, true);
2082+
await writePackageState(deps, _context, id, true);
19772083
} catch (err) {
2084+
if (err instanceof HostPackageStateRefusal) return hostPackageStateRefused(deps, err, 'disabled');
19782085
console.warn('[handlePackages] failed to persist disable state', { id, error: (err as Error)?.message });
19792086
}
2087+
const pkg = registry.disablePackage(id);
2088+
if (!pkg) return { handled: true, response: deps.error(`Package '${id}' not found`, 404) };
19802089
return { handled: true, response: deps.success(pkg) };
19812090
}
19822091

@@ -3127,12 +3236,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin
31273236
// whenever its stored row is gone, even if the running registry
31283237
// refused the withdrawal above.
31293238
//
3130-
// Same best-effort try/catch as the install and PATCH arms above:
3131-
// the uninstall itself already happened, so a state-file failure
3132-
// must not turn it into a 500.
3239+
// Same best-effort try/catch as the install arm above: the
3240+
// uninstall itself already happened, so a state-store failure must
3241+
// not turn it into a 500.
31333242
if (persists ? existed : registryRemoved) {
31343243
try {
3135-
setPackageDisabled(_context?.environmentId, id, false);
3244+
await writePackageStateAfterChange(deps, _context, id, false);
31363245
} catch (err) {
31373246
console.warn('[handlePackages] failed to clear persisted disable state on delete', { id, error: (err as Error)?.message });
31383247
}

0 commit comments

Comments
 (0)