-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathdependency_container.ts
259 lines (228 loc) · 9.16 KB
/
dependency_container.ts
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
// Copyright 2020 Liam Tan. All rights reserved. MIT license.
import { Newable, EInjectionScope, DependencyDefinition, RequestLifetime } from "./types.ts";
import { v4 } from "./deps.ts";
import { getConstructorTypes } from "./metadata.ts";
// TODO there is potentially a bug here. I think that
// Transient services aren't being created every time
// they are created definitely every time a resolution
// is called on the container or lifetime, but if the
// same transient is required in the one resolution
// tree, it will be the same instance.
// TODO another bug is that errors will be thrown
// on request, not on startup (unless the dep is
// singleton). This will be a poor user
// experience
/**
* `DependencyContainer`, used to register and resolve injected dependencies
*/
export class DependencyContainer {
/** Definitions */
#serviceDefinitions: Map<string, DependencyDefinition>;
/** Cached instances of dependencies */
#singletonCache: Map<string, any>;
#requestCache: Map<string, Map<string, any>>;
constructor() {
this.#serviceDefinitions = new Map<string, DependencyDefinition>();
this.#singletonCache = new Map<string, any>();
this.#requestCache = new Map<string, Map<string, any>>();
}
/**
* `register` function will register an instance inside the `DependencyContainer`.
* An optional key can be provided to specify the retrieval key when resolving
* using the `@Inject()` decorator, but this will default to use the implicit
* type name.
*/
register(newable: Newable<any>, scope: EInjectionScope, key: string) {
this.#serviceDefinitions.set(key, {
scope,
newable,
});
}
/**
* Request new lifetime. This will scope all REQUEST scoped services
* To it's own "container". You call resolve directly off this m3ethod
*/
newRequestLifetime(): RequestLifetime {
const requestId: string = v4.generate();
return (() => {
this.#requestCache.set(requestId, new Map<string, any>());
return {
requestId,
resolve: (key: string): any | null => this.resolve(key, requestId),
end: (): void => this.endRequestLifetime(requestId),
};
})();
}
endRequestLifetime(requestId: string) {
this.#requestCache.get(requestId)?.clear();
this.#requestCache.delete(requestId);
}
/**
* Helper method: scope cannot decrease in size in the dependency tree.
* As an example, Singleton -> Request is an invalid dependency
* relationship as Singleton services are only instanciated
* once.
*
* Only transient services can depend on transient services. Transient
* services are instantiated every time they are resolved, so a
* singleton or request service cannot be cached if they
* depend on transient.
*
* This method checks that the child deps of a parent are not smaller
* in scope.
*/
#childHasSmallerScope = (
parentScope: EInjectionScope,
children: Array<DependencyDefinition>
): boolean => {
const sizeArray: Array<EInjectionScope> = [
EInjectionScope.TRANSIENT,
EInjectionScope.REQUEST,
EInjectionScope.SINGLETON,
];
for (const child of children) {
if (sizeArray.indexOf(child.scope) < sizeArray.indexOf(parentScope)) {
return true;
}
}
return false;
};
/**
* Root resolution function.
*
* Builds a queue of `DependencyDefinitions` in the order they must be resolved.
* Accepts requestId, for request scoped dependencies.
*/
resolve<T>(key: string, requestId?: string | undefined): T | null {
const resolutionQueue: Array<DependencyDefinition> = [];
const rootServiceDefinition: DependencyDefinition | undefined = this.#serviceDefinitions.get(
key
);
let ptr = 0;
/**
* Internal helper function to select correct cache. Will throw error if cache
* lookup is request scoped, but no request id has been supplied.
*/
const _selectCacheFromScope = (scope: EInjectionScope, requestId?: string): any => {
switch (scope) {
case EInjectionScope.SINGLETON:
return this.#singletonCache;
case EInjectionScope.REQUEST:
if (!requestId) {
throw new Error(`
Attempted to resolve REQUEST scoped dependency outside of RequestLifetime.
REQUEST scoped dependencies may only be resolved by calling
DependencyContainer.newRequestLifetime().resolve("key");
`);
}
return this.#requestCache.get(requestId);
}
};
/**
* Internal process queue function
*/
const _processQueue = (): any => {
let instance: any;
// Cache transient local dependencies here. They are not cached
// in the container so we do this here instead.
const transientLocalCache: Map<string, any> = new Map<string, any>();
while (resolutionQueue.length) {
const dep: DependencyDefinition = <DependencyDefinition>resolutionQueue.pop();
const parentScope: EInjectionScope = dep.scope;
const parentKey: string = dep.newable.name;
const parentCache: Map<string, any> | undefined = _selectCacheFromScope(
parentScope,
requestId
);
// If cached, no need to resolve it's children. Skip this dependency and move
// onto the next dependency.
if (parentCache?.has(parentKey)) continue;
// Get children dependencies here. If any decrease in scope (Request -> Transient)
// then throw an error
const childDepDefinitions: Array<DependencyDefinition> = (
getConstructorTypes(dep.newable) ?? []
).map(
({ name }: { name: string }): DependencyDefinition =>
<DependencyDefinition>this.#serviceDefinitions.get(name)
);
if (this.#childHasSmallerScope(parentScope, childDepDefinitions)) {
throw new Error(
`Parent dependency "${parentKey}" depends on children with smaller scope (${childDepDefinitions.map(
(c) => c.newable.name
)}). Scope can only increase in size in your tree (Transient -> Request -> Singleton).`
);
}
const resolvedChildren: Array<any> = [];
// Queue is read backwards, so any parent with child dependencies
// will get them from cache
for (const childDepDefinition of childDepDefinitions) {
const childScope: EInjectionScope = childDepDefinition.scope;
const childKey: string = childDepDefinition.newable.name;
// If this dep is transient, it's deps will can be transient, singleton
// or request. In this case, the child is transient, so look for the
// local transient cache for the instance.
if (childScope === EInjectionScope.TRANSIENT) {
resolvedChildren.push(transientLocalCache.get(childKey));
continue;
}
const childCache: Map<string, any> | undefined = _selectCacheFromScope(
childScope,
requestId
);
resolvedChildren.push(childCache?.get(childKey));
}
instance = new dep.newable(...resolvedChildren);
// Skip container cache on transient.
if (parentScope === EInjectionScope.TRANSIENT) {
transientLocalCache.set(parentKey, instance);
continue;
}
parentCache?.set(parentKey, instance);
}
return instance;
};
const _resolve = (serviceDefinition: DependencyDefinition | undefined): any => {
if (!serviceDefinition) {
throw new Error("A non registered dependency was attempted to be resolved.");
}
// Maximum resolution size. This is a bandaid solution
// and a proper circular dependency solution needs to
// be implemented
if (ptr >= 512) {
throw new Error(
`Circular dependency detected, origin of key: ${serviceDefinition.newable.name}`
);
}
if (serviceDefinition === rootServiceDefinition) {
resolutionQueue.push(serviceDefinition);
}
const childDeps: Array<Function> = getConstructorTypes(serviceDefinition.newable) ?? [];
const childDefinitions: Array<DependencyDefinition> = childDeps.map(
({ name }: { name: string }) => <DependencyDefinition>this.#serviceDefinitions.get(name)
);
// TODO check for null here i.e. non registered service
// We grabbed this straight fgrom constructor, what if
// one arg is not wanting to be injected?
resolutionQueue.push(...childDefinitions);
ptr++;
if (ptr === resolutionQueue.length) {
return _processQueue();
}
return _resolve(resolutionQueue[ptr]);
};
if (!rootServiceDefinition) return null;
const cache: Map<string, any> = _selectCacheFromScope(rootServiceDefinition.scope, requestId);
return cache?.get(key) ?? _resolve(rootServiceDefinition);
}
instantiateAllSingletons() {
for (const [key, definition] of this.#serviceDefinitions.entries()) {
if (definition.scope === EInjectionScope.SINGLETON) {
this.resolve<any>(key);
}
}
}
}
// Freeze and export as singleton
const containerSingleton: DependencyContainer = new DependencyContainer();
Object.freeze(containerSingleton);
export default containerSingleton;