/
ifto.ts
362 lines (322 loc) · 7.4 KB
/
ifto.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import { Context } from 'aws-lambda';
import { Spy } from './spy_modules';
import { formatedDate } from './util';
/**
* Function signature of the expected output function
*/
export type OutputFunction = (...arg: any[]) => void;
/**
* Environment variable to indicate monitoring should start
*/
export const ENV_VAR_MONITORING_START_NAME = 'ifto_start';
/**
* Environment variable to enable to disable monitoring
*/
export const ENV_VAR_MONITORING_START_VALUE = 'true';
/**
* Environment variable to configure "flushLogsWhenDifferenceLessThanMilliseconds"
*/
export const ENV_VAR_FLUSH_LOGS_WHEN_DIFFERENCE_LESS_THAN_MILLISECONDS =
'ifto_flush_when';
/**
* Extended Global variable.
* Holds the Ifto instance
* @export
* @interface ExtendedNodeJsGlobal
* @extends {NodeJS.Global}
*/
export interface ExtendedNodeJsGlobal extends NodeJS.Global {
Ifto?: Ifto;
}
/**
* Option interface
*
* @interface Options
*/
interface Options {
flushLogsWhenDifferenceLessThanMilliseconds: number;
output: OutputFunction;
}
/**
* Default options
*/
export const defaults: Options = {
flushLogsWhenDifferenceLessThanMilliseconds: 50,
output: console.log
};
/**
* If lambda Timeout (Ifto) main class.
*
* @export
* @class Ifto
*/
export class Ifto {
/**
* flag indicates monitoring should enable or not
*
* @private
* @memberof Ifto
*/
private allowedToMonitor = false;
/**
* Holds the log entries
*
* @private
* @type {string[]}
* @memberof Ifto
*/
private logEntries: string[] = [];
/**
* This holds minimum time difference (in milliseconds) value to flush the logs.
*
* Lambda context contains 'getRemainingTimeInMillis()' function which give how many milliseconds
* left for execution. flushLogsWhenDifferenceLessThanMilliseconds defines minimum milliseconds left,
* before flushing logs.
* Eg:
* if (context.getRemainingTimeInMillis() <= flushLogsWhenDifferenceLessThanMilliseconds) {
* flush the logs
* }
*
* @private
* @type {number}
* @memberof Ifto
*/
private flushLogsWhenDifferenceLessThanMilliseconds: number;
/**
* Holds the output function
*
* @private
* @type {OutputFunction}
* @memberof Ifto
*/
private output: OutputFunction;
/**
* Holds the lambda Context object
*
* @private
* @type {Context}
* @memberof Ifto
*/
private lambdaContext?: Context;
/**
* Creates an instance of Ifto.
* @memberof Ifto
*/
constructor() {
this.flushLogsWhenDifferenceLessThanMilliseconds =
defaults.flushLogsWhenDifferenceLessThanMilliseconds;
this.output = defaults.output;
}
/**
* Get instance of Ifto
*
* @static
* @returns {Ifto}
* @memberof Ifto
*/
static getInstance(): Ifto {
return new Ifto();
}
/**
* Add Lambda function context
*
* @param {Context} lambdaContext
* @returns
* @memberof Ifto
*/
addLambdaContext(lambdaContext: Context) {
this.lambdaContext = lambdaContext;
return this;
}
/**
* Return lambda Context
*
* @returns {Context}
* @memberof Ifto
*/
getLambdaContext() {
return this.lambdaContext;
}
/**
* Update output function
*
* @param {OutputFunction} output
* @returns
* @memberof Ifto
*/
updateOutputFunction(output: OutputFunction) {
this.output = output;
return this;
}
/**
* Get output function
*
* @returns {OutputFunction}
* @memberof Ifto
*/
getOutputFunction() {
return this.output;
}
/**
* Get log entries
*
* @returns
* @memberof Ifto
*/
getLogEntries() {
return this.logEntries;
}
/**
* Log data
*
* @param {string} entry
* @returns
* @memberof Ifto
*/
log(entry: string) {
this.logEntries.push(this.getLogEntry(this.logEntries, entry));
return this;
}
/**
* Get value for flushLogsWhenDifferenceLessThanMilliseconds
*
* @returns
* @memberof Ifto
*/
getFlushLogsWhenDifferenceLessThanMilliseconds() {
return this.flushLogsWhenDifferenceLessThanMilliseconds;
}
/**
* Attach to Global object
*
* @param {ExtendedNodeJsGlobal} globalObject
* @returns
* @memberof Ifto
*/
attach(globalObject: ExtendedNodeJsGlobal) {
if (!globalObject.Ifto) {
globalObject.Ifto = this;
}
return this;
}
/**
* Indicates whether the monitoring should start or not
*
* @returns
* @memberof Ifto
*/
isAllowedToMonitor() {
return this.allowedToMonitor;
}
/**
* Initialize the Ifto process
*
* @param {NodeJS.Process} currentProcess
* @returns
* @memberof Ifto
*/
init(params: NodeJS.ProcessEnv) {
// Initializing the monitoring flag
const envValue = this.getValueFromProcessEnv(
params,
ENV_VAR_MONITORING_START_NAME
);
this.allowedToMonitor = !!(
envValue &&
envValue.toLocaleLowerCase() === ENV_VAR_MONITORING_START_VALUE
);
// Initializing flush time value
const flushTimeValue = this.getValueFromProcessEnv(
params,
ENV_VAR_FLUSH_LOGS_WHEN_DIFFERENCE_LESS_THAN_MILLISECONDS
);
if (flushTimeValue) {
const timeout = parseInt(flushTimeValue as string, 10);
if (!isNaN(timeout)) {
this.flushLogsWhenDifferenceLessThanMilliseconds = timeout;
}
}
return this;
}
/**
* Start monitoring
*
* @param {Promise<any>} executor
* @returns
* @memberof Ifto
*/
async monitor(handler: Promise<any>): Promise<any> {
let interval: NodeJS.Timeout | undefined;
if (this.allowedToMonitor && this.lambdaContext) {
const spy = Spy.getInstance(10);
spy.start();
interval = setInterval(() => {
spy.stop();
this.output(
`${this.getWarningString()}\n${this.logEntries.join(
'\n'
)}\n${spy.printEntries()}`
);
this.clearMonitoringInterval(interval);
}, this.lambdaContext.getRemainingTimeInMillis() - this.flushLogsWhenDifferenceLessThanMilliseconds);
}
try {
const result = await handler;
this.clearMonitoringInterval(interval);
return result;
} catch (error) {
this.clearMonitoringInterval(interval);
throw error;
}
}
/**
* Clear
*
* @private
* @param {NodeJS.Timeout} [interval]
* @memberof Ifto
*/
private clearMonitoringInterval(interval?: NodeJS.Timeout) {
if (interval) {
clearInterval(interval);
}
}
/**
* Get formated log entry
*
* @private
* @param {string[]} logArray
* @param {string} entry
* @returns
* @memberof Ifto
*/
private getLogEntry(logArray: string[], entry: string) {
return `${formatedDate()} ${logArray.length}: ${entry}`;
}
/**
* Get the warning header
*
* @private
* @returns
* @memberof Ifto
*/
private getWarningString() {
return `
Expecting a possible lambda timeout.
Only ${this.flushLogsWhenDifferenceLessThanMilliseconds} milliseconds remaining.
(If this is a false positive error change the value by setting up the environment variable "${ENV_VAR_FLUSH_LOGS_WHEN_DIFFERENCE_LESS_THAN_MILLISECONDS}").
Current log:`;
}
/**
* try to extract lower case or upper case values
*
* @private
* @param {NodeJS.ProcessEnv} params
* @param {string} valueKey
* @returns
* @memberof Ifto
*/
private getValueFromProcessEnv(params: NodeJS.ProcessEnv, valueKey: string) {
return params[valueKey] || params[valueKey.toUpperCase()];
}
}