| 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 |
1
1
1
1
1
1
1
1
1
566
283
283
283
283
283
283
283
283
283
283
283
283
1
1
307
307
27
1
281
281
1
2449
2449
1
280
280
280
1
27
27
1
27
27
1
283
283
283
283
283
283
283
1
75
1
2449
2449
2449
2449
2305
2449
2449
1
75
75
75
75
75
75
75
153
153
153
153
145
145
75
75
14
14
4
4
75
1
283
283
283
283
283
283
283
1
1
27
27
1
27
1
281
281
281
1
27
27
27
27
21
6
6
6
1
6
6
1
6
1
287
287
212
212
212
212
75
75
75
75
1
75
75
153
75
1
281
281
281
281
212
281
1
75
75
75
75
75
| // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var setTimeout = require('timers').setTimeout;
var clearTimeout = require('timers').clearTimeout;
var fs = require('fs');
var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var DEFAULT_POLL_INTERVAL = 60 * 1000;
module.exports = RemoteConfig;
function RemoteConfig(options) {
if (!(this instanceof RemoteConfig)) {
return new RemoteConfig(options);
}
var self = this;
EventEmitter.call(self);
assert(options && options.configFile, 'options.configFile required');
assert(options && options.logger, 'options.logger required');
self.logger = options.logger;
self.logError = options.logError;
self.pollInterval = options.pollInterval || DEFAULT_POLL_INTERVAL;
self.configRemoteFile = new RemoteConfigFile({
filePath: options.configFile,
logger: options.logger,
logError: self.logError
});
self._configValues = new ConfigValues({
remoteConfig: self,
configRemoteFile: self.configRemoteFile,
logger: options.logger
});
self.pollTimer = null;
self._destroyed = false;
}
util.inherits(RemoteConfig, EventEmitter);
RemoteConfig.prototype.startPolling = function startPolling() {
var self = this;
self.pollTimer = setTimeout(function onPoll() {
self._checkFile();
}, self.pollInterval);
};
RemoteConfig.prototype.loadSync = function loadSync() {
var self = this;
self.configRemoteFile.loadSync();
};
RemoteConfig.prototype.get = function get(key, defaultValue) {
var self = this;
return self._configValues.get(key, defaultValue);
};
RemoteConfig.prototype.destroy = function destroy() {
var self = this;
self._destroyed = true;
clearTimeout(self.pollTimer);
};
RemoteConfig.prototype._checkFile = function _checkFile() {
var self = this;
self.configRemoteFile.statFile(finish);
function finish() {
Eif (!self._destroyed) {
self.startPolling();
}
}
};
/* ConfigValues
This class keeps on updating config files
Supports three functions
- get(key) lookup the key in the current configData
- emit('update') emits a update event if there is new data
- emit('change:{key}') emits a change event if a key changed
*/
function ConfigValues(options) {
Iif (!(this instanceof ConfigValues)) {
return new ConfigValues(options);
}
var self = this;
self.logger = options.logger;
self.configRemoteFile = options.configRemoteFile;
self.remoteConfig = options.remoteConfig;
self._configValues = {};
self.configRemoteFile.on('fileChange', updateConfigValues);
function updateConfigValues(configObject) {
self._updateConfigValues(configObject);
}
}
ConfigValues.prototype.get = function get(key, defaultValue) {
var self = this;
assert(defaultValue !== undefined, 'defaultValue is required');
var value = self._configValues[key];
if (value === undefined) {
value = defaultValue;
}
Iif (typeof value !== typeof defaultValue) {
self.logger.error('[remote-config] Mismatch of value types', {
defaultValueType: typeof defaultValue,
valueType: typeof value
});
return defaultValue;
}
return value;
};
ConfigValues.prototype._updateConfigValues = function _updateConfigValues(newConfig) {
var self = this;
var oldConfigValues = self._configValues;
self._configValues = newConfig;
self.remoteConfig.emit('update');
var changedKeys = [];
// check for values in current newConfig that are different in oldConfig
var keys = Object.keys(newConfig);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var newJSON = JSON.stringify(newConfig[key]);
var oldJSON = JSON.stringify(oldConfigValues[key]);
if (newJSON !== oldJSON) {
self.remoteConfig.emit('change:' + key);
changedKeys.push('update:' + key);
}
}
// Check for old keys that do not exist in current newConfig
var oldKeys = Object.keys(oldConfigValues);
for (var j = 0; j < oldKeys.length; j++) {
var oldKey = oldKeys[j];
if (!(oldKey in newConfig)) {
self.remoteConfig.emit('change:' + oldKey);
changedKeys.push('remove:' + key);
}
}
self.logger.info('[remote-config] config file changed', {
changedKeys: changedKeys,
newConfig: newConfig
});
};
/* RemoteConfigFile
This class deals with all file IO. If you want to get the
file from a different remote location you could implement
another RemoteConfigFile that doesnt do file IO.
Supports three functions:
- loadSync(), checks the file sync and emits change event
- statFile(), checks to see if fs.Stat is different, if
so will load async and emit change event
- on('fileChange'), listen to file changes
*/
function RemoteConfigFile(options) {
Iif (!(this instanceof RemoteConfigFile)) {
return new RemoteConfigFile(options);
}
var self = this;
EventEmitter.call(self);
self.filePath = options.filePath;
self.logger = options.logger;
self.logError = options.logError;
self._oldStat = null;
}
util.inherits(RemoteConfigFile, EventEmitter);
RemoteConfigFile.prototype.statFile = function statFile(cb) {
var self = this;
fs.stat(self.filePath, onStat);
function onStat(err, stat) {
self._onStat(err, stat, cb);
}
};
RemoteConfigFile.prototype.loadSync = function loadSync() {
var self = this;
var result = safeSyncRead(self.filePath);
self._parseFile(result.error, result.fileContents);
};
RemoteConfigFile.prototype._onStat = function _onStat(err, stat, cb) {
var self = this;
Iif (err) {
var msg = '[remote-config] Could not stat file';
var logObj = {
error: err,
filePath: self.filePath
};
if (self.logError) {
self.logger.error(msg, logObj);
}
return cb();
}
var oldStat = self._oldStat;
if (oldStat && Number(oldStat.mtime) === Number(stat.mtime) &&
Number(oldStat.size) === Number(stat.size)) {
return cb();
}
self._oldStat = stat;
self._refreshFile();
cb();
};
RemoteConfigFile.prototype._refreshFile = function _refreshFile() {
var self = this;
fs.readFile(self.filePath, 'utf8', onFile);
function onFile(err, fileContents) {
self._parseFile(err, fileContents);
}
};
RemoteConfigFile.prototype._parseFile = function _parseFile(err, fileContents) {
var self = this;
if (err) {
var msg = '[remote-config] could not read file';
var logObj = {
error: err,
filePath: self.filePath
};
Iif (self.logError) {
self.logger.error(msg, logObj);
}
return;
}
var result = safeJSONParse(fileContents);
Iif (result.error) {
self.logger.error('[remote-config] could not json parse file', {
error: result.error,
filePath: self.filePath
});
return;
}
var json = self._convert(result.json);
self.emit('fileChange', json);
};
RemoteConfigFile.prototype._convert = function _convert(json) {
var object = {};
for (var i = 0; i < json.length; i++) {
object[json[i].key] = json[i].value;
}
return object;
};
function safeSyncRead(filePath) {
var fileContents;
var error;
try {
fileContents = fs.readFileSync(filePath, 'utf8');
} catch (err) {
error = err;
}
return {
fileContents: fileContents,
error: error
};
}
function safeJSONParse(text) {
var json;
var error;
try {
json = JSON.parse(text);
} catch (err) {
error = err;
}
return {
json: json,
error: error
};
}
|