Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions integration/scopes/e2e/transient-scope.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { INestApplication, Injectable, Scope } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { expect } from 'chai';
import * as request from 'supertest';
import { NestedTransientModule } from '../src/nested-transient/nested-transient.module';
import { Guard } from '../src/transient/guards/request-scoped.guard';
import { HelloController } from '../src/transient/hello.controller';
import { HelloModule } from '../src/transient/hello.module';
Expand Down Expand Up @@ -139,4 +140,53 @@ describe('Transient scope', () => {
await app.close();
});
});

describe('when nested transient providers are used in request scope', () => {
let server: any;
let app: INestApplication;

before(async () => {
const module = await Test.createTestingModule({
imports: [NestedTransientModule],
}).compile();

app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});

describe('when handling HTTP requests', () => {
let response: any;

before(async () => {
const performHttpCall = () =>
new Promise<any>((resolve, reject) => {
request(server)
.get('/nested-transient')
.end((err, res) => {
if (err) return reject(err);
resolve(res);
});
});

response = await performHttpCall();
});

it('should isolate nested transient instances for each parent service', () => {
expect(response.body.firstServiceContext).to.equal(
'NESTED-FirstService',
);
expect(response.body.secondServiceContext).to.equal(
'NESTED-SecondService',
);
expect(response.body.firstServiceNestedId).to.not.equal(
response.body.secondServiceNestedId,
);
});
});

after(async () => {
await app.close();
});
});
});
12 changes: 12 additions & 0 deletions integration/scopes/src/nested-transient/first-request.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Injectable, Scope } from '@nestjs/common';
import { TransientLoggerService } from './transient-logger.service';

@Injectable({ scope: Scope.REQUEST })
export class FirstRequestService {
static COUNTER = 0;

constructor(public readonly logger: TransientLoggerService) {
FirstRequestService.COUNTER++;
this.logger.setContext('FirstService');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Controller, Get, Scope } from '@nestjs/common';
import { FirstRequestService } from './first-request.service';
import { SecondRequestService } from './second-request.service';

@Controller({ path: 'nested-transient', scope: Scope.REQUEST })
export class NestedTransientController {
static COUNTER = 0;

constructor(
private readonly firstService: FirstRequestService,
private readonly secondService: SecondRequestService,
) {
NestedTransientController.COUNTER++;
}

@Get()
getIsolationData() {
return {
firstServiceContext: this.firstService.logger.getNestedContext(),
firstServiceNestedId: this.firstService.logger.getNestedInstanceId(),
secondServiceContext: this.secondService.logger.getNestedContext(),
secondServiceNestedId: this.secondService.logger.getNestedInstanceId(),
};
}
}
17 changes: 17 additions & 0 deletions integration/scopes/src/nested-transient/nested-transient.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { NestedTransientController } from './nested-transient.controller';
import { FirstRequestService } from './first-request.service';
import { SecondRequestService } from './second-request.service';
import { TransientLoggerService } from './transient-logger.service';
import { NestedTransientService } from './nested-transient.service';

@Module({
controllers: [NestedTransientController],
providers: [
FirstRequestService,
SecondRequestService,
TransientLoggerService,
NestedTransientService,
],
})
export class NestedTransientModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.TRANSIENT })
export class NestedTransientService {
static COUNTER = 0;
public readonly instanceId: number;
private context?: string;

constructor() {
NestedTransientService.COUNTER++;
this.instanceId = NestedTransientService.COUNTER;
}

setContext(ctx: string) {
this.context = ctx;
}

getContext(): string | undefined {
return this.context;
}
}
12 changes: 12 additions & 0 deletions integration/scopes/src/nested-transient/second-request.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Injectable, Scope } from '@nestjs/common';
import { TransientLoggerService } from './transient-logger.service';

@Injectable({ scope: Scope.REQUEST })
export class SecondRequestService {
static COUNTER = 0;

constructor(public readonly logger: TransientLoggerService) {
SecondRequestService.COUNTER++;
this.logger.setContext('SecondService');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Injectable, Scope } from '@nestjs/common';
import { NestedTransientService } from './nested-transient.service';

@Injectable({ scope: Scope.TRANSIENT })
export class TransientLoggerService {
static COUNTER = 0;
public readonly instanceId: number;

constructor(public readonly nested: NestedTransientService) {
TransientLoggerService.COUNTER++;
this.instanceId = TransientLoggerService.COUNTER;
}

setContext(ctx: string) {
this.nested.setContext(`NESTED-${ctx}`);
}

getNestedContext(): string | undefined {
return this.nested.getContext();
}

getNestedInstanceId(): number {
return this.nested.instanceId;
}
}
72 changes: 57 additions & 15 deletions packages/core/injector/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,6 @@ export class Injector {
inquirer?: InstanceWrapper,
parentInquirer?: InstanceWrapper,
) {
const inquirerId = this.getInquirerId(inquirer);
const metadata = wrapper.getCtorMetadata();

if (metadata && contextId !== STATIC_CONTEXT) {
Expand Down Expand Up @@ -349,15 +348,21 @@ export class Injector {
*/
await paramBarrier.signalAndWait();

const effectiveInquirer = this.getEffectiveInquirer(
paramWrapper,
inquirer,
parentInquirer,
contextId,
);
const paramWrapperWithInstance = await this.resolveComponentHost(
moduleRef,
paramWrapper,
contextId,
inquirer,
effectiveInquirer,
);
const instanceHost = paramWrapperWithInstance.getInstanceByContextId(
this.getContextId(contextId, paramWrapperWithInstance),
inquirerId,
this.getInquirerId(effectiveInquirer),
);
if (!instanceHost.isResolved && !paramWrapperWithInstance.forwardRef) {
isResolved = false;
Expand Down Expand Up @@ -742,19 +747,24 @@ export class Injector {
*/
await propertyBarrier.signalAndWait();

const effectivePropertyInquirer = this.getEffectiveInquirer(
paramWrapper,
inquirer,
parentInquirer,
contextId,
);
const paramWrapperWithInstance = await this.resolveComponentHost(
moduleRef,
paramWrapper,
contextId,
inquirer,
effectivePropertyInquirer,
);
if (!paramWrapperWithInstance) {
return undefined;
}
const inquirerId = this.getInquirerId(inquirer);
const instanceHost = paramWrapperWithInstance.getInstanceByContextId(
this.getContextId(contextId, paramWrapperWithInstance),
inquirerId,
this.getInquirerId(effectivePropertyInquirer),
);
return instanceHost.instance;
} catch (err) {
Expand Down Expand Up @@ -904,14 +914,20 @@ export class Injector {
),
),
);
const inquirerId = this.getInquirerId(inquirer);
return hosts.map(
item =>
item?.getInstanceByContextId(
this.getContextId(contextId, item),
inquirerId,
).instance,
);
return hosts.map((item, index) => {
const dependency = metadata[index];
const effectiveInquirer = this.getEffectiveInquirer(
dependency,
inquirer,
parentInquirer,
contextId,
);

return item?.getInstanceByContextId(
this.getContextId(contextId, item),
this.getInquirerId(effectiveInquirer),
).instance;
});
}

public async loadPropertiesMetadata(
Expand Down Expand Up @@ -947,6 +963,27 @@ export class Injector {
return inquirer ? inquirer.id : undefined;
}

/**
* For nested TRANSIENT dependencies (TRANSIENT -> TRANSIENT) in non-static contexts,
* returns parentInquirer to ensure each parent TRANSIENT gets its own instance.
* This is necessary because in REQUEST/DURABLE scopes, the same TRANSIENT wrapper
* can be used by multiple parents, causing nested TRANSIENTs to be shared incorrectly.
* For non-TRANSIENT -> TRANSIENT, returns inquirer (current wrapper being created).
*/
private getEffectiveInquirer(
dependency: InstanceWrapper | undefined,
inquirer: InstanceWrapper | undefined,
parentInquirer: InstanceWrapper | undefined,
contextId: ContextId,
): InstanceWrapper | undefined {
return dependency?.isTransient &&
inquirer?.isTransient &&
parentInquirer &&
contextId !== STATIC_CONTEXT
? parentInquirer
: inquirer;
}

private resolveScopedComponentHost(
item: InstanceWrapper,
contextId: ContextId,
Expand All @@ -955,7 +992,12 @@ export class Injector {
) {
return this.isInquirerRequest(item, parentInquirer)
? parentInquirer
: this.resolveComponentHost(item.host!, item, contextId, inquirer);
: this.resolveComponentHost(
item.host!,
item,
contextId,
this.getEffectiveInquirer(item, inquirer, parentInquirer, contextId),
);
}

private isInquirerRequest(
Expand Down
Loading
Loading