@objectstack/core 0.9.1 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{ENHANCED_FEATURES.md → ADVANCED_FEATURES.md} +13 -13
- package/CHANGELOG.md +7 -0
- package/PHASE2_IMPLEMENTATION.md +388 -0
- package/README.md +24 -11
- package/REFACTORING_SUMMARY.md +40 -0
- package/dist/api-registry-plugin.test.js +20 -20
- package/dist/dependency-resolver.d.ts +62 -0
- package/dist/dependency-resolver.d.ts.map +1 -0
- package/dist/dependency-resolver.js +317 -0
- package/dist/dependency-resolver.test.d.ts +2 -0
- package/dist/dependency-resolver.test.d.ts.map +1 -0
- package/dist/dependency-resolver.test.js +241 -0
- package/dist/health-monitor.d.ts +65 -0
- package/dist/health-monitor.d.ts.map +1 -0
- package/dist/health-monitor.js +269 -0
- package/dist/health-monitor.test.d.ts +2 -0
- package/dist/health-monitor.test.d.ts.map +1 -0
- package/dist/health-monitor.test.js +68 -0
- package/dist/hot-reload.d.ts +79 -0
- package/dist/hot-reload.d.ts.map +1 -0
- package/dist/hot-reload.js +313 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/kernel-base.d.ts +2 -2
- package/dist/kernel-base.js +2 -2
- package/dist/kernel.d.ts +79 -31
- package/dist/kernel.d.ts.map +1 -1
- package/dist/kernel.js +383 -73
- package/dist/kernel.test.js +373 -122
- package/dist/lite-kernel.d.ts +55 -0
- package/dist/lite-kernel.d.ts.map +1 -0
- package/dist/lite-kernel.js +112 -0
- package/dist/lite-kernel.test.d.ts +2 -0
- package/dist/lite-kernel.test.d.ts.map +1 -0
- package/dist/lite-kernel.test.js +161 -0
- package/dist/logger.d.ts +2 -2
- package/dist/logger.d.ts.map +1 -1
- package/dist/logger.js +26 -7
- package/dist/plugin-loader.d.ts +11 -0
- package/dist/plugin-loader.d.ts.map +1 -1
- package/dist/plugin-loader.js +34 -10
- package/dist/plugin-loader.test.js +9 -0
- package/dist/security/index.d.ts +3 -0
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/index.js +4 -0
- package/dist/security/permission-manager.d.ts +96 -0
- package/dist/security/permission-manager.d.ts.map +1 -0
- package/dist/security/permission-manager.js +235 -0
- package/dist/security/permission-manager.test.d.ts +2 -0
- package/dist/security/permission-manager.test.d.ts.map +1 -0
- package/dist/security/permission-manager.test.js +220 -0
- package/dist/security/sandbox-runtime.d.ts +115 -0
- package/dist/security/sandbox-runtime.d.ts.map +1 -0
- package/dist/security/sandbox-runtime.js +310 -0
- package/dist/security/security-scanner.d.ts +92 -0
- package/dist/security/security-scanner.d.ts.map +1 -0
- package/dist/security/security-scanner.js +273 -0
- package/examples/{enhanced-kernel-example.ts → kernel-features-example.ts} +6 -6
- package/examples/phase2-integration.ts +355 -0
- package/package.json +2 -2
- package/src/api-registry-plugin.test.ts +20 -20
- package/src/dependency-resolver.test.ts +287 -0
- package/src/dependency-resolver.ts +388 -0
- package/src/health-monitor.test.ts +81 -0
- package/src/health-monitor.ts +316 -0
- package/src/hot-reload.ts +388 -0
- package/src/index.ts +6 -1
- package/src/kernel-base.ts +2 -2
- package/src/kernel.test.ts +469 -134
- package/src/kernel.ts +464 -78
- package/src/lite-kernel.test.ts +200 -0
- package/src/lite-kernel.ts +135 -0
- package/src/logger.ts +28 -7
- package/src/plugin-loader.test.ts +10 -1
- package/src/plugin-loader.ts +42 -13
- package/src/security/index.ts +19 -0
- package/src/security/permission-manager.test.ts +256 -0
- package/src/security/permission-manager.ts +336 -0
- package/src/security/sandbox-runtime.ts +432 -0
- package/src/security/security-scanner.ts +365 -0
- package/dist/enhanced-kernel.d.ts +0 -103
- package/dist/enhanced-kernel.d.ts.map +0 -1
- package/dist/enhanced-kernel.js +0 -403
- package/dist/enhanced-kernel.test.d.ts +0 -2
- package/dist/enhanced-kernel.test.d.ts.map +0 -1
- package/dist/enhanced-kernel.test.js +0 -412
- package/src/enhanced-kernel.test.ts +0 -535
- package/src/enhanced-kernel.ts +0 -496
package/src/kernel.ts
CHANGED
|
@@ -1,135 +1,521 @@
|
|
|
1
|
-
import { Plugin } from './types.js';
|
|
1
|
+
import { Plugin, PluginContext } from './types.js';
|
|
2
2
|
import { createLogger, ObjectLogger } from './logger.js';
|
|
3
3
|
import type { LoggerConfig } from '@objectstack/spec/system';
|
|
4
|
-
import {
|
|
4
|
+
import { PluginLoader, PluginMetadata, ServiceLifecycle, ServiceFactory, PluginStartupResult } from './plugin-loader.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
|
-
*
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
7
|
+
* Enhanced Kernel Configuration
|
|
8
|
+
*/
|
|
9
|
+
export interface ObjectKernelConfig {
|
|
10
|
+
logger?: Partial<LoggerConfig>;
|
|
11
|
+
|
|
12
|
+
/** Default plugin startup timeout in milliseconds */
|
|
13
|
+
defaultStartupTimeout?: number;
|
|
14
|
+
|
|
15
|
+
/** Whether to enable graceful shutdown */
|
|
16
|
+
gracefulShutdown?: boolean;
|
|
17
|
+
|
|
18
|
+
/** Graceful shutdown timeout in milliseconds */
|
|
19
|
+
shutdownTimeout?: number;
|
|
20
|
+
|
|
21
|
+
/** Whether to rollback on startup failure */
|
|
22
|
+
rollbackOnFailure?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Enhanced ObjectKernel with Advanced Plugin Management
|
|
15
27
|
*
|
|
16
|
-
*
|
|
17
|
-
* -
|
|
18
|
-
* -
|
|
19
|
-
* -
|
|
28
|
+
* Extends the basic ObjectKernel with:
|
|
29
|
+
* - Async plugin loading with validation
|
|
30
|
+
* - Version compatibility checking
|
|
31
|
+
* - Plugin signature verification
|
|
32
|
+
* - Configuration validation (Zod)
|
|
33
|
+
* - Factory-based dependency injection
|
|
34
|
+
* - Service lifecycle management (singleton/transient/scoped)
|
|
35
|
+
* - Circular dependency detection
|
|
36
|
+
* - Lazy loading services
|
|
37
|
+
* - Graceful shutdown
|
|
38
|
+
* - Plugin startup timeout control
|
|
39
|
+
* - Startup failure rollback
|
|
40
|
+
* - Plugin health checks
|
|
20
41
|
*/
|
|
21
|
-
export class ObjectKernel
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
42
|
+
export class ObjectKernel {
|
|
43
|
+
private plugins: Map<string, PluginMetadata> = new Map();
|
|
44
|
+
private services: Map<string, any> = new Map();
|
|
45
|
+
private hooks: Map<string, Array<(...args: any[]) => void | Promise<void>>> = new Map();
|
|
46
|
+
private state: 'idle' | 'initializing' | 'running' | 'stopping' | 'stopped' = 'idle';
|
|
47
|
+
private logger: ObjectLogger;
|
|
48
|
+
private context: PluginContext;
|
|
49
|
+
private pluginLoader: PluginLoader;
|
|
50
|
+
private config: ObjectKernelConfig;
|
|
51
|
+
private startedPlugins: Set<string> = new Set();
|
|
52
|
+
private pluginStartTimes: Map<string, number> = new Map();
|
|
53
|
+
private shutdownHandlers: Array<() => Promise<void>> = [];
|
|
54
|
+
|
|
55
|
+
constructor(config: ObjectKernelConfig = {}) {
|
|
56
|
+
this.config = {
|
|
57
|
+
defaultStartupTimeout: 30000, // 30 seconds
|
|
58
|
+
gracefulShutdown: true,
|
|
59
|
+
shutdownTimeout: 60000, // 60 seconds
|
|
60
|
+
rollbackOnFailure: true,
|
|
61
|
+
...config,
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
this.logger = createLogger(config.logger);
|
|
65
|
+
this.pluginLoader = new PluginLoader(this.logger);
|
|
25
66
|
|
|
26
|
-
// Initialize context
|
|
27
|
-
this.context =
|
|
67
|
+
// Initialize context
|
|
68
|
+
this.context = {
|
|
69
|
+
registerService: (name, service) => {
|
|
70
|
+
if (this.services.has(name)) {
|
|
71
|
+
throw new Error(`[Kernel] Service '${name}' already registered`);
|
|
72
|
+
}
|
|
73
|
+
this.services.set(name, service);
|
|
74
|
+
this.pluginLoader.registerService(name, service);
|
|
75
|
+
this.logger.info(`Service '${name}' registered`, { service: name });
|
|
76
|
+
},
|
|
77
|
+
getService: <T>(name: string) => {
|
|
78
|
+
// 1. Try direct service map first (synchronous cache)
|
|
79
|
+
const service = this.services.get(name);
|
|
80
|
+
if (service) {
|
|
81
|
+
return service as T;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 2. Try to get from plugin loader cache (Sync access to factories)
|
|
85
|
+
const loaderService = this.pluginLoader.getServiceInstance<T>(name);
|
|
86
|
+
if (loaderService) {
|
|
87
|
+
// Cache it locally for faster next access
|
|
88
|
+
this.services.set(name, loaderService);
|
|
89
|
+
return loaderService;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 3. Try to get from plugin loader (support async factories)
|
|
93
|
+
try {
|
|
94
|
+
const service = this.pluginLoader.getService(name);
|
|
95
|
+
if (service instanceof Promise) {
|
|
96
|
+
// If we found it in the loader but not in the sync map, it's likely a factory-based service or still loading
|
|
97
|
+
throw new Error(`Service '${name}' is async - use await`);
|
|
98
|
+
}
|
|
99
|
+
return service as T;
|
|
100
|
+
} catch (error: any) {
|
|
101
|
+
if (error.message?.includes('is async')) {
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Re-throw critical factory errors instead of masking them as "not found"
|
|
106
|
+
// If the error came from the factory execution (e.g. database connection failed), we must see it.
|
|
107
|
+
// "Service '${name}' not found" comes from PluginLoader.getService fallback.
|
|
108
|
+
const isNotFoundError = error.message === `Service '${name}' not found`;
|
|
109
|
+
|
|
110
|
+
if (!isNotFoundError) {
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
throw new Error(`[Kernel] Service '${name}' not found`);
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
hook: (name, handler) => {
|
|
118
|
+
if (!this.hooks.has(name)) {
|
|
119
|
+
this.hooks.set(name, []);
|
|
120
|
+
}
|
|
121
|
+
this.hooks.get(name)!.push(handler);
|
|
122
|
+
},
|
|
123
|
+
trigger: async (name, ...args) => {
|
|
124
|
+
const handlers = this.hooks.get(name) || [];
|
|
125
|
+
for (const handler of handlers) {
|
|
126
|
+
await handler(...args);
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
getServices: () => {
|
|
130
|
+
return new Map(this.services);
|
|
131
|
+
},
|
|
132
|
+
logger: this.logger,
|
|
133
|
+
getKernel: () => this as any, // Type compatibility
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
this.pluginLoader.setContext(this.context);
|
|
137
|
+
|
|
138
|
+
// Register shutdown handler
|
|
139
|
+
if (this.config.gracefulShutdown) {
|
|
140
|
+
this.registerShutdownSignals();
|
|
141
|
+
}
|
|
28
142
|
}
|
|
29
143
|
|
|
30
144
|
/**
|
|
31
|
-
* Register a plugin
|
|
32
|
-
* @param plugin - Plugin instance
|
|
145
|
+
* Register a plugin with enhanced validation
|
|
33
146
|
*/
|
|
34
|
-
use(plugin: Plugin): this {
|
|
35
|
-
this.
|
|
147
|
+
async use(plugin: Plugin): Promise<this> {
|
|
148
|
+
if (this.state !== 'idle') {
|
|
149
|
+
throw new Error('[Kernel] Cannot register plugins after bootstrap has started');
|
|
150
|
+
}
|
|
36
151
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
152
|
+
// Load plugin through enhanced loader
|
|
153
|
+
const result = await this.pluginLoader.loadPlugin(plugin);
|
|
154
|
+
|
|
155
|
+
if (!result.success || !result.plugin) {
|
|
156
|
+
throw new Error(`Failed to load plugin: ${plugin.name} - ${result.error?.message}`);
|
|
40
157
|
}
|
|
41
158
|
|
|
42
|
-
|
|
159
|
+
const pluginMeta = result.plugin;
|
|
160
|
+
this.plugins.set(pluginMeta.name, pluginMeta);
|
|
161
|
+
|
|
162
|
+
this.logger.info(`Plugin registered: ${pluginMeta.name}@${pluginMeta.version}`, {
|
|
163
|
+
plugin: pluginMeta.name,
|
|
164
|
+
version: pluginMeta.version,
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
return this;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Register a service factory with lifecycle management
|
|
172
|
+
*/
|
|
173
|
+
registerServiceFactory<T>(
|
|
174
|
+
name: string,
|
|
175
|
+
factory: ServiceFactory<T>,
|
|
176
|
+
lifecycle: ServiceLifecycle = ServiceLifecycle.SINGLETON,
|
|
177
|
+
dependencies?: string[]
|
|
178
|
+
): this {
|
|
179
|
+
this.pluginLoader.registerServiceFactory({
|
|
180
|
+
name,
|
|
181
|
+
factory,
|
|
182
|
+
lifecycle,
|
|
183
|
+
dependencies,
|
|
184
|
+
});
|
|
43
185
|
return this;
|
|
44
186
|
}
|
|
45
187
|
|
|
46
188
|
/**
|
|
47
|
-
* Bootstrap the kernel
|
|
48
|
-
* 1. Resolve dependencies (topological sort)
|
|
49
|
-
* 2. Init phase - plugins register services
|
|
50
|
-
* 3. Start phase - plugins execute business logic
|
|
51
|
-
* 4. Trigger 'kernel:ready' hook
|
|
189
|
+
* Bootstrap the kernel with enhanced features
|
|
52
190
|
*/
|
|
53
191
|
async bootstrap(): Promise<void> {
|
|
54
|
-
this.
|
|
192
|
+
if (this.state !== 'idle') {
|
|
193
|
+
throw new Error('[Kernel] Kernel already bootstrapped');
|
|
194
|
+
}
|
|
55
195
|
|
|
56
196
|
this.state = 'initializing';
|
|
57
197
|
this.logger.info('Bootstrap started');
|
|
58
198
|
|
|
59
|
-
|
|
60
|
-
|
|
199
|
+
try {
|
|
200
|
+
// Check for circular dependencies
|
|
201
|
+
const cycles = this.pluginLoader.detectCircularDependencies();
|
|
202
|
+
if (cycles.length > 0) {
|
|
203
|
+
this.logger.warn('Circular service dependencies detected:', { cycles });
|
|
204
|
+
}
|
|
61
205
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
for (const plugin of orderedPlugins) {
|
|
65
|
-
await this.runPluginInit(plugin);
|
|
66
|
-
}
|
|
206
|
+
// Resolve plugin dependencies
|
|
207
|
+
const orderedPlugins = this.resolveDependencies();
|
|
67
208
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
await this.runPluginStart(plugin);
|
|
74
|
-
}
|
|
209
|
+
// Phase 1: Init - Plugins register services
|
|
210
|
+
this.logger.info('Phase 1: Init plugins');
|
|
211
|
+
for (const plugin of orderedPlugins) {
|
|
212
|
+
await this.initPluginWithTimeout(plugin);
|
|
213
|
+
}
|
|
75
214
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
215
|
+
// Phase 2: Start - Plugins execute business logic
|
|
216
|
+
this.logger.info('Phase 2: Start plugins');
|
|
217
|
+
this.state = 'running';
|
|
218
|
+
|
|
219
|
+
for (const plugin of orderedPlugins) {
|
|
220
|
+
const result = await this.startPluginWithTimeout(plugin);
|
|
221
|
+
|
|
222
|
+
if (!result.success) {
|
|
223
|
+
this.logger.error(`Plugin startup failed: ${plugin.name}`, result.error);
|
|
224
|
+
|
|
225
|
+
if (this.config.rollbackOnFailure) {
|
|
226
|
+
this.logger.warn('Rolling back started plugins...');
|
|
227
|
+
await this.rollbackStartedPlugins();
|
|
228
|
+
throw new Error(`Plugin ${plugin.name} failed to start - rollback complete`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
82
232
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
233
|
+
// Phase 3: Trigger kernel:ready hook
|
|
234
|
+
this.logger.debug('Triggering kernel:ready hook');
|
|
235
|
+
await this.context.trigger('kernel:ready');
|
|
236
|
+
|
|
237
|
+
this.logger.info('✅ Bootstrap complete');
|
|
238
|
+
} catch (error) {
|
|
239
|
+
this.state = 'stopped';
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
89
242
|
}
|
|
90
243
|
|
|
91
244
|
/**
|
|
92
|
-
* Graceful shutdown
|
|
245
|
+
* Graceful shutdown with timeout
|
|
93
246
|
*/
|
|
94
|
-
async
|
|
95
|
-
if (this.state === 'stopped') {
|
|
96
|
-
this.logger.warn('Kernel already stopped');
|
|
247
|
+
async shutdown(): Promise<void> {
|
|
248
|
+
if (this.state === 'stopped' || this.state === 'stopping') {
|
|
249
|
+
this.logger.warn('Kernel already stopped or stopping');
|
|
97
250
|
return;
|
|
98
251
|
}
|
|
99
252
|
|
|
253
|
+
if (this.state !== 'running') {
|
|
254
|
+
throw new Error('[Kernel] Kernel not running');
|
|
255
|
+
}
|
|
256
|
+
|
|
100
257
|
this.state = 'stopping';
|
|
101
|
-
this.logger.info('
|
|
258
|
+
this.logger.info('Graceful shutdown started');
|
|
102
259
|
|
|
103
|
-
|
|
104
|
-
|
|
260
|
+
try {
|
|
261
|
+
// Create shutdown promise with timeout
|
|
262
|
+
const shutdownPromise = this.performShutdown();
|
|
263
|
+
const timeoutPromise = new Promise<void>((_, reject) => {
|
|
264
|
+
setTimeout(() => {
|
|
265
|
+
reject(new Error('Shutdown timeout exceeded'));
|
|
266
|
+
}, this.config.shutdownTimeout);
|
|
267
|
+
});
|
|
105
268
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
269
|
+
// Race between shutdown and timeout
|
|
270
|
+
await Promise.race([shutdownPromise, timeoutPromise]);
|
|
271
|
+
|
|
272
|
+
this.state = 'stopped';
|
|
273
|
+
this.logger.info('✅ Graceful shutdown complete');
|
|
274
|
+
} catch (error) {
|
|
275
|
+
this.logger.error('Shutdown error - forcing stop', error as Error);
|
|
276
|
+
this.state = 'stopped';
|
|
277
|
+
throw error;
|
|
278
|
+
} finally {
|
|
279
|
+
// Cleanup logger resources
|
|
280
|
+
await this.logger.destroy();
|
|
110
281
|
}
|
|
282
|
+
}
|
|
111
283
|
|
|
112
|
-
|
|
113
|
-
|
|
284
|
+
/**
|
|
285
|
+
* Check health of a specific plugin
|
|
286
|
+
*/
|
|
287
|
+
async checkPluginHealth(pluginName: string): Promise<any> {
|
|
288
|
+
return await this.pluginLoader.checkPluginHealth(pluginName);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Check health of all plugins
|
|
293
|
+
*/
|
|
294
|
+
async checkAllPluginsHealth(): Promise<Map<string, any>> {
|
|
295
|
+
const results = new Map();
|
|
114
296
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
297
|
+
for (const pluginName of this.plugins.keys()) {
|
|
298
|
+
const health = await this.checkPluginHealth(pluginName);
|
|
299
|
+
results.set(pluginName, health);
|
|
118
300
|
}
|
|
301
|
+
|
|
302
|
+
return results;
|
|
119
303
|
}
|
|
120
304
|
|
|
121
305
|
/**
|
|
122
|
-
* Get
|
|
123
|
-
|
|
306
|
+
* Get plugin startup metrics
|
|
307
|
+
*/
|
|
308
|
+
getPluginMetrics(): Map<string, number> {
|
|
309
|
+
return new Map(this.pluginStartTimes);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Get a service (sync helper)
|
|
124
314
|
*/
|
|
125
315
|
getService<T>(name: string): T {
|
|
126
316
|
return this.context.getService<T>(name);
|
|
127
317
|
}
|
|
128
318
|
|
|
319
|
+
/**
|
|
320
|
+
* Get a service asynchronously (supports factories)
|
|
321
|
+
*/
|
|
322
|
+
async getServiceAsync<T>(name: string, scopeId?: string): Promise<T> {
|
|
323
|
+
return await this.pluginLoader.getService<T>(name, scopeId);
|
|
324
|
+
}
|
|
325
|
+
|
|
129
326
|
/**
|
|
130
327
|
* Check if kernel is running
|
|
131
328
|
*/
|
|
132
329
|
isRunning(): boolean {
|
|
133
330
|
return this.state === 'running';
|
|
134
331
|
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Get kernel state
|
|
335
|
+
*/
|
|
336
|
+
getState(): string {
|
|
337
|
+
return this.state;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Private methods
|
|
341
|
+
|
|
342
|
+
private async initPluginWithTimeout(plugin: PluginMetadata): Promise<void> {
|
|
343
|
+
const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout!;
|
|
344
|
+
|
|
345
|
+
this.logger.debug(`Init: ${plugin.name}`, { plugin: plugin.name });
|
|
346
|
+
|
|
347
|
+
const initPromise = plugin.init(this.context);
|
|
348
|
+
const timeoutPromise = new Promise<void>((_, reject) => {
|
|
349
|
+
setTimeout(() => {
|
|
350
|
+
reject(new Error(`Plugin ${plugin.name} init timeout after ${timeout}ms`));
|
|
351
|
+
}, timeout);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
await Promise.race([initPromise, timeoutPromise]);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
private async startPluginWithTimeout(plugin: PluginMetadata): Promise<PluginStartupResult> {
|
|
358
|
+
if (!plugin.start) {
|
|
359
|
+
return { success: true, pluginName: plugin.name };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const timeout = plugin.startupTimeout || this.config.defaultStartupTimeout!;
|
|
363
|
+
const startTime = Date.now();
|
|
364
|
+
|
|
365
|
+
this.logger.debug(`Start: ${plugin.name}`, { plugin: plugin.name });
|
|
366
|
+
|
|
367
|
+
try {
|
|
368
|
+
const startPromise = plugin.start(this.context);
|
|
369
|
+
const timeoutPromise = new Promise<void>((_, reject) => {
|
|
370
|
+
setTimeout(() => {
|
|
371
|
+
reject(new Error(`Plugin ${plugin.name} start timeout after ${timeout}ms`));
|
|
372
|
+
}, timeout);
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
await Promise.race([startPromise, timeoutPromise]);
|
|
376
|
+
|
|
377
|
+
const duration = Date.now() - startTime;
|
|
378
|
+
this.startedPlugins.add(plugin.name);
|
|
379
|
+
this.pluginStartTimes.set(plugin.name, duration);
|
|
380
|
+
|
|
381
|
+
this.logger.debug(`Plugin started: ${plugin.name} (${duration}ms)`);
|
|
382
|
+
|
|
383
|
+
return {
|
|
384
|
+
success: true,
|
|
385
|
+
pluginName: plugin.name,
|
|
386
|
+
startTime: duration,
|
|
387
|
+
};
|
|
388
|
+
} catch (error) {
|
|
389
|
+
const duration = Date.now() - startTime;
|
|
390
|
+
const isTimeout = (error as Error).message.includes('timeout');
|
|
391
|
+
|
|
392
|
+
return {
|
|
393
|
+
success: false,
|
|
394
|
+
pluginName: plugin.name,
|
|
395
|
+
error: error as Error,
|
|
396
|
+
startTime: duration,
|
|
397
|
+
timedOut: isTimeout,
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
private async rollbackStartedPlugins(): Promise<void> {
|
|
403
|
+
const pluginsToRollback = Array.from(this.startedPlugins).reverse();
|
|
404
|
+
|
|
405
|
+
for (const pluginName of pluginsToRollback) {
|
|
406
|
+
const plugin = this.plugins.get(pluginName);
|
|
407
|
+
if (plugin?.destroy) {
|
|
408
|
+
try {
|
|
409
|
+
this.logger.debug(`Rollback: ${pluginName}`);
|
|
410
|
+
await plugin.destroy();
|
|
411
|
+
} catch (error) {
|
|
412
|
+
this.logger.error(`Rollback failed for ${pluginName}`, error as Error);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
this.startedPlugins.clear();
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private async performShutdown(): Promise<void> {
|
|
421
|
+
// Trigger shutdown hook
|
|
422
|
+
await this.context.trigger('kernel:shutdown');
|
|
423
|
+
|
|
424
|
+
// Destroy plugins in reverse order
|
|
425
|
+
const orderedPlugins = Array.from(this.plugins.values()).reverse();
|
|
426
|
+
for (const plugin of orderedPlugins) {
|
|
427
|
+
if (plugin.destroy) {
|
|
428
|
+
this.logger.debug(`Destroy: ${plugin.name}`, { plugin: plugin.name });
|
|
429
|
+
try {
|
|
430
|
+
await plugin.destroy();
|
|
431
|
+
} catch (error) {
|
|
432
|
+
this.logger.error(`Error destroying plugin ${plugin.name}`, error as Error);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// Execute custom shutdown handlers
|
|
438
|
+
for (const handler of this.shutdownHandlers) {
|
|
439
|
+
try {
|
|
440
|
+
await handler();
|
|
441
|
+
} catch (error) {
|
|
442
|
+
this.logger.error('Shutdown handler error', error as Error);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
private resolveDependencies(): PluginMetadata[] {
|
|
448
|
+
const resolved: PluginMetadata[] = [];
|
|
449
|
+
const visited = new Set<string>();
|
|
450
|
+
const visiting = new Set<string>();
|
|
451
|
+
|
|
452
|
+
const visit = (pluginName: string) => {
|
|
453
|
+
if (visited.has(pluginName)) return;
|
|
454
|
+
|
|
455
|
+
if (visiting.has(pluginName)) {
|
|
456
|
+
throw new Error(`[Kernel] Circular dependency detected: ${pluginName}`);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const plugin = this.plugins.get(pluginName);
|
|
460
|
+
if (!plugin) {
|
|
461
|
+
throw new Error(`[Kernel] Plugin '${pluginName}' not found`);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
visiting.add(pluginName);
|
|
465
|
+
|
|
466
|
+
// Visit dependencies first
|
|
467
|
+
const deps = plugin.dependencies || [];
|
|
468
|
+
for (const dep of deps) {
|
|
469
|
+
if (!this.plugins.has(dep)) {
|
|
470
|
+
throw new Error(`[Kernel] Dependency '${dep}' not found for plugin '${pluginName}'`);
|
|
471
|
+
}
|
|
472
|
+
visit(dep);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
visiting.delete(pluginName);
|
|
476
|
+
visited.add(pluginName);
|
|
477
|
+
resolved.push(plugin);
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
// Visit all plugins
|
|
481
|
+
for (const pluginName of this.plugins.keys()) {
|
|
482
|
+
visit(pluginName);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
return resolved;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
private registerShutdownSignals(): void {
|
|
489
|
+
const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGQUIT'];
|
|
490
|
+
let shutdownInProgress = false;
|
|
491
|
+
|
|
492
|
+
const handleShutdown = async (signal: string) => {
|
|
493
|
+
if (shutdownInProgress) {
|
|
494
|
+
this.logger.warn(`Shutdown already in progress, ignoring ${signal}`);
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
shutdownInProgress = true;
|
|
499
|
+
this.logger.info(`Received ${signal} - initiating graceful shutdown`);
|
|
500
|
+
|
|
501
|
+
try {
|
|
502
|
+
await this.shutdown();
|
|
503
|
+
process.exit(0);
|
|
504
|
+
} catch (error) {
|
|
505
|
+
this.logger.error('Shutdown failed', error as Error);
|
|
506
|
+
process.exit(1);
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
for (const signal of signals) {
|
|
511
|
+
process.on(signal, () => handleShutdown(signal));
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Register a custom shutdown handler
|
|
517
|
+
*/
|
|
518
|
+
onShutdown(handler: () => Promise<void>): void {
|
|
519
|
+
this.shutdownHandlers.push(handler);
|
|
520
|
+
}
|
|
135
521
|
}
|