-
Notifications
You must be signed in to change notification settings - Fork 567
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #156 from midwayjs/fix_schedule
refactor: support @schedule decorator
- Loading branch information
Showing
28 changed files
with
203 additions
and
503 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,46 @@ | ||
module.exports = require('egg-schedule/agent'); | ||
import { ScheduleOpts, SCHEDULE_KEY } from '@midwayjs/decorator'; | ||
import { getClassMetaData, listModule, TagClsMetadata, TAGGED_CLS } from 'injection'; | ||
import 'reflect-metadata'; | ||
|
||
export = (agent) => { | ||
|
||
// ugly!! just support all and worker strategy | ||
class AllStrategy extends agent['TimerScheduleStrategy'] { | ||
handler() { | ||
this.sendAll(); | ||
} | ||
} | ||
|
||
class WorkerStrategy extends agent['TimerScheduleStrategy'] { | ||
handler() { | ||
this.sendOne(); | ||
} | ||
} | ||
|
||
const strategyMap = new Map(); | ||
strategyMap.set('worker', WorkerStrategy); | ||
strategyMap.set('all', AllStrategy); | ||
|
||
agent.messenger.once('egg-ready', () => { | ||
const schedules: any[] = listModule(SCHEDULE_KEY); | ||
for (const scheduleModule of schedules) { | ||
const metaData = Reflect.getMetadata(TAGGED_CLS, scheduleModule) as TagClsMetadata; | ||
const opts: ScheduleOpts = getClassMetaData(SCHEDULE_KEY, scheduleModule); | ||
const type = opts.type; | ||
if (opts.disable) { | ||
continue; | ||
} | ||
const key = metaData.id + '#' + scheduleModule.name; | ||
const Strategy = strategyMap.get(type); | ||
if (!Strategy) { | ||
const err = new Error(`schedule type [${type}] is not defined`); | ||
err.name = 'MidwayScheduleError'; | ||
throw err; | ||
} | ||
|
||
const instance = new Strategy(opts, agent, key); | ||
instance.start(); | ||
} | ||
}); | ||
|
||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,110 +1,35 @@ | ||
'use strict'; | ||
|
||
import * as qs from 'querystring'; | ||
import * as path from 'path'; | ||
import loadSchedule from './lib/load_schedule'; | ||
import * as fs from 'fs'; | ||
|
||
const loadEggSchedule = require('egg-schedule/lib/load_schedule'); | ||
|
||
module.exports = (app) => { | ||
// don't redirect scheduleLogger | ||
app.loggers.scheduleLogger.unredirect('error'); | ||
|
||
// 'app/schedule' load egg-schedule (spec for egg-logxx rotate) | ||
const schedules = loadEggSchedule(app); | ||
// 'lib/schedule' load midway-schedule (class only with decorator support) | ||
loadSchedule(app); | ||
|
||
// for test purpose | ||
app.runSchedule = (schedulePath, key = 'default') => { | ||
if (!path.isAbsolute(schedulePath)) { | ||
schedulePath = path.join( | ||
app.config.baseDir, | ||
'app/schedule', | ||
schedulePath, | ||
); | ||
if (!fs.existsSync(schedulePath)) { | ||
schedulePath = path.join( | ||
app.config.baseDir, | ||
'lib/schedule', | ||
schedulePath, | ||
import { ScheduleOpts, SCHEDULE_KEY } from '@midwayjs/decorator'; | ||
import { getClassMetaData, listModule, TagClsMetadata, TAGGED_CLS } from 'injection'; | ||
import * as is from 'is-type-of'; | ||
import 'reflect-metadata'; | ||
|
||
export = (app) => { | ||
const schedules: any[] = listModule(SCHEDULE_KEY); | ||
for (const scheduleModule of schedules) { | ||
const metaData = Reflect.getMetadata(TAGGED_CLS, scheduleModule) as TagClsMetadata; | ||
if (metaData) { | ||
const key = metaData.id + '#' + scheduleModule.name; | ||
const opts: ScheduleOpts = getClassMetaData(SCHEDULE_KEY, scheduleModule); | ||
const task = async (ctx, data) => { | ||
const ins = await ctx.requestContext.getAsync(scheduleModule); | ||
ins.exec = app.toAsyncFunction(ins.exec); | ||
return ins.exec(ctx, data); | ||
}; | ||
|
||
const env = app.config.env; | ||
const envList = opts.env; | ||
if (is.array(envList) && !envList.includes(env)) { | ||
app.coreLogger.info( | ||
`[midway-schedule]: ignore schedule ${key} due to \`schedule.env\` not match`, | ||
); | ||
return; | ||
} | ||
app.schedules[key] = { | ||
schedule: opts, | ||
task, | ||
key, | ||
}; | ||
} | ||
schedulePath = require.resolve(schedulePath); | ||
let schedule; | ||
|
||
try { | ||
schedule = schedules[schedulePath] || schedules[schedulePath + '#' + key]; | ||
if (!schedule) { | ||
throw new Error(`Cannot find schedule ${schedulePath}`); | ||
} | ||
} catch (err) { | ||
err.message = `[egg-schedule] ${err.message}`; | ||
return Promise.reject(err); | ||
} | ||
|
||
// run with anonymous context | ||
const ctx = app.createAnonymousContext({ | ||
method: 'SCHEDULE', | ||
url: `/__schedule?path=${schedulePath}&${qs.stringify( | ||
schedule.schedule, | ||
)}`, | ||
}); | ||
|
||
return schedule.task(ctx); | ||
}; | ||
|
||
// log schedule list | ||
for (const s in schedules) { | ||
const schedule = schedules[s]; | ||
if (!schedule.schedule.disable) | ||
app.coreLogger.info('[egg-schedule]: register schedule %s', schedule.key); | ||
} | ||
|
||
// register schedule event | ||
app.messenger.on('egg-schedule', (data) => { | ||
const id = data.id; | ||
const key = data.key; | ||
const schedule = schedules[key]; | ||
const logger = app.loggers.scheduleLogger; | ||
logger.info(`[${id}] ${key} task received by app`); | ||
|
||
if (!schedule) { | ||
logger.warn(`[${id}] ${key} unknown task`); | ||
return; | ||
} | ||
/* istanbul ignore next */ | ||
if (schedule.schedule.disable) return; | ||
|
||
// run with anonymous context | ||
const ctx = app.createAnonymousContext({ | ||
method: 'SCHEDULE', | ||
url: `/__schedule?path=${key}&${qs.stringify(schedule.schedule)}`, | ||
}); | ||
|
||
const start = Date.now(); | ||
const task = schedule.task; | ||
logger.info(`[${id}] ${key} executing by app`); | ||
// execute | ||
task(ctx, ...data.args) | ||
.then(() => true) // succeed | ||
.catch((err) => { | ||
logger.error(`[${id}] ${key} execute error.`, err); | ||
err.message = `[egg-schedule] ${key} execute error. ${err.message}`; | ||
app.logger.error(err); | ||
return false; // failed | ||
}) | ||
.then((success) => { | ||
const rt = Date.now() - start; | ||
const status = success ? 'succeed' : 'failed'; | ||
ctx.coreLogger.info( | ||
`[egg-schedule] ${key} execute ${status}, used ${rt}ms`, | ||
); | ||
logger[success ? 'info' : 'error']( | ||
`[${id}] ${key} execute ${status}, used ${rt}ms`, | ||
); | ||
}); | ||
}); | ||
}; |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.