-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfile_persistence.js
356 lines (297 loc) · 10.1 KB
/
file_persistence.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
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
/*
* Copyright (c) 2016-2017 Rafał Michalski <[email protected]>
*/
"use strict";
const THRESHOLD_SIZE_NEW_FILE = 512*1024;
const assign = Object.assign
, getOwnPropertyNames = Object.getOwnPropertyNames
const path = require('path');
const { createReadStream, createWriteStream } = require('fs');
const { createDecodeStream, Encoder } = require("msgpack-lite");
const { defineConst } = require('../utils/helpers');
const synchronize = require('../utils/synchronize');
const { close, fdatasync, link, openDir, readdir, renameSyncDir, unlink } = require("../utils/fsutil");
const { mixin: mixinHistoryRotation, createRotateName } = require('../utils/filerotate');
const { createTempName, cleanupTempFiles } = require('../utils/tempfiles');
const PersistenceBase = require('../api/persistence_base');
const debug = require('debug')('zmq-raft:file-persistence');
const encoder$ = Symbol('encoder')
, fd$ = Symbol('fd')
, writeStream$ = Symbol('writeStream')
const apply$ = Symbol.for('apply')
, byteSize$ = Symbol.for('byteSize')
, close$ = Symbol.for('close')
, init$ = Symbol.for('init')
, rotate$ = Symbol.for('rotate')
, update$ = Symbol.for('update')
, validate$ = Symbol.for('validate')
, data$ = Symbol.for('data')
class FilePersistence extends PersistenceBase {
/**
* Creates new instance
*
* `filename` should contain path to a filename in some existing directory.
* `initial` should contain all the state properties set to their intial state.
*
* A new file will be created if `filename` does not exist.
*
* Implementations must call super(filename, initial) in the constructor.
* Implementations may implement [Symbol.for('init')]() method for additional asynchronous initialization.
* Implementations should call this[Symbol.for('setReady')]() upon successfull initialization.
* Implementations should call this.error(err) upon error while initializing.
*
* @param {string} filename
* @param {Object} initial
* @return this
**/
constructor(filename, initial) {
super(initial);
defineConst(this, 'filename', filename);
this[byteSize$] = 0;
var onready = (flags, data, byteSize) => {
const error = (err) => this.error(err);
const writeStream = createWriteStream(filename, {flags: flags})
.on('error', error)
.on('open', fd => {
writeStream.removeListener('error', error);
debug('file "%s" opened with flags: %s', filename, flags);
new Promise((resolve, reject) => {
this[apply$](this[validate$](data));
this[byteSize$] = byteSize;
this[encoder$] = new Encoder();
this[fd$] = fd;
this[writeStream$] = writeStream;
debug('ready: %j', data);
cleanupTempFiles(filename, debug).catch(err => debug('temporary files cleanup ERROR: %s', err));
resolve(this[init$]());
})
.then(() => this[Symbol.for('setReady')]())
.catch(err => {
this[writeStream$] = null;
this[fd$] = null;
close(fd);
this.error(err);
});
});
};
const read = () => {
var lastData = assign({}, this.defaultData);
var byteSize = 0;
var decodeStream = createDecodeStream();
var readStream = createReadStream(filename)
.on('error', err => {
if (err.code === "ENOENT") {
debug('no such file: "%s", creating new state', filename);
setImmediate(onready, 'ax', lastData, 0);
}
else this.error(err);
})
.on('open', fd => {
debug('file "%s" opened for reading: %s', filename, fd);
})
.on("data", chunk => {
byteSize += chunk.byteLength;
});
readStream.pipe(decodeStream)
.on("data", data => {
if (data && 'object' === typeof data && lastData) assign(lastData, data);
else lastData = undefined;
})
.on("end", () => {
debug('finished reading: %s bytes', byteSize);
if (decodeStream.decoder.buffer &&
decodeStream.decoder.buffer.length !== decodeStream.decoder.offset) {
debug("unfinished chunk detected, a new file will be created on next update");
byteSize = THRESHOLD_SIZE_NEW_FILE;
}
setImmediate(onready, 'a', lastData, byteSize);
});
};
read();
}
/**
* additional initialization
*
* Implementations may initialize additional resources asynchronously,
* in such case this method should return promise.
*
* @return {Promise}
**/
[init$]() {
/* no-op */
}
/**
* closes this instance
*
* Implementations must call super.close() in overloaded method.
* However if overloaded method also need to call synchronize on this instance
* they might call super[Symbol.for('close')]() instead.
*
* @return {Promise}
**/
close() {
return synchronize(this, () => this[close$]());
}
/**
* closes storage file
*
* Implementations may call this method instead super.close() from synchronize callback:
*
* synchronize(this, () => this[Symbol.for('close')]());
*
* @return {Promise}
**/
[close$]() {
var writeStream = this[writeStream$];
this[writeStream$] = this[fd$] = null;
return new Promise((resolve, reject) => {
if (writeStream) {
debug('closing');
writeStream.end(resolve);
}
else resolve();
});
}
/**
* update state rotating current file
*
* Implementations normally should not overload this method.
* This method is automatically called from update when size
* of the current file exceeds THRESHOLD_SIZE_NEW_FILE.
*
* @param {Object} properties
* @return {Promise}
**/
rotate(properties) {
return synchronize(this, () => this[rotate$](properties));
}
[rotate$](properties) {
var _writeStream = this[writeStream$];
if (!_writeStream) throw new Error("persistent already closed");
var data = this[validate$](properties, true);
var filename = this.filename;
var tmpfilename = createTempName(filename);
return Promise.all([
new Promise((resolve, reject) => {
var encoder = this[encoder$];
encoder.write(data);
var chunk = encoder.read();
this[byteSize$] = 0;
this[fd$] = null;
var writeStream = this[writeStream$] = createWriteStream(tmpfilename, {flags: 'ax'})
.on('error', reject)
.on('open', fd => this[fd$] = fd);
writeStream.write(chunk, () => {
writeStream.removeListener('error', reject);
this[byteSize$] += chunk.byteLength;
fdatasync(this[fd$]).then(resolve, reject);
});
}),
new Promise((resolve, reject) => {
_writeStream.on('error', reject);
_writeStream.end(resolve);
})
])
.then(() => link(filename, createRotateName(filename)))
.then(() => renameSyncDir(tmpfilename, filename))
.catch(err => {
this[byteSize$] = THRESHOLD_SIZE_NEW_FILE; // in case of a failure next update will rotate
throw err;
})
.then(() => {
this[apply$](data);
this.triggerHistoryRotation();
});
}
/**
* update state
*
* Implementations normally should not overload this method.
*
* @param {Object} properties
* @return {Promise}
**/
update(properties) {
return synchronize(this, () => this[update$](properties));
}
/**
* update state
*
* Implementations normally should not overload this method.
*
* @param {Object} properties
* @return {Promise}
**/
[update$](data) {
var writeStream = this[writeStream$];
if (!writeStream) throw new Error("persistent already closed");
var byteSize = this[byteSize$];
if (byteSize >= THRESHOLD_SIZE_NEW_FILE) {
debug("update: file is large enough to be rotated: %s", byteSize);
return this[rotate$](data);
}
var encoder = this[encoder$];
data = this[validate$](data)
encoder.write(data);
var chunk = encoder.read();
return new Promise((resolve, reject) => {
writeStream.on('error', reject);
writeStream.write(chunk, () => {
this[byteSize$] += chunk.byteLength;
writeStream.removeListener('error', reject);
this[apply$](data);
fdatasync(this[fd$]).then(resolve, reject);
});
}).catch(err => {
this[byteSize$] = THRESHOLD_SIZE_NEW_FILE; // in case of a failure next update will rotate
throw err;
});
}
/**
* apply properties
*
* Implementations may customize this method.
*
* @param {Object} properties
**/
[apply$](properties) {
getOwnPropertyNames(properties).forEach(name => {
var data = this[data$] || (this[data$] = {});
if (properties[name] !== undefined) this[name] = this[data$][name] = properties[name];
});
}
/**
* validate properties
*
* Implementations should customize this method which would throw error on invalid value
* type and remove all properties which values are `undefined`.
* When `withAllProperties` is true implementations must fill undefined properties
* with current values.
*
* @param {Object} properties
* @param {bool} withAllProperties
* @return {Object}
**/
[validate$](properties, withAllProperties) {
var data = {};
getOwnPropertyNames(this.defaultData).forEach(name => {
if (properties[name] !== undefined) data[name] = properties[name];
else if (withAllProperties) data[name] = this[name];
});
return data;
}
}
mixinHistoryRotation(FilePersistence.prototype, debug);
module.exports = FilePersistence;
/*
var msgpack=require('msgpack-lite')
var ben=require('ben')
var obj={alpha:1,beta:'gamma delta epsylon'};
ben(100000, () => msgpack.encode(obj))
var e=new msgpack.Encoder();
ben(100000, () => {e.write(obj); return e.read()})
var FilePersistence = require('./raft/persistence')
var p=new FilePersistence('tmp/persistence.state');p.ready().then(()=>console.log('ok'), console.error)
var ben=require('ben')
ben.async(10000,cb => p.update({currentTerm: p.currentTerm+1}).then(cb,e=>console.error(e)),res=>console.log('\nresult: %s',res))
*/