-
Notifications
You must be signed in to change notification settings - Fork 374
/
timeout.ts
52 lines (47 loc) · 1.71 KB
/
timeout.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Filter for timeout.
* Print a warn information when request timeout.
*/
import { getLogger } from 'pinus-logger'; let logger = getLogger('pinus', __filename);
import * as utils from '../../util/utils';
import { IHandlerFilter } from '../../interfaces/IHandlerFilter';
import { RouteRecord } from '../../util/constants';
import { HandlerCallback } from '../../common/service/handlerService';
import { FrontendOrBackendSession } from '../../server/server';
let DEFAULT_TIMEOUT = 3000;
let DEFAULT_SIZE = 500;
export class TimeoutFilter implements IHandlerFilter
{
timeouts : {[id:number]:NodeJS.Timer} = {};
curId = 0;
constructor(private timeout = DEFAULT_TIMEOUT, private maxSize = DEFAULT_SIZE)
{
};
before(routeRecord : RouteRecord , msg : any, session : FrontendOrBackendSession, next : HandlerCallback)
{
let count = utils.size(this.timeouts);
if (count > this.maxSize)
{
logger.warn('timeout filter is out of range, current size is %s, max size is %s', count, this.maxSize);
next(null);
return;
}
this.curId++;
this.timeouts[this.curId] = setTimeout(function ()
{
logger.error('request %j timeout.', routeRecord.route);
}, this.timeout);
(session as any).__timeout__ = this.curId;
next(null);
};
after(err : Error, routeRecord : RouteRecord , msg : any, session : FrontendOrBackendSession, resp : any, next : HandlerCallback)
{
let timeout = this.timeouts[(session as any).__timeout__];
if (timeout)
{
clearTimeout(timeout);
delete this.timeouts[(session as any).__timeout__];
}
next(err);
};
}