feat(server): add request id on cluster event (#9998)

This commit is contained in:
fengmk2
2025-02-07 02:06:53 +00:00
parent 891d9df0b1
commit 1e83a056fc
3 changed files with 34 additions and 13 deletions

View File

@@ -1,5 +1,6 @@
import { INestApplication } from '@nestjs/common';
import ava, { TestFn } from 'ava';
import { CLS_ID, ClsServiceManager } from 'nestjs-cls';
import Sinon from 'sinon';
import { EventBus } from '../../base';
@@ -11,6 +12,7 @@ const test = ava as TestFn<{
app1: INestApplication;
app2: INestApplication;
}>;
async function createApp() {
const m = await createTestingModule(
{
@@ -49,14 +51,20 @@ test('should broadcast event to cluster instances', async t => {
// app 2 for broadcasting
const eventbus2 = app2.get(EventBus);
eventbus2.broadcast('__test__.event', { count: 0 });
const cls = ClsServiceManager.getClsService();
cls.run(() => {
cls.set(CLS_ID, 'test-request-id');
eventbus2.broadcast('__test__.event', { count: 0, requestId: cls.getId() });
});
// cause the cross instances broadcasting is asynchronization calling
// we should wait for the event's arriving before asserting
await eventbus1.waitFor('__test__.event');
t.true(listener.calledOnceWith({ count: 0 }));
t.true(runtimeListener.calledOnceWith({ count: 0 }));
t.true(listener.calledOnceWith({ count: 0, requestId: 'test-request-id' }));
t.true(
runtimeListener.calledOnceWith({ count: 0, requestId: 'test-request-id' })
);
off();
});

View File

@@ -4,7 +4,7 @@ import { OnEvent } from '../../base';
declare global {
interface Events {
'__test__.event': { count: number };
'__test__.event': { count: number; requestId?: string };
'__test__.event2': { count: number };
'__test__.throw': { count: number };
}
@@ -13,10 +13,15 @@ declare global {
@Injectable()
export class Listeners {
@OnEvent('__test__.event')
onTestEvent({ count }: Events['__test__.event']) {
return {
count: count + 1,
};
onTestEvent({ count, requestId }: Events['__test__.event']) {
return requestId
? {
count: count + 1,
requestId,
}
: {
count: count + 1,
};
}
@OnEvent('__test__.throw')