Skip to content

Commit

Permalink
馃摝 NEW: Run async function in the anonymous context scope (#5094)
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Dec 16, 2022
1 parent 5128bb9 commit 9d6acfd
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 2 deletions.
7 changes: 7 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,13 @@ declare module 'egg' {
*/
runInBackground(scope: (ctx: Context) => void): void;

/**
* Run async function in the anonymous context scope
* @see Context#runInAnonymousContextScope
* @param {Function} scope - the first args is an anonymous ctx, scope should be async function
*/
runInAnonymousContextScope(scope: (ctx: Context) => Promise<void>): Promise<void>;

/**
* Get current execute ctx async local storage
* @returns {AsyncLocalStorage} localStorage - store current execute Context
Expand Down
17 changes: 16 additions & 1 deletion lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,22 @@ class Application extends EggApplication {
runInBackground(scope) {
const ctx = this.createAnonymousContext();
if (!scope.name) scope._name = eggUtils.getCalleeFromStack(true);
ctx.runInBackground(scope);
this.ctxStorage.run(ctx, () => {
ctx.runInBackground(scope);
});
}

/**
* Run async function in the anonymous context scope
* @see Context#runInAnonymousContextScope
* @param {Function} scope - the first args is an anonymous ctx, scope should be async function
*/
async runInAnonymousContextScope(scope) {
const ctx = this.createAnonymousContext();
if (!scope.name) scope._name = eggUtils.getCalleeFromStack(true);
await this.ctxStorage.run(ctx, async () => {
await scope(ctx);
});
}

/**
Expand Down
20 changes: 19 additions & 1 deletion test/app/extend/application.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ describe('test/app/extend/application.test.js', () => {
.get('/app_background')
.expect(200)
.expect('hello app');
await utils.sleep(5000);
await utils.sleep(2100);
const logdir = app.config.logger.dir;
const log = fs.readFileSync(path.join(logdir, 'ctx-background-web.log'), 'utf8');
assert(/mock background run at app result file size: \d+/.test(log));
Expand All @@ -190,6 +190,24 @@ describe('test/app/extend/application.test.js', () => {
});
});

describe('app.runInAnonymousContextScope(scope)', () => {
it('should run task in anonymous context scope success', async () => {
const app = utils.app('apps/app-runInAnonymousContextScope');
await app.ready();
await app.close();
await utils.sleep(2100);
const logdir = app.config.logger.dir;
const logs = fs.readFileSync(path.join(logdir, 'app-runInAnonymousContextScope-web.log'), 'utf8').split('\n');
// console.log(logs);
// 2022-12-15 23:00:08,551 INFO 86728 [-/127.0.0.1/-/1ms GET /] before close on ctx logger
// 2022-12-15 23:00:08,551 INFO 86728 [-/127.0.0.1/-/1ms GET /] before close on app logger
// 2022-12-15 23:03:16,086 INFO 89216 outside before close on app logger
assert.match(logs[0], / INFO \d+ \[-\/127.0.0.1\/-\/\d+ms GET \/] inside before close on ctx logger/);
assert.match(logs[1], / INFO \d+ \[-\/127.0.0.1\/-\/\d+ms GET \/] inside before close on app logger/);
assert.match(logs[2], / INFO \d+ outside before close on app logger/);
});
});

describe('app.handleRequest(ctx, fnMiddleware)', () => {
let app;
before(() => {
Expand Down
13 changes: 13 additions & 0 deletions test/fixtures/apps/app-runInAnonymousContextScope/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = class Boot {
constructor(app) {
this.app = app;
}

async beforeClose() {
await this.app.runInAnonymousContextScope(async ctx => {
ctx.logger.info('inside before close on ctx logger');
this.app.logger.info('inside before close on app logger');
});
this.app.logger.info('outside before close on app logger');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exports.keys = 'foo';
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
exports.logger = {
consoleLevel: 'NONE',
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "app-runInAnonymousContextScope"
}
7 changes: 7 additions & 0 deletions test/fixtures/apps/app-ts-type-check/normal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ app.logger.info(app.Service);
app.logger.info(app.Controller);
app.controller.test().then(() => {});

async function main() {
await app.runInAnonymousContextScope(async ctx => {
await ctx.httpclient.request('url');
});
}
main();

// agent
const agent = new Agent({ baseDir: __dirname, plugins: {}, type: 'agent' });
agent.logger.info('123');
Expand Down

0 comments on commit 9d6acfd

Please sign in to comment.