/
instance-wrapper.ts
476 lines (421 loc) 路 13.4 KB
/
instance-wrapper.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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import { Logger, LoggerService, Provider, Scope, Type } from '@nestjs/common';
import { EnhancerSubtype } from '@nestjs/common/constants';
import { FactoryProvider } from '@nestjs/common/interfaces';
import { clc } from '@nestjs/common/utils/cli-colors.util';
import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util';
import {
isNil,
isString,
isUndefined,
} from '@nestjs/common/utils/shared.utils';
import { iterate } from 'iterare';
import { UuidFactory } from '../inspector/uuid-factory';
import { STATIC_CONTEXT } from './constants';
import {
isClassProvider,
isFactoryProvider,
isValueProvider,
} from './helpers/provider-classifier';
import { InstanceToken, Module } from './module';
export const INSTANCE_METADATA_SYMBOL = Symbol.for('instance_metadata:cache');
export const INSTANCE_ID_SYMBOL = Symbol.for('instance_metadata:id');
export interface HostComponentInfo {
/**
* Injection token (or class reference)
*/
token: InstanceToken;
/**
* Flag that indicates whether DI subtree is durable
*/
isTreeDurable: boolean;
}
export interface ContextId {
readonly id: number;
payload?: unknown;
getParent?(info: HostComponentInfo): ContextId;
}
export interface InstancePerContext<T> {
instance: T;
isResolved?: boolean;
isPending?: boolean;
donePromise?: Promise<unknown>;
}
export interface PropertyMetadata {
key: symbol | string;
wrapper: InstanceWrapper;
}
interface InstanceMetadataStore {
dependencies?: InstanceWrapper[];
properties?: PropertyMetadata[];
enhancers?: InstanceWrapper[];
}
export class InstanceWrapper<T = any> {
public readonly name: any;
public readonly token: InstanceToken;
public readonly async?: boolean;
public readonly host?: Module;
public readonly isAlias: boolean = false;
public readonly subtype?: EnhancerSubtype;
public scope?: Scope = Scope.DEFAULT;
public metatype: Type<T> | Function;
public inject?: FactoryProvider['inject'];
public forwardRef?: boolean;
public durable?: boolean;
public initTime?: number;
private static logger: LoggerService = new Logger(InstanceWrapper.name);
private readonly values = new WeakMap<ContextId, InstancePerContext<T>>();
private readonly [INSTANCE_METADATA_SYMBOL]: InstanceMetadataStore = {};
private readonly [INSTANCE_ID_SYMBOL]: string;
private transientMap?:
| Map<string, WeakMap<ContextId, InstancePerContext<T>>>
| undefined;
private isTreeStatic: boolean | undefined;
private isTreeDurable: boolean | undefined;
constructor(
metadata: Partial<InstanceWrapper<T>> & Partial<InstancePerContext<T>> = {},
) {
this.initialize(metadata);
this[INSTANCE_ID_SYMBOL] =
metadata[INSTANCE_ID_SYMBOL] ?? this.generateUuid();
}
get id(): string {
return this[INSTANCE_ID_SYMBOL];
}
set instance(value: T) {
this.values.set(STATIC_CONTEXT, { instance: value });
}
get instance(): T {
const instancePerContext = this.getInstanceByContextId(STATIC_CONTEXT);
return instancePerContext.instance;
}
get isNotMetatype(): boolean {
const isFactory = this.metatype && !isNil(this.inject);
return !this.metatype || isFactory;
}
get isTransient(): boolean {
return this.scope === Scope.TRANSIENT;
}
public getInstanceByContextId(
contextId: ContextId,
inquirerId?: string,
): InstancePerContext<T> {
if (this.scope === Scope.TRANSIENT && inquirerId) {
return this.getInstanceByInquirerId(contextId, inquirerId);
}
const instancePerContext = this.values.get(contextId);
return instancePerContext
? instancePerContext
: this.cloneStaticInstance(contextId);
}
public getInstanceByInquirerId(
contextId: ContextId,
inquirerId: string,
): InstancePerContext<T> {
let collectionPerContext = this.transientMap.get(inquirerId);
if (!collectionPerContext) {
collectionPerContext = new WeakMap();
this.transientMap.set(inquirerId, collectionPerContext);
}
const instancePerContext = collectionPerContext.get(contextId);
return instancePerContext
? instancePerContext
: this.cloneTransientInstance(contextId, inquirerId);
}
public setInstanceByContextId(
contextId: ContextId,
value: InstancePerContext<T>,
inquirerId?: string,
) {
if (this.scope === Scope.TRANSIENT && inquirerId) {
return this.setInstanceByInquirerId(contextId, inquirerId, value);
}
this.values.set(contextId, value);
}
public setInstanceByInquirerId(
contextId: ContextId,
inquirerId: string,
value: InstancePerContext<T>,
) {
let collection = this.transientMap.get(inquirerId);
if (!collection) {
collection = new WeakMap();
this.transientMap.set(inquirerId, collection);
}
collection.set(contextId, value);
}
public addCtorMetadata(index: number, wrapper: InstanceWrapper) {
if (!this[INSTANCE_METADATA_SYMBOL].dependencies) {
this[INSTANCE_METADATA_SYMBOL].dependencies = [];
}
this[INSTANCE_METADATA_SYMBOL].dependencies[index] = wrapper;
}
public getCtorMetadata(): InstanceWrapper[] {
return this[INSTANCE_METADATA_SYMBOL].dependencies;
}
public addPropertiesMetadata(key: symbol | string, wrapper: InstanceWrapper) {
if (!this[INSTANCE_METADATA_SYMBOL].properties) {
this[INSTANCE_METADATA_SYMBOL].properties = [];
}
this[INSTANCE_METADATA_SYMBOL].properties.push({
key,
wrapper,
});
}
public getPropertiesMetadata(): PropertyMetadata[] {
return this[INSTANCE_METADATA_SYMBOL].properties;
}
public addEnhancerMetadata(wrapper: InstanceWrapper) {
if (!this[INSTANCE_METADATA_SYMBOL].enhancers) {
this[INSTANCE_METADATA_SYMBOL].enhancers = [];
}
this[INSTANCE_METADATA_SYMBOL].enhancers.push(wrapper);
}
public getEnhancersMetadata(): InstanceWrapper[] {
return this[INSTANCE_METADATA_SYMBOL].enhancers;
}
public isDependencyTreeDurable(lookupRegistry: string[] = []): boolean {
if (!isUndefined(this.isTreeDurable)) {
return this.isTreeDurable;
}
if (this.scope === Scope.REQUEST) {
this.isTreeDurable = this.durable === undefined ? false : this.durable;
if (this.isTreeDurable) {
this.printIntrospectedAsDurable();
}
return this.isTreeDurable;
}
const isStatic = this.isDependencyTreeStatic();
if (isStatic) {
return false;
}
const isTreeNonDurable = this.introspectDepsAttribute(
(collection, registry) =>
collection.some(
(item: InstanceWrapper) =>
!item.isDependencyTreeStatic() &&
!item.isDependencyTreeDurable(registry),
),
lookupRegistry,
);
this.isTreeDurable = !isTreeNonDurable;
if (this.isTreeDurable) {
this.printIntrospectedAsDurable();
}
return this.isTreeDurable;
}
public introspectDepsAttribute(
callback: (
collection: InstanceWrapper[],
lookupRegistry: string[],
) => boolean,
lookupRegistry: string[] = [],
): boolean {
if (lookupRegistry.includes(this[INSTANCE_ID_SYMBOL])) {
return false;
}
lookupRegistry = lookupRegistry.concat(this[INSTANCE_ID_SYMBOL]);
const { dependencies, properties, enhancers } =
this[INSTANCE_METADATA_SYMBOL];
let introspectionResult = dependencies
? callback(dependencies, lookupRegistry)
: false;
if (introspectionResult || !(properties || enhancers)) {
return introspectionResult;
}
introspectionResult = properties
? callback(
properties.map(item => item.wrapper),
lookupRegistry,
)
: false;
if (introspectionResult || !enhancers) {
return introspectionResult;
}
return enhancers ? callback(enhancers, lookupRegistry) : false;
}
public isDependencyTreeStatic(lookupRegistry: string[] = []): boolean {
if (!isUndefined(this.isTreeStatic)) {
return this.isTreeStatic;
}
if (this.scope === Scope.REQUEST) {
this.isTreeStatic = false;
this.printIntrospectedAsRequestScoped();
return this.isTreeStatic;
}
this.isTreeStatic = !this.introspectDepsAttribute(
(collection, registry) =>
collection.some(
(item: InstanceWrapper) => !item.isDependencyTreeStatic(registry),
),
lookupRegistry,
);
if (!this.isTreeStatic) {
this.printIntrospectedAsRequestScoped();
}
return this.isTreeStatic;
}
public cloneStaticInstance(contextId: ContextId): InstancePerContext<T> {
const staticInstance = this.getInstanceByContextId(STATIC_CONTEXT);
if (this.isDependencyTreeStatic()) {
return staticInstance;
}
const instancePerContext: InstancePerContext<T> = {
...staticInstance,
instance: undefined,
isResolved: false,
isPending: false,
};
if (this.isNewable()) {
instancePerContext.instance = Object.create(this.metatype.prototype);
}
this.setInstanceByContextId(contextId, instancePerContext);
return instancePerContext;
}
public cloneTransientInstance(
contextId: ContextId,
inquirerId: string,
): InstancePerContext<T> {
const staticInstance = this.getInstanceByContextId(STATIC_CONTEXT);
const instancePerContext: InstancePerContext<T> = {
...staticInstance,
instance: undefined,
isResolved: false,
isPending: false,
};
if (this.isNewable()) {
instancePerContext.instance = Object.create(this.metatype.prototype);
}
this.setInstanceByInquirerId(contextId, inquirerId, instancePerContext);
return instancePerContext;
}
public createPrototype(contextId: ContextId) {
const host = this.getInstanceByContextId(contextId);
if (!this.isNewable() || host.isResolved) {
return;
}
return Object.create(this.metatype.prototype);
}
public isInRequestScope(
contextId: ContextId,
inquirer?: InstanceWrapper | undefined,
): boolean {
const isDependencyTreeStatic = this.isDependencyTreeStatic();
return (
!isDependencyTreeStatic &&
contextId !== STATIC_CONTEXT &&
(!this.isTransient || (this.isTransient && !!inquirer))
);
}
public isLazyTransient(
contextId: ContextId,
inquirer: InstanceWrapper | undefined,
): boolean {
const isInquirerRequestScoped =
inquirer && !inquirer.isDependencyTreeStatic();
return (
this.isDependencyTreeStatic() &&
contextId !== STATIC_CONTEXT &&
this.isTransient &&
isInquirerRequestScoped
);
}
public isExplicitlyRequested(
contextId: ContextId,
inquirer?: InstanceWrapper,
): boolean {
const isSelfRequested = inquirer === this;
return (
this.isDependencyTreeStatic() &&
contextId !== STATIC_CONTEXT &&
(isSelfRequested || (inquirer && inquirer.scope === Scope.TRANSIENT))
);
}
public isStatic(
contextId: ContextId,
inquirer: InstanceWrapper | undefined,
): boolean {
const isInquirerRequestScoped =
inquirer && !inquirer.isDependencyTreeStatic();
const isStaticTransient = this.isTransient && !isInquirerRequestScoped;
return (
this.isDependencyTreeStatic() &&
contextId === STATIC_CONTEXT &&
(!this.isTransient ||
(isStaticTransient && !!inquirer && !inquirer.isTransient))
);
}
public getStaticTransientInstances() {
if (!this.transientMap) {
return [];
}
const instances = [...this.transientMap.values()];
return iterate(instances)
.map(item => item.get(STATIC_CONTEXT))
.filter(item => !!item)
.toArray();
}
public mergeWith(provider: Provider) {
if (isValueProvider(provider)) {
this.metatype = null;
this.inject = null;
this.scope = Scope.DEFAULT;
this.setInstanceByContextId(STATIC_CONTEXT, {
instance: provider.useValue,
isResolved: true,
isPending: false,
});
} else if (isClassProvider(provider)) {
this.inject = null;
this.metatype = provider.useClass;
} else if (isFactoryProvider(provider)) {
this.metatype = provider.useFactory;
this.inject = provider.inject || [];
}
}
private isNewable(): boolean {
return isNil(this.inject) && this.metatype && this.metatype.prototype;
}
private initialize(
metadata: Partial<InstanceWrapper<T>> & Partial<InstancePerContext<T>>,
) {
const { instance, isResolved, ...wrapperPartial } = metadata;
Object.assign(this, wrapperPartial);
this.setInstanceByContextId(STATIC_CONTEXT, {
instance,
isResolved,
});
this.scope === Scope.TRANSIENT && (this.transientMap = new Map());
}
private printIntrospectedAsRequestScoped() {
if (!this.isDebugMode() || this.name === 'REQUEST') {
return;
}
if (isString(this.name)) {
InstanceWrapper.logger.log(
`${clc.cyanBright(this.name)}${clc.green(
' introspected as ',
)}${clc.magentaBright('request-scoped')}`,
);
}
}
private printIntrospectedAsDurable() {
if (!this.isDebugMode()) {
return;
}
if (isString(this.name)) {
InstanceWrapper.logger.log(
`${clc.cyanBright(this.name)}${clc.green(
' introspected as ',
)}${clc.magentaBright('durable')}`,
);
}
}
private isDebugMode(): boolean {
return !!process.env.NEST_DEBUG;
}
private generateUuid(): string {
let key = this.name?.toString() ?? this.token?.toString();
key += this.host?.name ?? '';
return key ? UuidFactory.get(key) : randomStringGenerator();
}
}