Elffuss BraidHub

kikocis/continue public

6d96ea0ab3d5 · 13.6 KiBRawPermalink
1import { describe, expect, test, beforeEach, vi } from "vitest";
2
3// Import the actual BaseService implementation directly
4import { EventEmitter } from "events";
5
6import { logger } from "../util/logger.js";
7
8/**
9 * Base abstract class for all services
10 * Provides common lifecycle methods and state management
11 */
12abstract class BaseService<TState> extends EventEmitter {
13 protected serviceName: string;
14 protected currentState: TState;
15 private isInitialized: boolean = false;
16
17 constructor(serviceName: string, initialState: TState) {
18 super();
19 this.serviceName = serviceName;
20 this.currentState = initialState;
21 }
22
23 /**
24 * Initialize the service (must be implemented by subclasses)
25 * This is automatically wrapped with initialization logic
26 */
27 abstract doInitialize(...args: any[]): Promise<TState>;
28
29 /**
30 * Public initialization method that wraps the implementation
31 */
32 async initialize(...args: any[]): Promise<TState> {
33 logger.debug(`Initializing ${this.serviceName}`, {
34 wasInitialized: this.isInitialized,
35 hadPreviousState: !!this.currentState,
36 });
37 this.emit("initializing");
38
39 try {
40 const state = await this.doInitialize(...args);
41 this.currentState = state;
42 this.isInitialized = true;
43 logger.debug(`${this.serviceName} initialized successfully`, {
44 stateKeys: state ? Object.keys(state as any) : [],
45 isNowInitialized: this.isInitialized,
46 });
47 this.emit("initialized", state);
48 return state;
49 } catch (error: any) {
50 logger.debug(`Failed to initialize ${this.serviceName}:`, error);
51 if (this.listenerCount("error") > 0) {
52 this.emit("error", error);
53 }
54 throw error;
55 }
56 }
57
58 /**
59 * Get current service state (shallow copy for immutability)
60 */
61 getState(): TState {
62 return { ...this.currentState };
63 }
64
65 /**
66 * Update service state and emit change event
67 */
68 protected setState(newState: Partial<TState>): void {
69 const previousState = this.currentState;
70 this.currentState = { ...this.currentState, ...newState };
71 // Only log state updates if not in production to avoid circular reference issues
72 if (process.env.NODE_ENV !== "production") {
73 logger.debug(`${this.serviceName} state updated`);
74 }
75 this.emit("stateChanged", this.currentState, previousState);
76 }
77
78 /**
79 * Check if service is ready for use
80 */
81 isReady(): boolean {
82 return this.isInitialized;
83 }
84
85 /**
86 * Reload/refresh the service
87 */
88 async reload(...args: any[]): Promise<TState> {
89 logger.debug(`Reloading ${this.serviceName}`);
90 this.isInitialized = false;
91 return this.initialize(...args);
92 }
93
94 /**
95 * Cleanup resources (can be overridden by subclasses)
96 */
97 async cleanup(): Promise<void> {
98 logger.debug(`Cleaning up ${this.serviceName}`);
99 this.removeAllListeners();
100 this.isInitialized = false;
101 }
102}
103
104/**
105 * Interface for services with dependencies
106 */
107interface ServiceWithDependencies {
108 getDependencies(): string[];
109}
110
111/**
112 * Helper to check if a service has dependencies
113 */
114function hasDependencies(service: any): service is ServiceWithDependencies {
115 return !!service && typeof service.getDependencies === "function";
116}
117
118// Test implementation of BaseService
119interface TestState {
120 value: number;
121 message: string;
122 data?: any[];
123}
124
125class TestService extends BaseService<TestState> {
126 constructor() {
127 super("TestService", {
128 value: 0,
129 message: "initial",
130 });
131 }
132
133 async doInitialize(value: number, message: string): Promise<TestState> {
134 return {
135 value,
136 message,
137 };
138 }
139
140 // Expose setState for testing
141 updateState(newState: Partial<TestState>) {
142 this.setState(newState);
143 }
144}
145
146// Test service with dependencies
147class DependentTestService
148 extends TestService
149 implements ServiceWithDependencies
150{
151 getDependencies(): string[] {
152 return ["auth", "config"];
153 }
154}
155
156// Test service that throws during initialization
157class FailingTestService extends BaseService<TestState> {
158 constructor() {
159 super("FailingService", {
160 value: 0,
161 message: "initial",
162 });
163 }
164
165 async doInitialize(): Promise<TestState> {
166 throw new Error("Initialization failed");
167 }
168}
169
170describe("BaseService", () => {
171 describe("Basic Functionality", () => {
172 let service: TestService;
173
174 beforeEach(() => {
175 service = new TestService();
176 });
177
178 test("should have correct initial state", () => {
179 const state = service.getState();
180 expect(state).toEqual({
181 value: 0,
182 message: "initial",
183 });
184 expect(service.isReady()).toBe(false);
185 });
186
187 test("should initialize successfully", async () => {
188 const state = await service.initialize(42, "initialized");
189
190 expect(state).toEqual({
191 value: 42,
192 message: "initialized",
193 });
194 expect(service.isReady()).toBe(true);
195 });
196
197 test("should emit initialization events", async () => {
198 const initializingListener = vi.fn();
199 const initializedListener = vi.fn();
200
201 service.on("initializing", initializingListener);
202 service.on("initialized", initializedListener);
203
204 await service.initialize(42, "initialized");
205
206 expect(initializingListener).toHaveBeenCalledTimes(1);
207 expect(initializedListener).toHaveBeenCalledTimes(1);
208 expect(initializedListener).toHaveBeenCalledWith({
209 value: 42,
210 message: "initialized",
211 });
212 });
213
214 test("should handle initialization failure", async () => {
215 const failingService = new FailingTestService();
216 const errorListener = vi.fn();
217
218 failingService.on("error", errorListener);
219
220 await expect(failingService.initialize()).rejects.toThrow(
221 "Initialization failed",
222 );
223 expect(errorListener).toHaveBeenCalledTimes(1);
224 expect(failingService.isReady()).toBe(false);
225 });
226 });
227
228 describe("State Management", () => {
229 let service: TestService;
230
231 beforeEach(() => {
232 service = new TestService();
233 });
234
235 test("should return immutable state copy", async () => {
236 await service.initialize(42, "test");
237
238 const state1 = service.getState();
239 const state2 = service.getState();
240
241 expect(state1).toEqual(state2);
242 expect(state1).not.toBe(state2); // Different object references
243 });
244
245 test("should return shallow copy of state", async () => {
246 await service.initialize(42, "test");
247 service.updateState({ data: [{ id: 1 }, { id: 2 }] });
248
249 const state = service.getState();
250 const originalData = state.data;
251
252 // Modify the returned state's nested object
253 if (state.data) {
254 state.data[0].id = 999;
255 }
256
257 // With shallow copy, nested objects are shared
258 const newState = service.getState();
259 expect(newState.data).toEqual([{ id: 999 }, { id: 2 }]);
260 expect(newState.data).toBe(originalData); // Same reference for nested objects
261 });
262
263 test("should emit state change events", async () => {
264 await service.initialize(42, "test");
265
266 const stateChangeListener = vi.fn();
267 service.on("stateChanged", stateChangeListener);
268
269 service.updateState({ value: 100 });
270
271 expect(stateChangeListener).toHaveBeenCalledTimes(1);
272 expect(stateChangeListener).toHaveBeenCalledWith(
273 { value: 100, message: "test" }, // new state
274 { value: 42, message: "test" }, // previous state
275 );
276 });
277
278 test("should merge partial state updates", async () => {
279 await service.initialize(42, "test");
280
281 service.updateState({ value: 100 });
282 expect(service.getState()).toEqual({
283 value: 100,
284 message: "test",
285 });
286
287 service.updateState({ message: "updated" });
288 expect(service.getState()).toEqual({
289 value: 100,
290 message: "updated",
291 });
292 });
293 });
294
295 describe("Reload Functionality", () => {
296 let service: TestService;
297
298 beforeEach(() => {
299 service = new TestService();
300 });
301
302 test("should reload service with new parameters", async () => {
303 await service.initialize(42, "first");
304 expect(service.getState()).toEqual({
305 value: 42,
306 message: "first",
307 });
308
309 await service.reload(100, "second");
310 expect(service.getState()).toEqual({
311 value: 100,
312 message: "second",
313 });
314 expect(service.isReady()).toBe(true);
315 });
316
317 test("should reset isInitialized during reload", async () => {
318 await service.initialize(42, "test");
319 expect(service.isReady()).toBe(true);
320
321 // Create a promise to check intermediate state
322 let wasNotReady = false;
323 const originalInit = service.initialize.bind(service);
324 service.initialize = vi.fn(async (value: number, message: string) => {
325 wasNotReady = !service.isReady();
326 return originalInit(value, message);
327 }) as any;
328
329 await service.reload(100, "reloaded");
330
331 expect(wasNotReady).toBe(true);
332 expect(service.isReady()).toBe(true);
333 });
334 });
335
336 describe("Cleanup", () => {
337 let service: TestService;
338
339 beforeEach(() => {
340 service = new TestService();
341 });
342
343 test("should cleanup resources", async () => {
344 await service.initialize(42, "test");
345
346 const listener = vi.fn();
347 service.on("test-event", listener);
348
349 await service.cleanup();
350
351 expect(service.isReady()).toBe(false);
352
353 // Verify listeners are removed
354 service.emit("test-event");
355 expect(listener).not.toHaveBeenCalled();
356 });
357 });
358
359 describe("ServiceWithDependencies", () => {
360 test("should correctly identify services with dependencies", () => {
361 const regularService = new TestService();
362 const dependentService = new DependentTestService();
363
364 expect(hasDependencies(regularService)).toBe(false);
365 expect(hasDependencies(dependentService)).toBe(true);
366
367 if (hasDependencies(dependentService)) {
368 expect(dependentService.getDependencies()).toEqual(["auth", "config"]);
369 }
370 });
371 });
372
373 describe("Shallow Copy Functionality", () => {
374 let service: TestService;
375
376 beforeEach(() => {
377 service = new TestService();
378 });
379
380 test("should handle null and undefined values", async () => {
381 await service.initialize(42, "test");
382 service.updateState({
383 data: [null, undefined, "string", 123] as any,
384 });
385
386 const state = service.getState();
387 expect(state.data).toEqual([null, undefined, "string", 123]);
388 });
389
390 test("should handle Date objects", async () => {
391 const date = new Date("2024-01-01");
392 await service.initialize(42, "test");
393 service.updateState({
394 data: [date] as any,
395 });
396
397 const state = service.getState();
398 expect(state.data?.[0]).toEqual(date);
399 expect(state.data?.[0]).toBe(date); // Same instance with shallow copy
400 expect(state.data?.[0]).toBeInstanceOf(Date);
401 });
402
403 test("should handle complex nested structures", async () => {
404 const complexData = {
405 nested: {
406 array: [1, 2, { deep: "value" }],
407 date: new Date(),
408 bool: true,
409 null: null,
410 },
411 };
412
413 await service.initialize(42, "test");
414 service.updateState({ data: complexData as any });
415
416 const state = service.getState();
417 expect(state.data).toEqual(complexData);
418 expect(state.data).toBe(complexData); // Same reference with shallow copy
419
420 // Verify nested objects are shared (not deep copied)
421 if (
422 state.data &&
423 typeof state.data === "object" &&
424 "nested" in state.data
425 ) {
426 const data = state.data as any;
427 expect(data.nested.array).toBe(complexData.nested.array);
428 expect(data.nested.array[2]).toBe(complexData.nested.array[2]);
429 }
430 });
431 });
432
433 describe("Error Handling", () => {
434 test("should emit error events on setState failures", () => {
435 const service = new TestService();
436
437 // Override setState to throw
438 const originalSetState = Object.getOwnPropertyDescriptor(
439 Object.getPrototypeOf(service),
440 "setState",
441 );
442
443 Object.defineProperty(service, "setState", {
444 value: function () {
445 throw new Error("setState failed");
446 },
447 });
448
449 expect(() => service.updateState({ value: 100 })).toThrow(
450 "setState failed",
451 );
452
453 // Restore original
454 if (originalSetState) {
455 Object.defineProperty(
456 Object.getPrototypeOf(service),
457 "setState",
458 originalSetState,
459 );
460 }
461 });
462 });
463
464 describe("Event Emitter Integration", () => {
465 let service: TestService;
466
467 beforeEach(() => {
468 service = new TestService();
469 });
470
471 test("should support multiple listeners", async () => {
472 const listener1 = vi.fn();
473 const listener2 = vi.fn();
474
475 service.on("initialized", listener1);
476 service.on("initialized", listener2);
477
478 await service.initialize(42, "test");
479
480 expect(listener1).toHaveBeenCalledTimes(1);
481 expect(listener2).toHaveBeenCalledTimes(1);
482 });
483
484 test("should support once listeners", async () => {
485 const listener = vi.fn();
486
487 service.once("stateChanged", listener);
488
489 await service.initialize(42, "test");
490 service.updateState({ value: 100 });
491 service.updateState({ value: 200 });
492
493 expect(listener).toHaveBeenCalledTimes(1);
494 });
495
496 test("should allow removing specific listeners", async () => {
497 const listener = vi.fn();
498
499 service.on("stateChanged", listener);
500 await service.initialize(42, "test");
501
502 service.updateState({ value: 100 });
503 expect(listener).toHaveBeenCalledTimes(1);
504
505 service.off("stateChanged", listener);
506 service.updateState({ value: 200 });
507 expect(listener).toHaveBeenCalledTimes(1); // Not called again
508 });
509 });
510});