Skip to content

Commit 240082d

Browse files
committed
fix(service-automation): stored connector entries wait for every plugin to start (WIP)
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oNHddQQdvMrpeQxiJ
1 parent 1c5b177 commit 240082d

6 files changed

Lines changed: 285 additions & 4 deletions

File tree

‎packages/core/src/kernel-base.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,22 @@ export abstract class ObjectKernelBase {
328328
return this.state;
329329
}
330330

331+
/**
332+
* Whether `bootstrap()` dispatches the boot-phase hooks — `kernel:ready`,
333+
* `kernel:bootstrapped` and `kernel:listening` — once every plugin's
334+
* `start()` has run. A kernel on this base always does, so this answers
335+
* `true`.
336+
*
337+
* Read-only. It is for a plugin that leaves part of its start to one of
338+
* those hooks and must know, during its own `start()`, that the hook will
339+
* come; where the answer is `false` (or a host does not say), it keeps
340+
* that work in `start()`. `ObjectKernel` answers from its
341+
* `bootPhaseHooks` option.
342+
*/
343+
dispatchesBootPhaseHooks(): boolean {
344+
return true;
345+
}
346+
331347
/**
332348
* Get all registered plugins
333349
*/

‎packages/core/src/kernel.boot-phase-hooks.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,22 @@ describe('ObjectKernel bootPhaseHooks', () => {
118118
});
119119

120120
describe('bootPhaseHooks: false', () => {
121+
it('dispatchesBootPhaseHooks() answers false, read by a plugin during its own start()', async () => {
122+
const { plugins } = composition();
123+
const read: unknown[] = [];
124+
const reader: Plugin = {
125+
name: 'test.reader',
126+
version: '1.0.0',
127+
start: async (ctx) => { read.push(ctx.getKernel().dispatchesBootPhaseHooks()); },
128+
};
129+
const kernel = track(newKernel({ bootPhaseHooks: false }));
130+
131+
await boot(kernel, [...plugins, reader]);
132+
133+
expect(read).toEqual([false]);
134+
expect(kernel.dispatchesBootPhaseHooks()).toBe(false);
135+
});
136+
121137
it('keeps every definition registered in init() and start(), and the kernel runs', async () => {
122138
const { plugins } = composition();
123139
const kernel = track(newKernel({ bootPhaseHooks: false }));
@@ -221,6 +237,21 @@ describe('ObjectKernel bootPhaseHooks', () => {
221237
['true', { bootPhaseHooks: true }],
222238
['undefined', { bootPhaseHooks: undefined }],
223239
] as Array<[string, ObjectKernelConfig]>)('bootPhaseHooks %s (control)', (_label, extra) => {
240+
it('dispatchesBootPhaseHooks() answers true, read by a plugin during its own start()', async () => {
241+
const { plugins } = composition();
242+
const read: unknown[] = [];
243+
const reader: Plugin = {
244+
name: 'test.reader',
245+
version: '1.0.0',
246+
start: async (ctx) => { read.push(ctx.getKernel().dispatchesBootPhaseHooks()); },
247+
};
248+
const kernel = track(newKernel(extra));
249+
250+
await boot(kernel, [...plugins, reader]);
251+
252+
expect(read).toEqual([true]);
253+
});
254+
224255
it('fires all three hooks in order and keeps every definition, the kernel:ready one included', async () => {
225256
const { plugins, spies, order } = composition();
226257
const kernel = track(newKernel(extra));

‎packages/core/src/kernel.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -891,6 +891,21 @@ export class ObjectKernel {
891891
return this.state;
892892
}
893893

894+
/**
895+
* Whether `bootstrap()` dispatches the boot-phase hooks — `kernel:ready`,
896+
* `kernel:bootstrapped` and `kernel:listening` — once every plugin's
897+
* `start()` has run: `false` exactly when {@link ObjectKernelConfig.bootPhaseHooks}
898+
* is `false`, `true` otherwise.
899+
*
900+
* Read-only; the option is fixed at construction. It is for a plugin that
901+
* leaves part of its start to one of those hooks and must know, during its
902+
* own `start()`, that the hook will come; where the answer is `false`, it
903+
* keeps that work in `start()`.
904+
*/
905+
dispatchesBootPhaseHooks(): boolean {
906+
return this.config.bootPhaseHooks !== false;
907+
}
908+
894909
// Private methods
895910

896911
private async initPluginWithTimeout(plugin: PluginMetadata): Promise<void> {

‎packages/core/src/lite-kernel.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,22 @@ describe('LiteKernel with Configurable Logger', () => {
271271
expect(order).toEqual(['kernel:ready', 'kernel:bootstrapped', 'kernel:listening']);
272272
});
273273

274+
it('dispatchesBootPhaseHooks() answers true, read by a plugin during its own start()', async () => {
275+
const read: unknown[] = [];
276+
const plugin: Plugin = {
277+
name: 'boot-phase-reader-plugin',
278+
init: async () => {},
279+
start: async (ctx) => { read.push(ctx.getKernel().dispatchesBootPhaseHooks()); },
280+
};
281+
282+
kernel.use(plugin);
283+
await kernel.bootstrap();
284+
await kernel.shutdown();
285+
286+
expect(read).toEqual([true]);
287+
expect(kernel.dispatchesBootPhaseHooks()).toBe(true);
288+
});
289+
274290
// #5170 — the LiteKernel half of the cross-kernel pin. This is the
275291
// behaviour the issue changed: the throw used to be caught inside
276292
// `triggerHook`, logged as `Hook handler failed: kernel:ready`, and the

‎packages/services/service-automation/src/connector-materialization.test.ts‎

Lines changed: 145 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'nod
1313
import { tmpdir } from 'node:os';
1414
import * as path from 'node:path';
1515
import { describe, it, expect, afterAll, afterEach, vi } from 'vitest';
16-
import { LiteKernel } from '@objectstack/core';
16+
import { LiteKernel, ObjectKernel } from '@objectstack/core';
1717
import type {
1818
Connector,
1919
ConnectorProviderContext,
@@ -1217,6 +1217,150 @@ describe('#28698 — a stored entry\'s configuration fault never fails the boot;
12171217
});
12181218
});
12191219

1220+
// ── #28713 — a stored entry waits until every plugin has started ────────────
1221+
//
1222+
// A connector plugin registers its connector in its own start(), after the
1223+
// automation plugin's (it depends on it). A stored entry under that name used
1224+
// to be materialized by the automation plugin's start() reconcile first, so the
1225+
// plugin's registration was refused and its start() failed the boot. Stored
1226+
// entries now wait for the `kernel:bootstrapped` pass, where they meet the
1227+
// plugin's connector the way a running platform does: the §4 conflict logged,
1228+
// the stored entry skipped, the plugin's connector served.
1229+
1230+
describe('#28713 — a stored entry under a connector plugin\'s name never stops the boot; the plugin\'s connector serves', () => {
1231+
const HOST = 'com.acme.host';
1232+
const packages = { [HOST]: { source: 'code' } };
1233+
const ownedBy = <T extends object>(item: T, packageId: string) => ({ ...item, _packageId: packageId });
1234+
const hostServed = ownedBy(providerConnector('host_served'), HOST);
1235+
1236+
interface Observed {
1237+
/** What the registry holds when the connector plugin's start() begins (after the automation plugin's). */
1238+
atPluginStart?: string[];
1239+
/** What it holds when `kernel:listening` is dispatched. */
1240+
atListening?: string[];
1241+
logged: Array<{ msg: string; meta?: unknown }>;
1242+
}
1243+
1244+
/**
1245+
* Boot `kernel` with the automation plugin and one harness standing for the
1246+
* registry and a connector plugin: it serves `declared` (`registered` are the
1247+
* host's, the rest stored) and registers `pluginConnectors` in its own
1248+
* start(), the way ConnectorSlackPlugin does.
1249+
*/
1250+
async function bootWith(
1251+
kernel: { use(p: unknown): unknown; bootstrap(): Promise<void> },
1252+
declared: unknown[],
1253+
opts: { registered: unknown[]; pluginConnectors?: string[] },
1254+
): Promise<Observed> {
1255+
const observed: Observed = { logged: [] };
1256+
const { factory } = makeFakeProvider();
1257+
await kernel.use(new AutomationServicePlugin());
1258+
await kernel.use({
1259+
name: 'test.connector-plugin',
1260+
type: 'standard' as const,
1261+
version: '1.0.0',
1262+
dependencies: ['com.objectstack.service-automation'],
1263+
async init(ctx: any) {
1264+
ctx.registerService('objectql', {
1265+
registry: {
1266+
listItems: (type: string) => (type === 'connector' ? declared : []),
1267+
getPackage: (id: string) => (packages as Record<string, { source: string }>)[id],
1268+
getArtifactItem: artifactReader(opts.registered),
1269+
},
1270+
residualOwnerSource: () => undefined,
1271+
});
1272+
const original = ctx.logger.error.bind(ctx.logger);
1273+
ctx.logger.error = (msg: string, err?: unknown, meta?: unknown) => {
1274+
observed.logged.push({ msg, meta });
1275+
return original(msg, err, meta);
1276+
};
1277+
ctx.getService('automation').registerConnectorProvider('fake', factory);
1278+
ctx.hook('kernel:listening', async () => {
1279+
observed.atListening = ctx.getService('automation').getRegisteredConnectors();
1280+
});
1281+
},
1282+
async start(ctx: any) {
1283+
const automation = ctx.getService('automation');
1284+
observed.atPluginStart = automation.getRegisteredConnectors();
1285+
for (const name of opts.pluginConnectors ?? []) {
1286+
automation.registerConnector(
1287+
{ name, label: name, type: 'api', authentication: { type: 'none' }, actions: [{ key: 'plugin_action', label: 'A' }] },
1288+
{ plugin_action: async () => ({ ok: true }) },
1289+
);
1290+
}
1291+
},
1292+
});
1293+
await kernel.bootstrap();
1294+
await flush();
1295+
return observed;
1296+
}
1297+
1298+
it('a stored entry under a name a plugin registers in its start(): the boot starts, the plugin\'s connector serves, the stored entry is skipped with its record', async () => {
1299+
const kernel = new LiteKernel({ logger: { level: 'silent' } } as never);
1300+
const observed = await bootWith(kernel, [{ ...hostServed }, providerConnector('slack')], {
1301+
registered: [hostServed],
1302+
pluginConnectors: ['slack'],
1303+
});
1304+
const engine = automationOf(kernel);
1305+
expect(engine.getConnectorOrigin('slack')).toBe('plugin');
1306+
expect(engine.resolveConnectorAction('slack', 'plugin_action')).toBeDefined();
1307+
expect(engine.resolveConnectorAction('slack', 'ping')).toBeUndefined();
1308+
expect(engine.getConnectorOrigin('host_served')).toBe('declarative');
1309+
const record = observed.logged.find((l) => l.msg.includes(`declarative provider-bound instance 'slack' collides with a plugin-registered connector`));
1310+
expect(record, JSON.stringify(observed.logged.map((l) => l.msg))).toBeDefined();
1311+
await kernel.shutdown();
1312+
});
1313+
1314+
it('control: a stored entry under a free name serves, materialized after every plugin has started and before kernel:listening', async () => {
1315+
const kernel = new LiteKernel({ logger: { level: 'silent' } } as never);
1316+
const observed = await bootWith(kernel, [{ ...hostServed }, providerConnector('stored_free')], {
1317+
registered: [hostServed],
1318+
});
1319+
// The host's entry is served from the automation plugin's start(); the
1320+
// stored one is not there yet when a later plugin starts…
1321+
expect(observed.atPluginStart).toEqual(['host_served']);
1322+
// …and is served before the server listens.
1323+
expect(observed.atListening).toEqual(expect.arrayContaining(['host_served', 'stored_free']));
1324+
expect(automationOf(kernel).getConnectorOrigin('stored_free')).toBe('declarative');
1325+
expect(observed.logged).toEqual([]);
1326+
await kernel.shutdown();
1327+
});
1328+
1329+
it('control: the host\'s own entry under a name a plugin registers in its start() still fails the boot', async () => {
1330+
const kernel = new LiteKernel({ logger: { level: 'silent' } } as never);
1331+
const hostSlack = ownedBy(providerConnector('slack'), HOST);
1332+
const err = await rejectionOf(bootWith(kernel, [{ ...hostSlack }], {
1333+
registered: [hostSlack],
1334+
pluginConnectors: ['slack'],
1335+
}));
1336+
expect(err.message).toContain(`Connector name conflict: 'slack' is already registered by a declarative provider-bound`);
1337+
});
1338+
1339+
it('a kernel that withholds its boot-phase hooks keeps stored entries in the start() reconcile, so they are served', async () => {
1340+
const kernel = new ObjectKernel({ logger: { level: 'error' }, gracefulShutdown: false, skipSystemValidation: true, bootPhaseHooks: false });
1341+
const observed = await bootWith(kernel, [{ ...hostServed }, providerConnector('stored_free')], {
1342+
registered: [hostServed],
1343+
});
1344+
expect(observed.atPluginStart).toEqual(expect.arrayContaining(['host_served', 'stored_free']));
1345+
expect((kernel.getService('automation') as AutomationEngine).getConnectorOrigin('stored_free')).toBe('declarative');
1346+
await kernel.shutdown();
1347+
});
1348+
1349+
it.each([
1350+
['has no reader', (k: LiteKernel) => { (k as unknown as { dispatchesBootPhaseHooks?: unknown }).dispatchesBootPhaseHooks = undefined; }],
1351+
['answers false', (k: LiteKernel) => { (k as unknown as { dispatchesBootPhaseHooks: () => boolean }).dispatchesBootPhaseHooks = () => false; }],
1352+
] as const)('a host whose kernel %s keeps stored entries in the start() reconcile, so they are served', async (_label, shape) => {
1353+
const kernel = new LiteKernel({ logger: { level: 'silent' } } as never);
1354+
shape(kernel);
1355+
const observed = await bootWith(kernel, [{ ...hostServed }, providerConnector('stored_free')], {
1356+
registered: [hostServed],
1357+
});
1358+
expect(observed.atPluginStart).toEqual(expect.arrayContaining(['host_served', 'stored_free']));
1359+
expect(automationOf(kernel).getConnectorOrigin('stored_free')).toBe('declarative');
1360+
await kernel.shutdown();
1361+
});
1362+
});
1363+
12201364
// ── #3017 — upstream unavailable: degrade + retry, never a dead boot ─────────
12211365
//
12221366
// A provider factory that throws the CONNECTOR_UPSTREAM_UNAVAILABLE marker

0 commit comments

Comments
 (0)