Elffuss BraidHub

kikocis/continue public

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