Skip to content

Commit

Permalink
feat: support background task on ctx
Browse files Browse the repository at this point in the history
```js
ctx.runAtBackground(function* (ctx) {
  // async actions here
});
```
  • Loading branch information
fengmk2 committed Oct 14, 2016
1 parent 163aa7e commit ba78878
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 6 deletions.
32 changes: 26 additions & 6 deletions app/extend/context.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
/**
* 对 koa context 的所有扩展,都放在此文件统一维护。
*
* - koa context: https://github.com/koajs/koa/blob/master/lib/context.js
*/

'use strict';

const delegate = require('delegates');
const jsonpBody = require('jsonp-body');
const ContextLogger = require('egg-logger').EggContextLogger;
const Cookies = require('egg-cookies');
const co = require('co');
const util = require('../../lib/core/util');

const LOGGER = Symbol('LOGGER');
Expand Down Expand Up @@ -345,6 +340,31 @@ const proto = module.exports = {
set state(val) {
this.locals = val;
},

/**
* Run generator function in the background
* @param {Generator} scope - generator function, the first args is ctx
* ```js
* this.body = 'hi';
*
* this.runInBackground(function* saveUserInfo(ctx) {
* yield ctx.mysql.query(sql);
* yield ctx.curl(url);
* });
* ```
*/
runInBackground(scope) {
const ctx = this;
const start = Date.now();
const taskName = scope.name || '-';
co(function* () {
yield scope(ctx);
ctx.coreLogger.info('[egg:background] task:%s success (%dms)', taskName, Date.now() - start);
}).catch(err => {
ctx.coreLogger.info('[egg:background] task:%s fail (%dms)', taskName, Date.now() - start);
ctx.coreLogger.error(err);
});
},
};

/**
Expand Down
44 changes: 44 additions & 0 deletions test/app/extend/context.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -305,4 +305,48 @@ describe('test/app/extend/context.test.js', () => {
context.state.should.equal(context.locals);
});
});

describe('ctx.runInBackground(scope)', () => {
let app;
before(() => {
app = utils.app('apps/ctx-background');
});
after(() => app.close());

it('should run background task success', done => {
request(app.callback())
.get('/')
.expect(200)
.expect('hello')
.end(err => {
if (err) return done(err);
setTimeout(() => {
const logdir = app.config.logger.dir;
const log = fs.readFileSync(path.join(logdir, 'ctx-background-web.log'), 'utf8');
log.should.match(/background run result status: 200/);
fs.readFileSync(path.join(logdir, 'egg-web.log'), 'utf8')
.should.match(/\[egg:background\] task:saveUserInfo success \(\d+ms\)/);
done();
}, 3000);
});
});

it('should run background task error', done => {
request(app.callback())
.get('/error')
.expect(200)
.expect('hello error')
.end(err => {
if (err) return done(err);
setTimeout(() => {
const logdir = app.config.logger.dir;
const log = fs.readFileSync(path.join(logdir, 'common-error.log'), 'utf8');
log.should.match(/getaddrinfo ENOTFOUND registry-not-exists\.npm/);
fs.readFileSync(path.join(logdir, 'egg-web.log'), 'utf8')
.should.match(/\[egg:background\] task:mockError fail \(\d+ms\)/);
done();
}, 2000);
});
});
});
});
9 changes: 9 additions & 0 deletions test/fixtures/apps/ctx-background/app/controller/error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use strict';

module.exports = function* () {
this.body = 'hello error';
this.runInBackground(function* mockError(ctx) {
const r = yield ctx.curl('http://registry-not-exists.npm.taobao.org/pedding/latest', { dataType: 'json' });
ctx.logger.warn('background run result status: %s', r.status);
});
};
10 changes: 10 additions & 0 deletions test/fixtures/apps/ctx-background/app/controller/home.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

module.exports = function* () {
this.body = 'hello';
this.runInBackground(function* saveUserInfo(ctx) {
const domain = process.env.CI ? 'registry.npmjs.com' : 'registry.npm.taobao.org';
const r = yield ctx.curl(`http://${domain}/pedding/latest`, { dataType: 'json' });
ctx.logger.warn('background run result status: %s', r.status);
});
};
6 changes: 6 additions & 0 deletions test/fixtures/apps/ctx-background/app/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

module.exports = app => {
app.get('/', app.controller.home);
app.get('/error', app.controller.error);
};
3 changes: 3 additions & 0 deletions test/fixtures/apps/ctx-background/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "ctx-background"
}

0 comments on commit ba78878

Please sign in to comment.