Skip to content

Commit ad22faf

Browse files
authored
refactor(gateway): register resident lifecycles (#121996)
1 parent e082acd commit ad22faf

7 files changed

Lines changed: 564 additions & 302 deletions

‎src/gateway/server-core-runtime.ts‎

Lines changed: 57 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,6 @@ export async function startGatewayCoreRuntime(input: {
114114
runtimeState,
115115
kernel,
116116
startupTrace,
117-
activeTaskCount,
118117
channelManager,
119118
workerDispatchAuthority,
120119
clients,
@@ -141,9 +140,13 @@ export async function startGatewayCoreRuntime(input: {
141140
workerEnvironmentStartup,
142141
broadcastPluginEvent,
143142
activateRuntimeSecrets,
143+
residentRegistry,
144144
} = runtime;
145-
const earlyRuntime = await startupTrace.measure("runtime.early", () =>
146-
loadGatewayStartupEarlyModule().then(({ startGatewayEarlyRuntime }) =>
145+
let earlyRuntimePromise: ReturnType<
146+
Awaited<ReturnType<typeof loadGatewayStartupEarlyModule>>["startGatewayEarlyRuntime"]
147+
> | null = null;
148+
const startEarlyRuntime = () => {
149+
earlyRuntimePromise ??= loadGatewayStartupEarlyModule().then(({ startGatewayEarlyRuntime }) =>
147150
startGatewayEarlyRuntime({
148151
minimalTestGateway,
149152
cfgAtStart,
@@ -180,11 +183,31 @@ export async function startGatewayCoreRuntime(input: {
180183
getRuntimeConfig,
181184
startupTrace,
182185
}),
183-
),
186+
);
187+
return earlyRuntimePromise;
188+
};
189+
const discoveryResident = residentRegistry.register({
190+
name: "bonjour-discovery",
191+
start: startEarlyRuntime,
192+
stop: async () => {
193+
const earlyRuntime = await startEarlyRuntime();
194+
await earlyRuntime.bonjourStop?.();
195+
},
196+
});
197+
const taskAndSkillsResident = residentRegistry.register({
198+
name: "task-and-skills-runtime",
199+
start: async () => await discoveryResident.start(),
200+
stop: async () => {
201+
const earlyRuntime = await startEarlyRuntime();
202+
earlyRuntime.skillsChangeUnsub();
203+
const { stopTaskRegistryMaintenance } = await import("../tasks/task-registry.maintenance.js");
204+
stopTaskRegistryMaintenance();
205+
},
206+
});
207+
const earlyRuntime = await startupTrace.measure("runtime.early", () =>
208+
taskAndSkillsResident.start(),
184209
);
185-
runtimeState.bonjourStop = earlyRuntime.bonjourStop;
186-
activeTaskCount.get = earlyRuntime.getActiveTaskCount;
187-
runtimeState.skillsChangeUnsub = earlyRuntime.skillsChangeUnsub;
210+
kernel.setEarlyRuntimeHandles(earlyRuntime);
188211

189212
const [{ startGatewayEventSubscriptions }, { startGatewayRuntimeServices }] =
190213
await startupTrace.measure("runtime.post-early-imports", () =>
@@ -193,8 +216,9 @@ export async function startGatewayCoreRuntime(input: {
193216
import("./server-runtime-startup-services.js"),
194217
]),
195218
);
196-
const { sessionCompanion, sessionObserver, ...runtimeSubscriptionUnsubs } =
197-
await startupTrace.measure("runtime.subscriptions", () =>
219+
const eventSubscriptionsResident = residentRegistry.register({
220+
name: "event-subscriptions",
221+
start: () =>
198222
startGatewayEventSubscriptions({
199223
log,
200224
broadcast,
@@ -209,7 +233,16 @@ export async function startGatewayCoreRuntime(input: {
209233
restartRecoveryCandidates,
210234
terminalSessions,
211235
}),
212-
);
236+
stop: async () => {
237+
await runtimeState.agentUnsub?.();
238+
runtimeState.heartbeatUnsub?.();
239+
runtimeState.transcriptUnsub?.();
240+
runtimeState.lifecycleUnsub?.();
241+
runtimeState.taskUnsub?.();
242+
},
243+
});
244+
const { sessionCompanion, sessionObserver, ...runtimeSubscriptionUnsubs } =
245+
await startupTrace.measure("runtime.subscriptions", () => eventSubscriptionsResident.start());
213246
Object.assign(runtimeState, runtimeSubscriptionUnsubs);
214247

215248
const runtimeServices = await startupTrace.measure("runtime.services", () =>
@@ -289,7 +322,7 @@ export async function startGatewayCoreRuntime(input: {
289322
coreGatewayHandlers: coreGatewayHandlersLocal,
290323
};
291324
});
292-
runtimeState.gatewayLifetimeSidecars.push({
325+
kernel.addGatewayLifetimeSidecar({
293326
stop: async () => {
294327
unregisterApprovalAuthorityObserver();
295328
},
@@ -385,8 +418,7 @@ export async function startGatewayCoreRuntime(input: {
385418
return;
386419
}
387420
try {
388-
const stopPreviousDiscovery = runtimeState.bonjourStop;
389-
runtimeState.bonjourStop = null;
421+
const stopPreviousDiscovery = kernel.swapBonjourStop(null);
390422
if (stopPreviousDiscovery) {
391423
try {
392424
await stopPreviousDiscovery();
@@ -395,16 +427,18 @@ export async function startGatewayCoreRuntime(input: {
395427
}
396428
}
397429
const { startGatewayPluginDiscovery } = await loadGatewayStartupEarlyModule();
398-
runtimeState.bonjourStop = await startGatewayPluginDiscovery({
399-
minimalTestGateway,
400-
cfgAtStart,
401-
port,
402-
gatewayTls,
403-
gatewayDirectReachable: !isLoopbackHost(bindHost),
404-
tailscaleMode,
405-
logDiscovery,
406-
pluginRegistry: nextPluginRegistry,
407-
});
430+
kernel.swapBonjourStop(
431+
await startGatewayPluginDiscovery({
432+
minimalTestGateway,
433+
cfgAtStart,
434+
port,
435+
gatewayTls,
436+
gatewayDirectReachable: !isLoopbackHost(bindHost),
437+
tailscaleMode,
438+
logDiscovery,
439+
pluginRegistry: nextPluginRegistry,
440+
}),
441+
);
408442
} catch (err) {
409443
logDiscovery.warn(`gateway discovery refresh failed after plugin load: ${String(err)}`);
410444
}

‎src/gateway/server-lifecycle.ts‎

Lines changed: 90 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ export async function prepareGatewayLifecycle(params: {
9898
sessionEventSubscribers,
9999
watchNodeRequestHandler,
100100
defaultWorkspaceDir,
101+
activeTaskCount,
102+
residentRegistry,
101103
} = runtime;
102104
const completeControlUiDeviceAuthMigrationForEffectiveOperator = (
103105
device: EffectiveOperatorDeviceIdentity,
@@ -264,6 +266,66 @@ export async function prepareGatewayLifecycle(params: {
264266
publishMethodSurface: (methods: readonly string[]) => {
265267
runtimeState.gatewayMethods.splice(0, runtimeState.gatewayMethods.length, ...methods);
266268
},
269+
setEarlyRuntimeHandles: (handles: {
270+
bonjourStop: typeof runtimeState.bonjourStop;
271+
getActiveTaskCount: () => number;
272+
skillsChangeUnsub: typeof runtimeState.skillsChangeUnsub;
273+
}) => {
274+
runtimeState.bonjourStop = handles.bonjourStop;
275+
activeTaskCount.get = handles.getActiveTaskCount;
276+
runtimeState.skillsChangeUnsub = handles.skillsChangeUnsub;
277+
},
278+
swapBonjourStop: (next: typeof runtimeState.bonjourStop) => {
279+
const previous = runtimeState.bonjourStop;
280+
runtimeState.bonjourStop = next;
281+
return previous;
282+
},
283+
setScheduledServiceHandles: (handles: {
284+
heartbeatRunner: typeof runtimeState.heartbeatRunner;
285+
stopOutboundDeliveryRecovery: typeof runtimeState.stopOutboundDeliveryRecovery;
286+
}) => {
287+
runtimeState.heartbeatRunner = handles.heartbeatRunner;
288+
runtimeState.stopOutboundDeliveryRecovery = handles.stopOutboundDeliveryRecovery;
289+
},
290+
setPostAttachHandles: (handles: {
291+
stopGatewayUpdateCheck: typeof runtimeState.stopGatewayUpdateCheck;
292+
tailscaleCleanup: typeof runtimeState.tailscaleCleanup;
293+
pluginServices: typeof runtimeState.pluginServices;
294+
}) => {
295+
runtimeState.stopGatewayUpdateCheck = handles.stopGatewayUpdateCheck;
296+
runtimeState.tailscaleCleanup = handles.tailscaleCleanup;
297+
runtimeState.pluginServices = handles.pluginServices;
298+
},
299+
setPluginServices: (pluginServices: typeof runtimeState.pluginServices) => {
300+
runtimeState.pluginServices = pluginServices;
301+
},
302+
setConfigReloaderHandle: (configReloader: typeof runtimeState.configReloader) => {
303+
runtimeState.configReloader = configReloader;
304+
},
305+
setPostReadySidecars: (sidecars: typeof runtimeState.postReadySidecars) => {
306+
runtimeState.postReadySidecars = sidecars;
307+
},
308+
setGatewayLifetimeSidecars: (sidecars: typeof runtimeState.gatewayLifetimeSidecars) => {
309+
runtimeState.gatewayLifetimeSidecars = sidecars;
310+
},
311+
addGatewayLifetimeSidecar: (sidecar: (typeof runtimeState.gatewayLifetimeSidecars)[number]) => {
312+
runtimeState.gatewayLifetimeSidecars.push(sidecar);
313+
},
314+
setMaintenanceHandles: (handles: {
315+
tickInterval: typeof runtimeState.tickInterval;
316+
healthInterval: typeof runtimeState.healthInterval;
317+
dedupeCleanup: typeof runtimeState.dedupeCleanup;
318+
stopMediaCleanup: typeof runtimeState.stopMediaCleanup;
319+
worktreeCleanup: typeof runtimeState.worktreeCleanup;
320+
skillCuratorCleanup: typeof runtimeState.skillCuratorCleanup;
321+
}) => {
322+
runtimeState.tickInterval = handles.tickInterval;
323+
runtimeState.healthInterval = handles.healthInterval;
324+
runtimeState.dedupeCleanup = handles.dedupeCleanup;
325+
runtimeState.stopMediaCleanup = handles.stopMediaCleanup;
326+
runtimeState.worktreeCleanup = handles.worktreeCleanup;
327+
runtimeState.skillCuratorCleanup = handles.skillCuratorCleanup;
328+
},
267329
};
268330
runtimeState.controlUiSessionPullRequests = createControlUiSessionPullRequestSubscriptions({
269331
broadcastToConnIds,
@@ -500,28 +562,35 @@ export async function prepareGatewayLifecycle(params: {
500562
}
501563
};
502564

565+
const diagnosticHeartbeatResident = residentRegistry.register({
566+
name: "diagnostic-heartbeat",
567+
start: () => {
568+
// Gateway lifecycle owns both this existing heartbeat timer and the monitor
569+
// it samples, so startup failure and normal close tear them down together.
570+
startDiagnosticHeartbeat(undefined, {
571+
getConfig: getRuntimeConfig,
572+
startupGraceMs: 60_000,
573+
sampleLiveness: () => {
574+
const sample = readinessEventLoopHealth.persistentDegradationSnapshot();
575+
if (!sample || sample.degradedSinceMs == null) {
576+
return null;
577+
}
578+
return {
579+
reasons: sample.reasons,
580+
intervalMs: sample.intervalMs,
581+
degradedSinceMs: sample.degradedSinceMs,
582+
eventLoopDelayP99Ms: sample.delayP99Ms,
583+
eventLoopDelayMaxMs: sample.delayMaxMs,
584+
eventLoopUtilization: sample.utilization,
585+
cpuCoreRatio: sample.cpuCoreRatio,
586+
};
587+
},
588+
});
589+
},
590+
stop: () => stopDiagnosticHeartbeat(),
591+
});
503592
if (diagnosticsEnabled) {
504-
// Gateway lifecycle owns both this existing heartbeat timer and the monitor
505-
// it samples, so startup failure and normal close tear them down together.
506-
startDiagnosticHeartbeat(undefined, {
507-
getConfig: getRuntimeConfig,
508-
startupGraceMs: 60_000,
509-
sampleLiveness: () => {
510-
const sample = readinessEventLoopHealth.persistentDegradationSnapshot();
511-
if (!sample || sample.degradedSinceMs == null) {
512-
return null;
513-
}
514-
return {
515-
reasons: sample.reasons,
516-
intervalMs: sample.intervalMs,
517-
degradedSinceMs: sample.degradedSinceMs,
518-
eventLoopDelayP99Ms: sample.delayP99Ms,
519-
eventLoopDelayMaxMs: sample.delayMaxMs,
520-
eventLoopUtilization: sample.utilization,
521-
cpuCoreRatio: sample.cpuCoreRatio,
522-
};
523-
},
524-
});
593+
diagnosticHeartbeatResident.start();
525594
}
526595

527596
return {
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
type GatewayResident<
2+
TStart extends () => unknown = () => unknown,
3+
TStop extends () => unknown = () => unknown,
4+
> = {
5+
name: string;
6+
start: TStart;
7+
stop: TStop;
8+
};
9+
10+
export type GatewayResidentRegistry = {
11+
register: <TStart extends () => unknown, TStop extends () => unknown>(
12+
resident: GatewayResident<TStart, TStop>,
13+
) => GatewayResident<TStart, TStop>;
14+
list: () => readonly GatewayResident[];
15+
};
16+
17+
/** Records resident lifecycle owners without changing when callers start or stop them. */
18+
export function createGatewayResidentRegistry(): GatewayResidentRegistry {
19+
const residents: GatewayResident[] = [];
20+
const names = new Set<string>();
21+
22+
return {
23+
register: <TStart extends () => unknown, TStop extends () => unknown>(
24+
resident: GatewayResident<TStart, TStop>,
25+
) => {
26+
if (names.has(resident.name)) {
27+
throw new Error(`Gateway resident already registered: ${resident.name}`);
28+
}
29+
names.add(resident.name);
30+
residents.push(resident as GatewayResident);
31+
return resident;
32+
},
33+
list: () => residents,
34+
};
35+
}

‎src/gateway/server-runtime-state-prepare.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { createGatewayControlUiRootLifecycle } from "./server-control-ui-root.js
2121
import type { GatewayInstanceRuntime } from "./server-instance-runtime.types.js";
2222
import type { GatewayServerLiveState } from "./server-live-state.js";
2323
import type { GatewayRequestContext } from "./server-methods/types.js";
24+
import { createGatewayResidentRegistry } from "./server-resident-registry.js";
2425
import { createGatewayHttpTransport } from "./server-runtime-state.js";
2526
import type { SharedGatewaySessionGenerationState } from "./server-shared-auth-generation.js";
2627
import type { prepareGatewayServerBootstrap } from "./server-startup-bootstrap.js";
@@ -294,13 +295,25 @@ export async function prepareGatewayKernelState(params: {
294295
const systemAgentSessions: GatewayRequestContext["systemAgentSessions"] = new Map();
295296

296297
const deps = createDefaultDeps();
298+
const residentRegistry = createGatewayResidentRegistry();
297299
const runtimeStateRef: { current: GatewayServerLiveState | null } = { current: null };
298300
const cronStartState = { handled: false };
299301
const gatewayTls = await startupTrace.measure("tls.runtime", () =>
300302
loadGatewayTlsRuntime(cfgAtStart.gateway?.tls, log.child("tls")),
301303
);
302304
const serverStartedAt = Date.now();
303-
const readinessEventLoopHealth = createGatewayEventLoopHealthMonitor();
305+
const eventLoopHealthState: {
306+
current?: ReturnType<typeof createGatewayEventLoopHealthMonitor>;
307+
} = {};
308+
const eventLoopHealthResident = residentRegistry.register({
309+
name: "event-loop-health",
310+
start: () => {
311+
eventLoopHealthState.current ??= createGatewayEventLoopHealthMonitor();
312+
return eventLoopHealthState.current;
313+
},
314+
stop: () => eventLoopHealthState.current?.stop(),
315+
});
316+
const readinessEventLoopHealth = eventLoopHealthResident.start();
304317
const startupState = {
305318
sidecarsReady: minimalTestGateway,
306319
pendingReason: "startup-sidecars",
@@ -468,6 +481,7 @@ export async function prepareGatewayKernelState(params: {
468481
purgeWizardSession,
469482
systemAgentSessions,
470483
deps,
484+
residentRegistry,
471485
runtimeStateRef,
472486
cronStartState,
473487
gatewayTls,

0 commit comments

Comments
 (0)