| 1 | import { EventEmitter } from "events"; |
| 2 | |
| 3 | import { logger } from "../util/logger.js"; |
| 4 | |
| 5 | import { ServiceResult, ServiceState } from "./types.js"; |
| 6 | |
| 7 | /** |
| 8 | * Central service container that manages service lifecycle and dependencies |
| 9 | * Uses EventEmitter for reactive updates across the application |
| 10 | */ |
| 11 | export class ServiceContainer extends EventEmitter { |
| 12 | private services = new Map<string, ServiceResult<any>>(); |
| 13 | private factories = new Map<string, () => Promise<any>>(); |
| 14 | private dependencies = new Map<string, string[]>(); |
| 15 | |
| 16 | constructor() { |
| 17 | super(); |
| 18 | // Increase max listeners to handle multiple UI components |
| 19 | this.setMaxListeners(50); |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * Register a service factory with optional dependencies |
| 24 | */ |
| 25 | register<T>( |
| 26 | serviceName: string, |
| 27 | factory: () => Promise<T>, |
| 28 | deps: string[] = [], |
| 29 | ): void { |
| 30 | this.factories.set(serviceName, factory); |
| 31 | this.dependencies.set(serviceName, deps); |
| 32 | |
| 33 | // Only initialize with idle state if the service doesn't already exist |
| 34 | // This prevents overwriting services that were registered with registerValue |
| 35 | if (!this.services.has(serviceName)) { |
| 36 | this.services.set(serviceName, { |
| 37 | value: null, |
| 38 | state: "idle", |
| 39 | error: null, |
| 40 | }); |
| 41 | } |
| 42 | |
| 43 | logger.debug(`Registered service: ${serviceName}`, { dependencies: deps }); |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Register a service with an immediate value (no factory needed) |
| 48 | * Used when the service is already initialized |
| 49 | */ |
| 50 | registerValue<T>(serviceName: string, value: T): void { |
| 51 | // Set the service as ready with the provided value |
| 52 | this.services.set(serviceName, { |
| 53 | value, |
| 54 | state: "ready", |
| 55 | error: null, |
| 56 | lastUpdated: new Date(), |
| 57 | }); |
| 58 | |
| 59 | // Emit ready event |
| 60 | this.emit(`${serviceName}:ready`, value); |
| 61 | |
| 62 | logger.debug(`Registered service with immediate value: ${serviceName}`, { |
| 63 | state: "ready", |
| 64 | hasValue: value !== null, |
| 65 | serviceMapSize: this.services.size, |
| 66 | }); |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * Get current service result (synchronous) |
| 71 | */ |
| 72 | getSync<T>(serviceName: string): ServiceResult<T> { |
| 73 | const result = this.services.get(serviceName); |
| 74 | if (!result) { |
| 75 | logger.warn(`Service not found: ${serviceName}`); |
| 76 | return { |
| 77 | value: null, |
| 78 | state: "error", |
| 79 | error: new Error(`Service '${serviceName}' not registered`), |
| 80 | }; |
| 81 | } |
| 82 | return result; |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Get service value, loading if necessary (async) |
| 87 | */ |
| 88 | async get<T>(serviceName: string): Promise<T> { |
| 89 | const current = this.getSync<T>(serviceName); |
| 90 | |
| 91 | if (current.state === "ready" && current.value !== null) { |
| 92 | return current.value; |
| 93 | } |
| 94 | |
| 95 | if (current.state === "loading") { |
| 96 | // Wait for loading to complete |
| 97 | return new Promise((resolve, reject) => { |
| 98 | const onReady = (value: T) => { |
| 99 | this.off(`${serviceName}:ready`, onReady); |
| 100 | this.off(`${serviceName}:error`, onError); |
| 101 | resolve(value); |
| 102 | }; |
| 103 | |
| 104 | const onError = (error: Error) => { |
| 105 | this.off(`${serviceName}:ready`, onReady); |
| 106 | this.off(`${serviceName}:error`, onError); |
| 107 | reject(error); |
| 108 | }; |
| 109 | |
| 110 | this.once(`${serviceName}:ready`, onReady); |
| 111 | this.once(`${serviceName}:error`, onError); |
| 112 | }); |
| 113 | } |
| 114 | |
| 115 | // Need to load |
| 116 | return this.load<T>(serviceName); |
| 117 | } |
| 118 | |
| 119 | /** |
| 120 | * Load a service, handling dependencies |
| 121 | */ |
| 122 | async load<T>(serviceName: string): Promise<T> { |
| 123 | const factory = this.factories.get(serviceName); |
| 124 | if (!factory) { |
| 125 | const error = new Error( |
| 126 | `No factory registered for service '${serviceName}'`, |
| 127 | ); |
| 128 | this.setServiceError(serviceName, error); |
| 129 | throw error; |
| 130 | } |
| 131 | |
| 132 | // Check if already loading |
| 133 | const current = this.services.get(serviceName); |
| 134 | if (current?.state === "loading") { |
| 135 | return this.get<T>(serviceName); |
| 136 | } |
| 137 | |
| 138 | logger.debug(`Loading service: ${serviceName}`); |
| 139 | this.setServiceState(serviceName, "loading"); |
| 140 | |
| 141 | try { |
| 142 | // Load dependencies first |
| 143 | const deps = this.dependencies.get(serviceName) || []; |
| 144 | await Promise.all(deps.map((dep) => this.load(dep))); |
| 145 | |
| 146 | // Load the service |
| 147 | const value = await factory(); |
| 148 | |
| 149 | this.setServiceValue(serviceName, value); |
| 150 | logger.debug(`Service loaded successfully: ${serviceName}`); |
| 151 | |
| 152 | return value; |
| 153 | } catch (error: any) { |
| 154 | logger.debug(`Failed to load service '${serviceName}':`, error); |
| 155 | this.setServiceError(serviceName, error); |
| 156 | throw error; |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /** |
| 161 | * Reload a service (and all transitive dependents) |
| 162 | */ |
| 163 | async reload<T>(serviceName: string): Promise<T> { |
| 164 | logger.debug(`Reloading service: ${serviceName}`); |
| 165 | |
| 166 | // Find all services that depend on this one (recursively) |
| 167 | const dependents = this.findAllDependents(serviceName); |
| 168 | |
| 169 | logger.debug(`Found dependents for ${serviceName}:`, dependents); |
| 170 | |
| 171 | // Reset this service and all dependents to ensure fresh reload |
| 172 | this.resetService(serviceName); |
| 173 | dependents.forEach((dep) => this.resetService(dep)); |
| 174 | |
| 175 | // Now reload ALL services that were reset, starting with the root service |
| 176 | // This ensures proper dependency order and that all dependents get reloaded |
| 177 | const allToReload = [serviceName, ...dependents]; |
| 178 | |
| 179 | // Reset ALL services first to ensure clean state |
| 180 | allToReload.forEach((name) => this.resetService(name)); |
| 181 | |
| 182 | // Load all services in dependency order - starting with the root service |
| 183 | // will naturally load its dependents when they're requested |
| 184 | const results = await Promise.all( |
| 185 | allToReload.map((name) => this.load(name)), |
| 186 | ); |
| 187 | |
| 188 | // Return the value of the primary service that was reloaded |
| 189 | return results[0] as T; |
| 190 | } |
| 191 | |
| 192 | /** |
| 193 | * Find all services that transitively depend on the given service |
| 194 | */ |
| 195 | private findAllDependents(serviceName: string): string[] { |
| 196 | const result = new Set<string>(); |
| 197 | const visited = new Set<string>(); |
| 198 | |
| 199 | const findDeps = (name: string) => { |
| 200 | if (visited.has(name)) return; |
| 201 | visited.add(name); |
| 202 | |
| 203 | // Find direct dependents |
| 204 | const directDependents = Array.from(this.dependencies.entries()) |
| 205 | .filter(([_, deps]) => deps.includes(name)) |
| 206 | .map(([depName, _]) => depName); |
| 207 | |
| 208 | for (const dependent of directDependents) { |
| 209 | result.add(dependent); |
| 210 | findDeps(dependent); // Recurse for transitive dependencies |
| 211 | } |
| 212 | }; |
| 213 | |
| 214 | findDeps(serviceName); |
| 215 | return Array.from(result); |
| 216 | } |
| 217 | |
| 218 | /** |
| 219 | * Manually set a service value (for testing or external updates) |
| 220 | */ |
| 221 | set<T>(serviceName: string, value: T): void { |
| 222 | this.setServiceValue(serviceName, value); |
| 223 | } |
| 224 | |
| 225 | /** |
| 226 | * Check if service is ready |
| 227 | */ |
| 228 | isReady(serviceName: string): boolean { |
| 229 | const result = this.services.get(serviceName); |
| 230 | return result?.state === "ready" && result.value !== null; |
| 231 | } |
| 232 | |
| 233 | /** |
| 234 | * Check if service is loading |
| 235 | */ |
| 236 | isLoading(serviceName: string): boolean { |
| 237 | const result = this.services.get(serviceName); |
| 238 | return result?.state === "loading"; |
| 239 | } |
| 240 | |
| 241 | /** |
| 242 | * Initialize all registered services |
| 243 | * This eagerly loads all services rather than waiting for them to be requested |
| 244 | */ |
| 245 | async initializeAll(): Promise<void> { |
| 246 | logger.debug("Initializing all registered services"); |
| 247 | |
| 248 | // Get all registered service names |
| 249 | const serviceNames = Array.from(this.factories.keys()); |
| 250 | |
| 251 | // Load all services in parallel (dependencies will be handled by load()) |
| 252 | await Promise.all( |
| 253 | serviceNames.map((name) => |
| 254 | this.load(name).catch((error) => { |
| 255 | logger.debug(`Failed to initialize service ${name}:`, error); |
| 256 | // Don't throw - let individual services fail without breaking others |
| 257 | }), |
| 258 | ), |
| 259 | ); |
| 260 | |
| 261 | logger.debug( |
| 262 | "All services initialization complete", |
| 263 | this.getServiceStates(), |
| 264 | ); |
| 265 | } |
| 266 | |
| 267 | /** |
| 268 | * Get all service states (for debugging) |
| 269 | */ |
| 270 | getServiceStates(): Record<string, ServiceState> { |
| 271 | const states: Record<string, ServiceState> = {}; |
| 272 | for (const [name, result] of this.services) { |
| 273 | states[name] = result.state; |
| 274 | } |
| 275 | return states; |
| 276 | } |
| 277 | |
| 278 | /** |
| 279 | * Private helper methods |
| 280 | */ |
| 281 | private setServiceState(serviceName: string, state: ServiceState): void { |
| 282 | const current = this.services.get(serviceName) || { |
| 283 | value: null, |
| 284 | state: "idle", |
| 285 | error: null, |
| 286 | }; |
| 287 | const updated = { ...current, state, lastUpdated: new Date() }; |
| 288 | this.services.set(serviceName, updated); |
| 289 | this.emit(`${serviceName}:${state}`); |
| 290 | } |
| 291 | |
| 292 | private setServiceValue<T>(serviceName: string, value: T): void { |
| 293 | const result: ServiceResult<T> = { |
| 294 | value, |
| 295 | state: "ready", |
| 296 | error: null, |
| 297 | lastUpdated: new Date(), |
| 298 | }; |
| 299 | |
| 300 | this.services.set(serviceName, result); |
| 301 | this.emit(`${serviceName}:ready`, value); |
| 302 | this.emit(`${serviceName}:changed`, value); |
| 303 | } |
| 304 | |
| 305 | private setServiceError(serviceName: string, error: Error): void { |
| 306 | const result: ServiceResult<any> = { |
| 307 | value: null, |
| 308 | state: "error", |
| 309 | error, |
| 310 | lastUpdated: new Date(), |
| 311 | }; |
| 312 | |
| 313 | this.services.set(serviceName, result); |
| 314 | this.emit(`${serviceName}:error`, error); |
| 315 | } |
| 316 | |
| 317 | private resetService(serviceName: string): void { |
| 318 | const result: ServiceResult<any> = { |
| 319 | value: null, |
| 320 | state: "idle", |
| 321 | error: null, |
| 322 | }; |
| 323 | |
| 324 | this.services.set(serviceName, result); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | // Global singleton instance |
| 329 | export const serviceContainer = new ServiceContainer(); |