-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlifecycle.ts
More file actions
287 lines (254 loc) · 8.01 KB
/
lifecycle.ts
File metadata and controls
287 lines (254 loc) · 8.01 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
import type { Lifecycle, Token } from "../types/index.js";
import { Lifetime } from "../types/index.js";
/**
* Time-to-live for failed token tracking (5 seconds)
*/
const FAILED_TOKEN_TTL = 5000;
/**
* Lifecycle manager handles service instance creation and disposal
*/
export class LifecycleManager {
private readonly singletons = new Map<Token, any>();
private readonly scopedInstances = new Map<Token, any>();
private readonly disposables: Lifecycle[] = [];
private readonly pendingAsync = new Map<Token, Promise<any>>();
private readonly failedTokens = new Map<Token, { error: Error; timestamp: number }>();
/**
* Get or create a singleton instance
*/
getSingleton<T>(token: Token<T>, factory: () => T): T {
let instance = this.singletons.get(token);
if (instance === undefined) {
instance = factory();
this.singletons.set(token, instance);
this.trackDisposable(instance);
}
return instance;
}
/**
* Get or create a scoped instance
*/
getScoped<T>(token: Token<T>, factory: () => T): T {
let instance = this.scopedInstances.get(token);
if (instance === undefined) {
instance = factory();
this.scopedInstances.set(token, instance);
this.trackDisposable(instance);
}
return instance;
}
/**
* Get or create an async singleton instance
*/
async getSingletonAsync<T>(token: Token<T>, factory: () => Promise<T>): Promise<T> {
let instance = this.singletons.get(token);
if (instance !== undefined) {
return instance;
}
// Check for recently failed resolutions (with TTL)
const failed = this.failedTokens.get(token);
if (failed && Date.now() - failed.timestamp < FAILED_TOKEN_TTL) {
throw failed.error;
}
// Clean up expired failures to prevent unbounded growth
this.cleanupExpiredFailures();
// Check for pending async resolution
const pending = this.pendingAsync.get(token);
if (pending) {
return pending;
}
// Create promise and cache it
const promise = (async () => {
try {
const inst = await factory();
this.singletons.set(token, inst);
this.trackDisposable(inst);
// Clean up pending and failed maps
this.failedTokens.delete(token);
return inst;
} catch (error) {
// Track failure with timestamp for TTL
this.failedTokens.set(token, { error: error as Error, timestamp: Date.now() });
throw error;
} finally {
this.pendingAsync.delete(token);
}
})();
this.pendingAsync.set(token, promise);
return promise;
}
/**
* Get or create an async scoped instance
*/
async getScopedAsync<T>(token: Token<T>, factory: () => Promise<T>): Promise<T> {
let instance = this.scopedInstances.get(token);
if (instance !== undefined) {
return instance;
}
// Check for recently failed resolutions (with TTL)
const failed = this.failedTokens.get(token);
if (failed && Date.now() - failed.timestamp < FAILED_TOKEN_TTL) {
throw failed.error;
}
// Clean up expired failures to prevent unbounded growth
this.cleanupExpiredFailures();
// Check for pending async resolution
const pending = this.pendingAsync.get(token);
if (pending) {
return pending;
}
// Create promise and cache it
const promise = (async () => {
try {
const inst = await factory();
this.scopedInstances.set(token, inst);
this.trackDisposable(inst);
// Clean up pending and failed maps
this.failedTokens.delete(token);
return inst;
} catch (error) {
// Track failure with timestamp for TTL
this.failedTokens.set(token, { error: error as Error, timestamp: Date.now() });
throw error;
} finally {
this.pendingAsync.delete(token);
}
})();
this.pendingAsync.set(token, promise);
return promise;
}
/**
* Create a transient instance (always new)
*/
getTransient<T>(factory: () => T): T {
const instance = factory();
// Transient instances are not cached, but we still track for disposal
this.trackDisposable(instance);
return instance;
}
/**
* Create a transient instance asynchronously
*/
async getTransientAsync<T>(factory: () => Promise<T>): Promise<T> {
const instance = await factory();
// Transient instances are not cached, but we still track for disposal
this.trackDisposable(instance);
return instance;
}
/**
* Apply lifecycle based on lifetime type
*/
applyLifetime<T>(lifetime: Lifetime, token: Token<T>, factory: () => T): T {
switch (lifetime) {
case Lifetime.Singleton:
return this.getSingleton(token, factory);
case Lifetime.Scoped:
return this.getScoped(token, factory);
case Lifetime.Transient:
default:
return this.getTransient(factory);
}
}
/**
* Apply lifecycle based on lifetime type (async)
*/
async applyLifetimeAsync<T>(lifetime: Lifetime, token: Token<T>, factory: () => Promise<T>): Promise<T> {
switch (lifetime) {
case Lifetime.Singleton:
return this.getSingletonAsync(token, factory);
case Lifetime.Scoped:
return this.getScopedAsync(token, factory);
case Lifetime.Transient:
default:
return this.getTransientAsync(factory);
}
}
/**
* Track an instance for disposal if it implements Lifecycle
*/
private trackDisposable(instance: any): void {
if (this.hasLifecycleHooks(instance)) {
this.disposables.push(instance);
// Call onInit hook if available
if (instance.onInit) {
const result = instance.onInit();
// If onInit returns a promise, we should handle it
if (result instanceof Promise) {
result.catch(() => {
// Error in onInit hook - logged but not thrown
});
}
}
}
}
/**
* Check if an instance implements Lifecycle interface
*/
private hasLifecycleHooks(instance: any): instance is Lifecycle {
return (
instance &&
typeof instance === "object" &&
(typeof instance.onInit === "function" || typeof instance.onDispose === "function")
);
}
/**
* Dispose of all tracked instances
*/
async dispose(): Promise<void> {
const disposePromises: Promise<void>[] = [];
// Call onDispose on all tracked instances in reverse order
for (let i = this.disposables.length - 1; i >= 0; i--) {
const instance = this.disposables[i];
if (instance?.onDispose) {
try {
const result = instance.onDispose();
if (result instanceof Promise) {
disposePromises.push(result);
}
} catch (error) {
// Log error but continue disposing other instances
}
}
}
await Promise.all(disposePromises);
// Clear all caches
this.singletons.clear();
this.scopedInstances.clear();
this.pendingAsync.clear();
this.failedTokens.clear();
this.disposables.length = 0;
}
/**
* Clear scoped instances only (for creating child scopes)
*/
clearScoped(): void {
this.scopedInstances.clear();
// Note: Don't clear failedTokens for singletons as they persist across scopes
}
/**
* Clean up expired failed token entries to prevent unbounded growth
*/
private cleanupExpiredFailures(): void {
const now = Date.now();
for (const [token, { timestamp }] of this.failedTokens.entries()) {
if (now - timestamp >= FAILED_TOKEN_TTL) {
this.failedTokens.delete(token);
}
}
}
/**
* Create a child lifecycle manager with inherited singletons
*/
createChild(): LifecycleManager {
const child = new LifecycleManager();
// Share singleton references with child (but not scoped instances)
for (const [token, instance] of this.singletons.entries()) {
child.singletons.set(token, instance);
}
// Share pending async singletons
for (const [token, promise] of this.pendingAsync.entries()) {
child.pendingAsync.set(token, promise);
}
return child;
}
}