-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathkernel.ts
More file actions
683 lines (584 loc) · 25.7 KB
/
Copy pathkernel.ts
File metadata and controls
683 lines (584 loc) · 25.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Plugin, PluginContext } from './types.js';
import { createLogger, ObjectLogger } from './logger.js';
import type { LoggerConfig } from '@objectstack/spec/system';
import { ServiceRequirementDef } from '@objectstack/spec/system';
import { PluginLoader, PluginMetadata, ServiceLifecycle, ServiceFactory, PluginStartupResult } from './plugin-loader.js';
import { isNode, safeExit } from './utils/env.js';
import { CORE_FALLBACK_FACTORIES } from './fallbacks/index.js';
/**
* Enhanced Kernel Configuration
*/
export interface ObjectKernelConfig {
logger?: Partial<LoggerConfig>;
/** Default plugin startup timeout in milliseconds */
defaultStartupTimeout?: number;
/** Whether to enable graceful shutdown */
gracefulShutdown?: boolean;
/** Graceful shutdown timeout in milliseconds */
shutdownTimeout?: number;
/** Whether to rollback on startup failure */
rollbackOnFailure?: boolean;
/** Whether to skip strict system requirement validation (Critical for testing) */
skipSystemValidation?: boolean;
}
/**
* Enhanced ObjectKernel with Advanced Plugin Management
*
* Extends the basic ObjectKernel with:
* - Async plugin loading with validation
* - Version compatibility checking
* - Plugin signature verification
* - Configuration validation (Zod)
* - Factory-based dependency injection
* - Service lifecycle management (singleton/transient/scoped)
* - Circular dependency detection
* - Lazy loading services
* - Graceful shutdown
* - Plugin startup timeout control
* - Startup failure rollback
* - Plugin health checks
*/
export class ObjectKernel {
private plugins: Map<string, PluginMetadata> = new Map();
private services: Map<string, any> = new Map();
private hooks: Map<string, Array<(...args: any[]) => void | Promise<void>>> = new Map();
private state: 'idle' | 'initializing' | 'running' | 'stopping' | 'stopped' = 'idle';
private logger: ObjectLogger;
private context: PluginContext;
private pluginLoader: PluginLoader;
private config: ObjectKernelConfig;
private startedPlugins: Set<string> = new Set();
private pluginStartTimes: Map<string, number> = new Map();
private shutdownHandlers: Array<() => Promise<void>> = [];
constructor(config: ObjectKernelConfig = {}) {
this.config = {
defaultStartupTimeout: 30000, // 30 seconds
gracefulShutdown: true,
shutdownTimeout: 60000, // 60 seconds
rollbackOnFailure: true,
...config,
};
this.logger = createLogger(config.logger);
this.pluginLoader = new PluginLoader(this.logger);
// Initialize context
this.context = {
registerService: (name, service) => {
this.registerService(name, service);
},
registerServiceFactory: (name, factory, lifecycle, dependencies) => {
this.registerServiceFactory(name, factory, lifecycle, dependencies);
},
getService: <T>(name: string) => {
// 1. Try direct service map first (synchronous cache)
const service = this.services.get(name);
if (service) {
return service as T;
}
// 2. Try to get from plugin loader cache (Sync access to factories)
const loaderService = this.pluginLoader.getServiceInstance<T>(name);
if (loaderService) {
// Cache it locally for faster next access
this.services.set(name, loaderService);
return loaderService;
}
// 3. Try to get from plugin loader (support async factories)
try {
const service = this.pluginLoader.getService(name);
if (service instanceof Promise) {
// If we found it in the loader but not in the sync map, it's likely a factory-based service or still loading
// We must silence any potential rejection from this promise since we are about to throw our own error
// and abandon the promise. Without this, Node.js will crash with "Unhandled Promise Rejection".
service.catch(() => {});
throw new Error(`Service '${name}' is async - use await`);
}
return service as T;
} catch (error: any) {
if (error.message?.includes('is async')) {
throw error;
}
// Re-throw critical factory errors instead of masking them as "not found"
// If the error came from the factory execution (e.g. database connection failed), we must see it.
// "Service '${name}' not found" comes from PluginLoader.getService fallback.
const isNotFoundError = error.message === `Service '${name}' not found`;
if (!isNotFoundError) {
throw error;
}
throw new Error(`[Kernel] Service '${name}' not found`);
}
},
replaceService: <T>(name: string, implementation: T): void => {
const hasService = this.services.has(name) || this.pluginLoader.hasService(name);
if (!hasService) {
throw new Error(`[Kernel] Service '${name}' not found. Use registerService() to add new services.`);
}
this.services.set(name, implementation);
this.pluginLoader.replaceService(name, implementation);
this.logger.info(`Service '${name}' replaced`, { service: name });
},
hook: (name, handler) => {
if (!this.hooks.has(name)) {
this.hooks.set(name, []);
}
this.hooks.get(name)!.push(handler);
},
trigger: async (name, ...args) => {
const handlers = this.hooks.get(name) || [];
for (const handler of handlers) {
await handler(...args);
}
},
getServices: () => {
return new Map(this.services);
},
getServiceScoped: <T>(name: string, scopeId: string): Promise<T> => {
return this.pluginLoader.getService<T>(name, scopeId);
},
logger: this.logger,
getKernel: () => this as any, // Type compatibility
};
this.pluginLoader.setContext(this.context);
// Register shutdown handler
if (this.config.gracefulShutdown) {
this.registerShutdownSignals();
}
}
/**
* Register a plugin with enhanced validation
*/
async use(plugin: Plugin): Promise<this> {
if (this.state !== 'idle') {
throw new Error('[Kernel] Cannot register plugins after bootstrap has started');
}
// Load plugin through enhanced loader
const result = await this.pluginLoader.loadPlugin(plugin);
if (!result.success || !result.plugin) {
throw new Error(`Failed to load plugin: ${plugin.name} - ${result.error?.message}`);
}
const pluginMeta = result.plugin;
this.plugins.set(pluginMeta.name, pluginMeta);
this.logger.info(`Plugin registered: ${pluginMeta.name}@${pluginMeta.version}`, {
plugin: pluginMeta.name,
version: pluginMeta.version,
});
return this;
}
/**
* Register a service instance directly
*/
registerService<T>(name: string, service: T): this {
if (this.services.has(name)) {
throw new Error(`[Kernel] Service '${name}' already registered`);
}
this.services.set(name, service);
this.pluginLoader.registerService(name, service);
this.logger.info(`Service '${name}' registered`, { service: name });
return this;
}
/**
* Register a service factory with lifecycle management
*/
registerServiceFactory<T>(
name: string,
factory: ServiceFactory<T>,
lifecycle: ServiceLifecycle = ServiceLifecycle.SINGLETON,
dependencies?: string[]
): this {
this.pluginLoader.registerServiceFactory({
name,
factory,
lifecycle,
dependencies,
});
return this;
}
/**
* Pre-inject in-memory fallbacks for 'core' services that were not registered
* by plugins during Phase 1. Called before Phase 2 so that all core services
* (e.g. 'metadata', 'cache', 'queue') are resolvable via ctx.getService()
* when plugin start() methods execute.
*/
private preInjectCoreFallbacks() {
if (this.config.skipSystemValidation) return;
for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) {
if (criticality !== 'core') continue;
const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName);
if (!hasService) {
const factory = CORE_FALLBACK_FACTORIES[serviceName];
if (factory) {
const fallback = factory();
this.registerService(serviceName, fallback);
this.logger.debug(`[Kernel] Pre-injected in-memory fallback for '${serviceName}' before Phase 2`);
}
}
}
}
/**
* Validate Critical System Requirements
*/
private validateSystemRequirements() {
if (this.config.skipSystemValidation) {
this.logger.debug('System requirement validation skipped');
return;
}
this.logger.debug('Validating system service requirements...');
const missingServices: string[] = [];
const missingCoreServices: string[] = [];
// Iterate through all defined requirements
for (const [serviceName, criticality] of Object.entries(ServiceRequirementDef)) {
const hasService = this.services.has(serviceName) || this.pluginLoader.hasService(serviceName);
if (!hasService) {
if (criticality === 'required') {
this.logger.error(`CRITICAL: Required service missing: ${serviceName}`);
missingServices.push(serviceName);
} else if (criticality === 'core') {
// Auto-inject in-memory fallback if available
const factory = CORE_FALLBACK_FACTORIES[serviceName];
if (factory) {
const fallback = factory();
this.registerService(serviceName, fallback);
this.logger.warn(`Service '${serviceName}' not provided — using in-memory fallback`);
} else {
this.logger.warn(`CORE: Core service missing, functionality may be degraded: ${serviceName}`);
missingCoreServices.push(serviceName);
}
} else {
this.logger.info(`Info: Optional service not present: ${serviceName}`);
}
}
}
if (missingServices.length > 0) {
const errorMsg = `System failed to start. Missing critical services: ${missingServices.join(', ')}`;
this.logger.error(errorMsg);
throw new Error(errorMsg);
}
if (missingCoreServices.length > 0) {
this.logger.warn(`System started with degraded capabilities. Missing core services: ${missingCoreServices.join(', ')}`);
}
this.logger.info('System requirement check passed');
}
/**
* Bootstrap the kernel with enhanced features
*/
async bootstrap(): Promise<void> {
if (this.state !== 'idle') {
throw new Error('[Kernel] Kernel already bootstrapped');
}
this.state = 'initializing';
this.logger.info('Bootstrap started');
try {
// Check for circular dependencies
const cycles = this.pluginLoader.detectCircularDependencies();
if (cycles.length > 0) {
this.logger.warn('Circular service dependencies detected:', { cycles });
}
// Resolve plugin dependencies
const orderedPlugins = this.resolveDependencies();
// Phase 1: Init - Plugins register services
this.logger.info('Phase 1: Init plugins');
for (const plugin of orderedPlugins) {
await this.initPluginWithTimeout(plugin);
}
// Pre-inject in-memory fallbacks for 'core' services that were not
// registered by any plugin during Phase 1. This ensures services like
// 'metadata', 'cache', 'queue', etc. are always available when plugins
// call ctx.getService() during their start() methods.
this.preInjectCoreFallbacks();
// Phase 2: Start - Plugins execute business logic
this.logger.info('Phase 2: Start plugins');
this.state = 'running';
for (const plugin of orderedPlugins) {
const result = await this.startPluginWithTimeout(plugin);
if (!result.success) {
this.logger.error(`Plugin startup failed: ${plugin.name}`, result.error);
const origMsg = result.error instanceof Error ? result.error.message : String(result.error);
const origStack = result.error instanceof Error ? result.error.stack : '';
console.error(`[Kernel] Plugin startup failed: ${plugin.name}`, origMsg, origStack);
if (this.config.rollbackOnFailure) {
this.logger.warn('Rolling back started plugins...');
await this.rollbackStartedPlugins();
// Propagate the original cause through the thrown error
// so callers (e.g. cloud auth-proxy) can surface the
// real failure instead of an opaque "rollback complete"
// string. Without this, every kernel-boot failure looks
// identical from the outside.
const err: any = new Error(
`Plugin ${plugin.name} failed to start - rollback complete: ${origMsg}`,
);
if (result.error instanceof Error) {
err.cause = result.error;
err.originalStack = origStack;
}
throw err;
}
}
}
// Phase 3: Trigger kernel:ready hook
this.validateSystemRequirements(); // Final check before ready
this.logger.debug('Triggering kernel:ready hook');
await this.context.trigger('kernel:ready');
// Phase 3.5: Trigger kernel:bootstrapped AFTER every kernel:ready
// handler has settled — the "all synchronous bootstrap has settled"
// anchor. Reconcile/backfill work that consumes data produced by a
// later-starting plugin's kernel:ready handler belongs here, not in
// kernel:ready (where handler order would race the data). NOTE: this
// does NOT guarantee background app seed data has settled (an inline
// seed that overruns OS_INLINE_SEED_BUDGET_MS finishes later) —
// subscribe `app:seeded` for that. See
// packages/spec/src/contracts/plugin-lifecycle-events.ts.
this.logger.debug('Triggering kernel:bootstrapped hook');
await this.context.trigger('kernel:bootstrapped');
// Phase 4: Trigger kernel:listening hook AFTER all kernel:ready
// handlers have completed. This is the cue for HTTP server
// plugins to actually open the listening socket — by now every
// other plugin has finished registering routes/middleware.
// See `kernel:listening` docs in
// packages/spec/src/contracts/plugin-lifecycle-events.ts
// for the race-condition rationale.
this.logger.debug('Triggering kernel:listening hook');
await this.context.trigger('kernel:listening');
this.logger.info('✅ Bootstrap complete');
} catch (error) {
this.state = 'stopped';
throw error;
}
}
/**
* Graceful shutdown with timeout
*/
async shutdown(): Promise<void> {
if (this.state === 'stopped' || this.state === 'stopping') {
this.logger.warn('Kernel already stopped or stopping');
return;
}
if (this.state !== 'running') {
throw new Error('[Kernel] Kernel not running');
}
this.state = 'stopping';
this.logger.info('Graceful shutdown started');
try {
const shutdownPromise = this.performShutdown();
const timeoutPromise = new Promise<void>((_, reject) => {
const t = setTimeout(() => {
reject(new Error('Shutdown timeout exceeded'));
}, this.config.shutdownTimeout);
// Don't let this timer keep the event loop alive
if (t.unref) t.unref();
});
await Promise.race([shutdownPromise, timeoutPromise]);
this.state = 'stopped';
this.logger.info('✅ Graceful shutdown complete');
} catch (error) {
this.logger.error('Shutdown timed out — forcing exit', error as Error);
this.state = 'stopped';
// Flush logger then hard-exit; the process would otherwise hang
await this.logger.destroy();
process.exit(1);
} finally {
await this.logger.destroy();
}
}
/**
* Check health of a specific plugin
*/
async checkPluginHealth(pluginName: string): Promise<any> {
return await this.pluginLoader.checkPluginHealth(pluginName);
}
/**
* Check health of all plugins
*/
async checkAllPluginsHealth(): Promise<Map<string, any>> {
const results = new Map();
for (const pluginName of this.plugins.keys()) {
const health = await this.checkPluginHealth(pluginName);
results.set(pluginName, health);
}
return results;
}
/**
* Get plugin startup metrics
*/
getPluginMetrics(): Map<string, number> {
return new Map(this.pluginStartTimes);
}
/**
* Get a service (sync helper)
*/
getService<T>(name: string): T {
return this.context.getService<T>(name);
}
/**
* Get a service asynchronously (supports factories)
*/
async getServiceAsync<T>(name: string, scopeId?: string): Promise<T> {
return await this.pluginLoader.getService<T>(name, scopeId);
}
/**
* Clear all scoped service instances for a given scope (e.g., environmentId).
* Releases driver connections and metadata caches for idle projects.
*/
clearScope(scopeId: string): void {
this.pluginLoader.clearScope(scopeId);
}
/**
* Check if kernel is running
*/
isRunning(): boolean {
return this.state === 'running';
}
/**
* Get kernel state
*/
getState(): string {
return this.state;
}
// Private methods
private async initPluginWithTimeout(plugin: PluginMetadata): Promise<void> {
const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout!;
this.logger.debug(`Init: ${plugin.name}`, { plugin: plugin.name });
const initPromise = plugin.init(this.context);
const timeoutPromise = new Promise<void>((_, reject) => {
setTimeout(() => {
reject(new Error(`Plugin ${plugin.name} init timeout after ${timeout}ms`));
}, timeout);
});
await Promise.race([initPromise, timeoutPromise]);
}
private async startPluginWithTimeout(plugin: PluginMetadata): Promise<PluginStartupResult> {
if (!plugin.start) {
return { success: true, pluginName: plugin.name };
}
const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout!;
const startTime = Date.now();
this.logger.debug(`Start: ${plugin.name}`, { plugin: plugin.name });
try {
const startPromise = plugin.start(this.context);
const timeoutPromise = new Promise<void>((_, reject) => {
setTimeout(() => {
reject(new Error(`Plugin ${plugin.name} start timeout after ${timeout}ms`));
}, timeout);
});
await Promise.race([startPromise, timeoutPromise]);
const duration = Date.now() - startTime;
this.startedPlugins.add(plugin.name);
this.pluginStartTimes.set(plugin.name, duration);
this.logger.debug(`Plugin started: ${plugin.name} (${duration}ms)`);
return {
success: true,
pluginName: plugin.name,
startTime: duration,
};
} catch (error) {
const duration = Date.now() - startTime;
const isTimeout = (error as Error).message.includes('timeout');
return {
success: false,
pluginName: plugin.name,
error: error as Error,
startTime: duration,
timedOut: isTimeout,
};
}
}
private async rollbackStartedPlugins(): Promise<void> {
const pluginsToRollback = Array.from(this.startedPlugins).reverse();
for (const pluginName of pluginsToRollback) {
const plugin = this.plugins.get(pluginName);
if (plugin?.destroy) {
try {
this.logger.debug(`Rollback: ${pluginName}`);
await plugin.destroy();
} catch (error) {
this.logger.error(`Rollback failed for ${pluginName}`, error as Error);
}
}
}
this.startedPlugins.clear();
}
private async performShutdown(): Promise<void> {
// Trigger shutdown hook
await this.context.trigger('kernel:shutdown');
// Destroy plugins in reverse order
const orderedPlugins = Array.from(this.plugins.values()).reverse();
for (const plugin of orderedPlugins) {
if (plugin.destroy) {
this.logger.debug(`Destroy: ${plugin.name}`, { plugin: plugin.name });
try {
await plugin.destroy();
} catch (error) {
this.logger.error(`Error destroying plugin ${plugin.name}`, error as Error);
}
}
}
// Execute custom shutdown handlers
for (const handler of this.shutdownHandlers) {
try {
await handler();
} catch (error) {
this.logger.error('Shutdown handler error', error as Error);
}
}
}
private resolveDependencies(): PluginMetadata[] {
const resolved: PluginMetadata[] = [];
const visited = new Set<string>();
const visiting = new Set<string>();
const visit = (pluginName: string) => {
if (visited.has(pluginName)) return;
if (visiting.has(pluginName)) {
throw new Error(`[Kernel] Circular dependency detected: ${pluginName}`);
}
const plugin = this.plugins.get(pluginName);
if (!plugin) {
throw new Error(`[Kernel] Plugin '${pluginName}' not found`);
}
visiting.add(pluginName);
// Visit dependencies first
const deps = plugin.dependencies || [];
for (const dep of deps) {
if (!this.plugins.has(dep)) {
throw new Error(`[Kernel] Dependency '${dep}' not found for plugin '${pluginName}'`);
}
visit(dep);
}
visiting.delete(pluginName);
visited.add(pluginName);
resolved.push(plugin);
};
// Visit all plugins
for (const pluginName of this.plugins.keys()) {
visit(pluginName);
}
return resolved;
}
private registerShutdownSignals(): void {
const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGQUIT'];
let shutdownInProgress = false;
const handleShutdown = async (signal: string) => {
if (shutdownInProgress) {
this.logger.warn(`Shutdown already in progress, ignoring ${signal}`);
return;
}
shutdownInProgress = true;
this.logger.info(`Received ${signal} - initiating graceful shutdown`);
try {
await this.shutdown();
safeExit(0);
} catch (error) {
this.logger.error('Shutdown failed', error as Error);
safeExit(1);
}
};
if (isNode) {
for (const signal of signals) {
process.on(signal, () => handleShutdown(signal));
}
}
}
/**
* Register a custom shutdown handler
*/
onShutdown(handler: () => Promise<void>): void {
this.shutdownHandlers.push(handler);
}
}