-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathkernel.test.ts
More file actions
642 lines (515 loc) · 20.1 KB
/
Copy pathkernel.test.ts
File metadata and controls
642 lines (515 loc) · 20.1 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
import { describe, it, expect, beforeEach } from 'vitest';
import { ObjectKernel } from './kernel';
import { ServiceLifecycle, PluginMetadata } from './plugin-loader';
import type { Plugin } from './types';
describe('ObjectKernel', () => {
let kernel: ObjectKernel;
beforeEach(() => {
kernel = new ObjectKernel({
logger: { level: 'error' }, // Suppress logs in tests
gracefulShutdown: false, // Disable for tests
skipSystemValidation: true,
});
});
describe('Plugin Registration and Loading', () => {
it('should register a plugin with version', async () => {
const plugin: Plugin = {
name: 'versioned-plugin',
version: '1.2.3',
init: async () => {},
};
await kernel.use(plugin);
await kernel.bootstrap();
expect(kernel.isRunning()).toBe(true);
await kernel.shutdown();
});
it('should validate plugin during registration', async () => {
const invalidPlugin: any = {
name: '',
init: async () => {},
};
await expect(async () => {
await kernel.use(invalidPlugin);
}).rejects.toThrow();
});
it('should reject plugin registration after bootstrap', async () => {
await kernel.bootstrap();
const plugin: Plugin = {
name: 'late-plugin',
init: async () => {},
};
await expect(async () => {
await kernel.use(plugin);
}).rejects.toThrow('Cannot register plugins after bootstrap');
await kernel.shutdown();
});
});
describe('Service Factory Registration', () => {
it('should register singleton service factory', async () => {
let callCount = 0;
kernel.registerServiceFactory(
'counter',
() => {
callCount++;
return { count: callCount };
},
ServiceLifecycle.SINGLETON
);
await kernel.bootstrap();
const service1 = await kernel.getServiceAsync('counter');
const service2 = await kernel.getServiceAsync('counter');
expect(callCount).toBe(1);
expect(service1).toBe(service2);
await kernel.shutdown();
});
it('should register transient service factory', async () => {
let callCount = 0;
kernel.registerServiceFactory(
'transient',
() => {
callCount++;
return { count: callCount };
},
ServiceLifecycle.TRANSIENT
);
await kernel.bootstrap();
const service1 = await kernel.getServiceAsync('transient');
const service2 = await kernel.getServiceAsync('transient');
expect(callCount).toBe(2);
expect(service1).not.toBe(service2);
await kernel.shutdown();
});
it('should register scoped service factory', async () => {
let callCount = 0;
kernel.registerServiceFactory(
'scoped',
() => {
callCount++;
return { count: callCount };
},
ServiceLifecycle.SCOPED
);
await kernel.bootstrap();
const service1 = await kernel.getServiceAsync('scoped', 'request-1');
const service2 = await kernel.getServiceAsync('scoped', 'request-1');
const service3 = await kernel.getServiceAsync('scoped', 'request-2');
expect(callCount).toBe(2); // Once per scope
expect(service1).toBe(service2); // Same within scope
expect(service1).not.toBe(service3); // Different across scopes
await kernel.shutdown();
});
});
describe('Plugin Lifecycle with Timeout', () => {
it('should timeout plugin init if it takes too long', async () => {
const plugin: PluginMetadata = {
name: 'slow-init',
version: '1.0.0',
init: async () => {
await new Promise(resolve => setTimeout(resolve, 5000)); // 5 seconds
},
startupTimeout: 100, // 100ms timeout
};
await kernel.use(plugin);
await expect(async () => {
await kernel.bootstrap();
}).rejects.toThrow('timeout');
}, 1000); // Test should complete in 1 second
it('should timeout plugin start if it takes too long', async () => {
const plugin: PluginMetadata = {
name: 'slow-start',
version: '1.0.0',
init: async () => {},
start: async () => {
await new Promise(resolve => setTimeout(resolve, 5000)); // 5 seconds
},
startupTimeout: 100, // 100ms timeout
};
await kernel.use(plugin);
await expect(async () => {
await kernel.bootstrap();
}).rejects.toThrow();
}, 1000); // Test should complete in 1 second
it('should complete plugin startup within timeout', async () => {
const plugin: PluginMetadata = {
name: 'fast-plugin',
version: '1.0.0',
init: async () => {
await new Promise(resolve => setTimeout(resolve, 10));
},
start: async () => {
await new Promise(resolve => setTimeout(resolve, 10));
},
startupTimeout: 1000,
};
await kernel.use(plugin);
await kernel.bootstrap();
expect(kernel.isRunning()).toBe(true);
await kernel.shutdown();
});
});
describe('Startup Failure Rollback', () => {
it('should rollback started plugins on failure', async () => {
let plugin1Destroyed = false;
const plugin1: Plugin = {
name: 'plugin-1',
version: '1.0.0',
init: async () => {},
start: async () => {},
destroy: async () => {
plugin1Destroyed = true;
},
};
const plugin2: Plugin = {
name: 'plugin-2',
version: '1.0.0',
init: async () => {},
start: async () => {
throw new Error('Startup failed');
},
};
await kernel.use(plugin1);
await kernel.use(plugin2);
await expect(async () => {
await kernel.bootstrap();
}).rejects.toThrow('failed to start');
// Plugin 1 should be rolled back
expect(plugin1Destroyed).toBe(true);
});
it('should not rollback if disabled', async () => {
const noRollbackKernel = new ObjectKernel({
logger: { level: 'error' },
rollbackOnFailure: false,
gracefulShutdown: false,
skipSystemValidation: true,
});
let plugin1Destroyed = false;
const plugin1: Plugin = {
name: 'plugin-1',
version: '1.0.0',
init: async () => {},
start: async () => {},
destroy: async () => {
plugin1Destroyed = true;
},
};
const plugin2: Plugin = {
name: 'plugin-2',
version: '1.0.0',
init: async () => {},
start: async () => {
throw new Error('Startup failed');
},
};
await noRollbackKernel.use(plugin1);
await noRollbackKernel.use(plugin2);
// Should not throw since rollback is disabled
await noRollbackKernel.bootstrap();
// Plugin 1 should NOT be destroyed
expect(plugin1Destroyed).toBe(false);
});
});
describe('Plugin Health Checks', () => {
it('should check individual plugin health', async () => {
const plugin: Plugin = {
name: 'healthy-plugin',
version: '1.0.0',
init: async () => {},
};
await kernel.use(plugin);
await kernel.bootstrap();
const health = await kernel.checkPluginHealth('healthy-plugin');
expect(health.healthy).toBe(true);
expect(health.lastCheck).toBeInstanceOf(Date);
await kernel.shutdown();
});
it('should check all plugins health', async () => {
const plugin1: Plugin = {
name: 'plugin-1',
version: '1.0.0',
init: async () => {},
};
const plugin2: Plugin = {
name: 'plugin-2',
version: '1.0.0',
init: async () => {},
};
await kernel.use(plugin1);
await kernel.use(plugin2);
await kernel.bootstrap();
const allHealth = await kernel.checkAllPluginsHealth();
expect(allHealth.size).toBe(2);
expect(allHealth.get('plugin-1').healthy).toBe(true);
expect(allHealth.get('plugin-2').healthy).toBe(true);
await kernel.shutdown();
});
});
describe('Plugin Metrics', () => {
it('should track plugin startup times', async () => {
const plugin1: Plugin = {
name: 'plugin-1',
version: '1.0.0',
init: async () => {},
start: async () => {
await new Promise(resolve => setTimeout(resolve, 50));
},
};
const plugin2: Plugin = {
name: 'plugin-2',
version: '1.0.0',
init: async () => {},
start: async () => {
await new Promise(resolve => setTimeout(resolve, 30));
},
};
await kernel.use(plugin1);
await kernel.use(plugin2);
await kernel.bootstrap();
const metrics = kernel.getPluginMetrics();
expect(metrics.size).toBe(2);
expect(metrics.get('plugin-1')).toBeGreaterThan(0);
expect(metrics.get('plugin-2')).toBeGreaterThan(0);
await kernel.shutdown();
});
it('should not track metrics for plugins without start', async () => {
const plugin: Plugin = {
name: 'no-start',
version: '1.0.0',
init: async () => {},
};
await kernel.use(plugin);
await kernel.bootstrap();
const metrics = kernel.getPluginMetrics();
expect(metrics.has('no-start')).toBe(false);
await kernel.shutdown();
});
});
describe('Graceful Shutdown', () => {
it('should call destroy on all plugins', async () => {
let plugin1Destroyed = false;
let plugin2Destroyed = false;
const plugin1: Plugin = {
name: 'plugin-1',
version: '1.0.0',
init: async () => {},
destroy: async () => {
plugin1Destroyed = true;
},
};
const plugin2: Plugin = {
name: 'plugin-2',
version: '1.0.0',
init: async () => {},
destroy: async () => {
plugin2Destroyed = true;
},
};
await kernel.use(plugin1);
await kernel.use(plugin2);
await kernel.bootstrap();
await kernel.shutdown();
expect(plugin1Destroyed).toBe(true);
expect(plugin2Destroyed).toBe(true);
});
it('should handle plugin destroy errors gracefully', async () => {
const plugin1: Plugin = {
name: 'error-destroy',
version: '1.0.0',
init: async () => {},
destroy: async () => {
throw new Error('Destroy failed');
},
};
const plugin2: Plugin = {
name: 'normal-plugin',
version: '1.0.0',
init: async () => {},
};
await kernel.use(plugin1);
await kernel.use(plugin2);
await kernel.bootstrap();
// Should not throw even if one plugin fails to destroy
await kernel.shutdown();
expect(kernel.getState()).toBe('stopped');
});
it('fires kernel:ready → kernel:bootstrapped → kernel:listening in order', async () => {
const order: string[] = [];
const plugin: Plugin = {
name: 'lifecycle-order-plugin',
version: '1.0.0',
init: async (ctx) => {
ctx.hook('kernel:listening', async () => { order.push('kernel:listening'); });
ctx.hook('kernel:bootstrapped', async () => { order.push('kernel:bootstrapped'); });
ctx.hook('kernel:ready', async () => { order.push('kernel:ready'); });
},
};
await kernel.use(plugin);
await kernel.bootstrap();
expect(order).toEqual(['kernel:ready', 'kernel:bootstrapped', 'kernel:listening']);
});
it('should trigger shutdown hook', async () => {
let hookCalled = false;
const plugin: Plugin = {
name: 'hook-plugin',
version: '1.0.0',
init: async (ctx) => {
ctx.hook('kernel:shutdown', async () => {
hookCalled = true;
});
},
};
await kernel.use(plugin);
await kernel.bootstrap();
await kernel.shutdown();
expect(hookCalled).toBe(true);
});
it('should execute custom shutdown handlers', async () => {
let handlerCalled = false;
kernel.onShutdown(async () => {
handlerCalled = true;
});
await kernel.bootstrap();
await kernel.shutdown();
expect(handlerCalled).toBe(true);
});
});
describe('Dependency Resolution', () => {
it('should resolve plugin dependencies in correct order', async () => {
const initOrder: string[] = [];
const pluginA: Plugin = {
name: 'plugin-a',
version: '1.0.0',
dependencies: ['plugin-b'],
init: async () => {
initOrder.push('plugin-a');
},
};
const pluginB: Plugin = {
name: 'plugin-b',
version: '1.0.0',
init: async () => {
initOrder.push('plugin-b');
},
};
await kernel.use(pluginA);
await kernel.use(pluginB);
await kernel.bootstrap();
expect(initOrder).toEqual(['plugin-b', 'plugin-a']);
await kernel.shutdown();
});
it('should detect circular plugin dependencies', async () => {
const pluginA: Plugin = {
name: 'plugin-a',
version: '1.0.0',
dependencies: ['plugin-b'],
init: async () => {},
};
const pluginB: Plugin = {
name: 'plugin-b',
version: '1.0.0',
dependencies: ['plugin-a'],
init: async () => {},
};
await kernel.use(pluginA);
await kernel.use(pluginB);
await expect(async () => {
await kernel.bootstrap();
}).rejects.toThrow('Circular dependency');
});
});
describe('State Management', () => {
it('should track kernel state correctly', async () => {
expect(kernel.getState()).toBe('idle');
await kernel.bootstrap();
expect(kernel.getState()).toBe('running');
expect(kernel.isRunning()).toBe(true);
await kernel.shutdown();
expect(kernel.getState()).toBe('stopped');
expect(kernel.isRunning()).toBe(false);
});
it('should not allow double bootstrap', async () => {
await kernel.bootstrap();
await expect(async () => {
await kernel.bootstrap();
}).rejects.toThrow('already bootstrapped');
await kernel.shutdown();
});
it('should not allow shutdown before bootstrap', async () => {
await expect(async () => {
await kernel.shutdown();
}).rejects.toThrow('not running');
});
});
describe('Service Replacement', () => {
it('should replace an existing service via replaceService', async () => {
const originalService = { value: 'original' };
const replacementService = { value: 'replaced' };
const plugin: Plugin = {
name: 'register-plugin',
version: '1.0.0',
init: async (ctx) => {
ctx.registerService('metadata', originalService);
},
};
const optimizationPlugin: Plugin = {
name: 'optimization-plugin',
version: '1.0.0',
dependencies: ['register-plugin'],
init: async (ctx) => {
const existing = ctx.getService('metadata');
expect(existing).toBe(originalService);
ctx.replaceService('metadata', replacementService);
},
};
await kernel.use(plugin);
await kernel.use(optimizationPlugin);
await kernel.bootstrap();
const result = kernel.getService('metadata');
expect(result).toBe(replacementService);
await kernel.shutdown();
});
it('should throw when replacing a non-existent service', async () => {
const plugin: Plugin = {
name: 'bad-replace-plugin',
version: '1.0.0',
init: async (ctx) => {
expect(() => {
ctx.replaceService('nonexistent', { value: 'test' });
}).toThrow("Service 'nonexistent' not found");
},
};
await kernel.use(plugin);
await kernel.bootstrap();
await kernel.shutdown();
});
it('should allow decorator pattern via replaceService', async () => {
const original = {
getData: () => 'raw-data',
};
const plugin: Plugin = {
name: 'data-plugin',
version: '1.0.0',
init: async (ctx) => {
ctx.registerService('data', original);
},
};
const wrapperPlugin: Plugin = {
name: 'wrapper-plugin',
version: '1.0.0',
dependencies: ['data-plugin'],
init: async (ctx) => {
const existing = ctx.getService<typeof original>('data');
const decorated = {
getData: () => `cached(${existing.getData()})`,
};
ctx.replaceService('data', decorated);
},
};
await kernel.use(plugin);
await kernel.use(wrapperPlugin);
await kernel.bootstrap();
const result = kernel.getService<typeof original>('data');
expect(result.getData()).toBe('cached(raw-data)');
await kernel.shutdown();
});
});
});