/
log.js
207 lines (152 loc) · 4.1 KB
/
log.js
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
'use strict';
const { struct } = require('superstruct');
const EventEmmiter = require('events');
const UUID = require('uuid/v4');
const LogError = require('./log-error');
const { STS, Firehose } = require('./aws-wrappers');
const ARN_DURATION = 1800; // 30 min
const MAX_ATTEMPTS = 3;
const MAX_TIMEOUT = 500;
const DELIVERY_STREAM_PREFIX = 'JanisTraceFirehose';
const sts = new STS();
const emitter = new EventEmmiter();
class Log {
static get _serviceName() {
return process.env.JANIS_SERVICE_NAME;
}
static get _env() {
return process.env.JANIS_ENV;
}
static get _roleArn() {
return process.env.LOG_ROLE_ARN;
}
static get _envs() {
return {
local: 'Local',
beta: 'Beta',
qa: 'QA',
prod: 'Prod'
};
}
static get deliveryStreamName() {
if(!this._deliveryStreamName)
this._deliveryStreamName = `${DELIVERY_STREAM_PREFIX}${this._getFormattedEnv()}`;
return this._deliveryStreamName;
}
/**
* Put a log into Firehose
* @param {String} client The client code who created the log
* @param {Object} log The log object
* @example
* add('some-client', {
* type: 'some-type',
* entity: 'some-entity',
* entityId: 'some-entityId',
* message: 'some-message',
* log: {
* some: 'log'
* }
* });
*/
static async add(client, log) {
try {
log = this._validateLog(log, client);
} catch(err) {
return emitter.emit('create-error', log, err);
}
return this._add(log);
}
/**
* Sets a callback for the specified event name
* @param {String} event The event name
* @param {Function} callback The event callback
* @example
* on('create-error', (log, err) => {...});
*/
static on(event, callback) {
emitter.on(event, callback);
}
static _validateLog(rawLog, client) {
const logStruct = struct.partial({
id: 'string',
service: 'string',
entity: 'string',
entityId: 'string?|number?',
type: 'string',
log: 'object?|array?',
message: 'string?',
client: 'string',
userCreated: 'string?'
}, {
id: UUID(),
service: this._serviceName,
client
});
try {
const validLog = logStruct(rawLog);
if(validLog.log)
validLog.log = JSON.stringify(validLog.log);
return {
...validLog,
dateCreated: new Date().toISOString()
};
} catch(err) {
throw new LogError(err.message, LogError.codes.INVALID_LOG);
}
}
static async _getFirehoseInstance() {
const hasExpired = this._credentialsExpiration < new Date();
if(this._firehose && !hasExpired)
return this._firehose;
const firehoseParams = {
region: process.env.AWS_DEFAULT_REGION,
httpOptions: { timeout: MAX_TIMEOUT }
};
if(this._roleArn) {
firehoseParams.credentials = await this._getCredentials();
this._credentialsExpiration = firehoseParams.credentials.expiration;
}
this._firehose = new Firehose(firehoseParams);
return this._firehose;
}
static async _getCredentials() {
const assumedRole = await sts.assumeRole({
RoleArn: this._roleArn,
RoleSessionName: this._serviceName,
DurationSeconds: ARN_DURATION
});
if(!assumedRole)
throw new LogError('Failed to assume role, invalid response.', LogError.codes.ASSUME_ROLE_ERROR);
const { Credentials, Expiration } = assumedRole;
return {
accessKeyId: Credentials.AccessKeyId,
secretAccessKey: Credentials.SecretAccessKey,
sessionToken: Credentials.SessionToken,
expiration: Expiration
};
}
static _getFormattedEnv() {
if(this._env && this._envs[this._env])
return this._envs[this._env];
throw new LogError('Unknown environment', LogError.codes.NO_ENVIRONMENT);
}
static async _add(log, attempts = 0) {
try {
const firehose = await this._getFirehoseInstance();
await firehose.putRecord({
DeliveryStreamName: this.deliveryStreamName,
Record: {
Data: Buffer.from(JSON.stringify(log))
}
});
} catch(err) {
attempts++;
if(attempts >= MAX_ATTEMPTS) {
return emitter.emit('create-error', log,
new LogError(`Unable to put the log into firehose, max attempts reached: ${err.message}`, LogError.codes.FIREHOSE_ERROR));
}
return this._add(log, attempts);
}
}
}
module.exports = Log;