forked from cilliemalan/node-zookeeper-client-async
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
429 lines (397 loc) · 15.4 KB
/
index.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
const zookeeper = require('node-zookeeper-client');
const State = zookeeper.State;
const ACL = zookeeper.ACL;
const CreateMode = zookeeper.CreateMode;
const Exception = zookeeper.Exception;
// use bluebird promises if available
try {
var bluebird = require('bluebird');
if (bluebird) {
global.Promise = bluebird.Promise;
}
} catch (_) { }
module.exports = Object.assign({}, zookeeper);
/**
* An asynchronous zookeeper transaction. Created by AsyncClient.transaction()
*/
class AsyncTransaction {
constructor(transaction) {
this._transaction = transaction;
}
/**
* Add a create operation with given path, data, acls and mode.
* @param {String} path Path of the node.
* @param {Buffer} data The data buffer, optional, defaults to null.
* @param {ACL[]} acls An array of ACL objects, optional, defaults to ACL.OPEN_ACL_UNSAFE
* @param {CreateMode} mode The creation mode, optional, defaults to CreateMode.PERSISTENT
* @returns {AsyncTransaction}
*/
create(path, data = null, acls = null, mode = null) {
this._transaction.create(path, data, acls, mode);
return this;
}
/**
* Add a set-data operation with the given path, data and optional version.
* @param {string} path Path of the node.
* @param {Buffer} data The data buffer, or null.
* @param {number} version The version of the node, optional, defaults to -1.
* @returns {AsyncTransaction}
*/
setData(path, data, version = -1) {
this._transaction.setData(path, data, version);
return this;
}
/**
* Add a check (existence) operation with given path and optional version.
* @param {*} path Path of the node.
* @param {*} version The version of the node, optional, defaults to -1.
* @returns {AsyncTransaction}
*/
check(path, version = -1) {
this._transaction.check(path, version);
return this;
}
/**
* Add a delete operation with the given path and optional version.
* @param {*} path Path of the node.
* @param {*} version The version of the node, optional, defaults to -1.
* @returns {AsyncTransaction}
*/
remove(path, version = -1) {
this._transaction.remove(path, version);
return this;
}
/**
* Execute the transaction atomically.
* @param {Function} cb The callback function.
*/
commit(cb) {
this._transaction.commit(cb);
}
/**
* Execute the transaction atomically. Resolves when the operation has completed,
* rejects if anything goes wrong.
* @returns {Promise}
*/
commitAsync() {
return new Promise((resolve, reject) => {
this._transaction.commit((e, r) => {
if (e) reject(e);
else resolve(r);
})
});
}
}
/**
* A zookeeper client that has methods that return promises.
* @example
* const zk = require('node-zookeeper-client-async');
*
* const client = zk.createAsyncClient("127.0.0.1:2181");
*
* // connect to the server
* await client.connectAsync();
* console.log('connected!');
*
* // create a node
* const rootPath = await client.mkdirpAsync('/test');
* console.log(`created ${rootPath}`)
*
* // add some ephemeral nodes
* await client.createAsync('/test/counter-', Buffer.from('first'), null, zk.CreateMode.EPHEMERAL_SEQUENTIAL);
* await client.createAsync('/test/counter-', Buffer.from('second'), null, zk.CreateMode.EPHEMERAL_SEQUENTIAL);
*
* // list the nodes
* const nodes = await client.getChildrenAsync('/test');
*
* // print stuff to console
* console.log(`${rootPath} has the children:`)
* await Promise.all(nodes.map(async node => {
* const data = await client.getDataAsync(`/test/${node}`);
* console.log(` ${node}: ${data.data}`);
* }));
*
* // delete everything
* await client.rmrfAsync(rootPath);
*
* // shut down
* await client.closeAsync();
* console.log('disconnected');
*/
class AsyncClient {
/**
* Creates a new AsyncClient for communicating with zookeeper. This object will
* expose all the methods of the underlying zookeeper client, but also expose
* a number of methods that return promises.
* @param {Client} client the underlying zookeeper client created by createClient.
*/
constructor(client) {
this._client = client;
// this object has all the methods of the underlying client.
for (let k in client) {
if (k in AsyncClient.prototype) continue;
const v = client[k];
if (typeof v == 'function') this[k] = v.bind(client);
}
}
/**
* Initiate the connection to the provided server list (ensemble). The client will
* pick an arbitrary server from the list and attempt to connect to it. If the
* establishment of the connection fails, another server will be tried (picked
* randomly) until a connection is established or close method is invoked.
* @returns {Promise} resolves on connect. Rejects with message on failure.
*/
connectAsync() {
return new Promise((resolve, reject) => {
this._client.once('connected', () => resolve());
this._client.once('connectedReadOnly', () => resolve());
this._client.once('authenticationFailed', () => reject('Authentication failed.'));
this._client.once('disconnected', () => reject('Client disconnected before it could open a successful connection.'));
this._client.connect();
});
}
/**
* Close this client. Once the client is closed, its session becomes invalid. All the
* ephemeral nodes in the ZooKeeper server associated with the session will be
* removed. The watchers left on those nodes (and on their parents) will be triggered.
* Resolves true when the client disconnects, resolves false if the client is already
* disconnected.
* @returns {Promise} resolves when disconnected. Does not reject.
*/
closeAsync() {
return new Promise((resolve, reject) => {
if (this._client.getState() == State.DISCONNECTED) {
resolve(false);
} else {
this._client.once('disconnected', () => resolve(true));
this._client.close();
}
});
}
/**
* Create a node with given path, data, acls and mode. Resolves the path name if
* successful, resolves false if the path already exists, and rejects for anything
* else going wrong
* @param {String} path Path of the node.
* @param {Buffer} data The data buffer, optional, defaults to null.
* @param {ACL} acls An array of ACL objects, optional, defaults to ACL.OPEN_ACL_UNSAFE.
* @param {CreateMode} mode The creation mode, optional, defaults to CreateMode.PERSISTENT.
* @returns {Promise} resolves with the path of the created item. Rejects with an error
* if something goes wrong.
*/
createAsync(path, data = null, acls = null, mode = null) {
return new Promise((resolve, reject) => {
this._client.create(path, data, acls, mode, (error, path) => {
if (error) {
if (error.code == Exception.NODE_EXISTS) {
resolve(false);
} else {
reject(error);
}
} else {
resolve(path);
}
});
});
}
/**
* Delete a node with the given path and version. If version is provided and not equal
* to -1, the request will fail when the provided version does not match the server
* version. Resolves true if the node is deleted. Resolves false if the node does
* not exist. Rejects if the node has children, if the version does not match, or
* for any other result.
* @param {String} path Path of the node.
* @param {Number} version The version of the node, optional, defaults to -1.
* @returns {Promise}
*/
removeAsync(path, version = -1) {
return new Promise((resolve, reject) => {
this._client.remove(path, version, e => {
switch (e && e.code) {
case Exception.NO_NODE: resolve(false); break;
case null:
resolve(true);
break;
default:
reject(e);
break;
}
});
});
}
/**
* For the given node path, retrieve the children list and the stat. The children will
* be an unordered list of strings. Resolves the stat object if the node exists,
* resolves null if it does not exist, rejects if anything goes wrong.
* @param {string} path the Path of the node.
* @returns {Promise}
*/
existsAsync(path) {
return new Promise((resolve, reject) => {
this._client.exists(path, null, (e, stat) => {
if (e) {
reject(e);
} else {
resolve(stat);
}
});
});
}
/**
* For the given node path, retrieve the children list and the stat. The children will
* be an unordered list of strings. Resolved the children if the node exists, resolves
* null if the node does not exist. Rejects if anything goes wrong.
* @param {string} path the Path of the node.
* @returns {Promise}
*/
getChildrenAsync(path) {
return new Promise((resolve, reject) => {
this._client.getChildren(path, null, (e, children) => {
if (e) {
if (e.code == Exception.NO_NODE) resolve(null);
else reject(e);
} else {
resolve(children);
}
});
});
}
/**
* Retrieve the data and the stat of the node of the given path. Resolves an object
* containing data as a Buffer object and stat as the stat object. Resolves null
* if the node does not exist. Rejects if anything goes wrong.
* @param {string} path the Path of the node.
* @returns {Promise}
*/
getDataAsync(path) {
return new Promise((resolve, reject) => {
this._client.getData(path, null, (e, data, stat) => {
if (e) {
if (e.code == Exception.NO_NODE) resolve(null);
else reject(e);
} else {
resolve({ data, stat });
}
});
});
}
/**
* Set the data for the node of the given path if such a node exists and the optional
* given version matches the version of the node (if the given version is -1, it
* matches any node's versions). Will resolve the stat of the node if successful. Will
* reject if unsuccessful or if the node does not exist.
* @param {string} path the Path of the node.
* @param {Buffer} data the data to set on the node.
* @param {Number} version the version to set. -1 (default) to match any version.
* @returns {Promise}
*/
setDataAsync(path, data, version = -1) {
return new Promise((resolve, reject) => {
this._client.setData(path, data, version, (e, stat) => {
if (e) {
reject(e);
} else {
resolve(stat);
}
});
});
}
/**
* Retrieve the list of ACL and stat of the node of the given path. Will resolve an
* object with acls as a list of ACL objects and stat as the stat for the node. Will
* resolve null if the node does not exist and will reject if anything goes wrong.
* @param {string} path the Path of the node.
* @returns {Promise}
*/
getACLAsync(path) {
return new Promise((resolve, reject) => {
this._client.getACL(path, (e, acls, stat) => {
if (e) {
if (e.code == Exception.NO_NODE) resolve(null);
else reject(e);
} else {
resolve({ stat, acls });
}
});
});
}
/**
* Set the ACL for the node of the given path if such a node exists and the given
* version (optional) matches the version of the node on the server. (if the given
* version is -1, it matches any versions). Will resolve on success and reject
* if anything goes wrong or the node does not exist.
* @param {string} path the Path of the node.
* @param {ACL[]} acls An array of ACL instances to set on the node.
* @param {Number} version the version to set. -1 (default) to match any version.
*/
setACLAsync(path, acls, version = -1) {
return new Promise((resolve, reject) => {
this._client.setACL(path, acls, version, (e, stat) => {
if (e) {
reject(e);
} else {
resolve(stat);
}
});
});
}
/**
* Create given path in a way similar to mkdir -p. Will resolve the path if the node
* is created and will reject if anything goes wrong.
* @param {string} path the Path of the node.
* @param {Buffer} data The data buffer, optional, defaults to null.
* @param {ACL[]} acls array of ACL objects, optional, defaults to ACL.OPEN_ACL_UNSAFE
* @param {CreateMode} mode The creation mode, optional, defaults to CreateMode.PERSISTENT
* @return {Promise}
*/
mkdirpAsync(path, data = null, acls = null, mode = null) {
return new Promise((resolve, reject) => {
this._client.mkdirp(path, data, acls, mode, (e, path) => {
if (e) {
reject(e);
} else {
resolve(path);
}
});
});
}
/**
* Remove a given path in a way similar to rm -rf. Will resolve if the node is deleted
* or does not exist and reject if anything goes wrong.
* @param {string} path the Path of the node.
* @return {Promise}
*/
rmrfAsync(path) {
return new Promise((resolve, reject) => {
this.getChildrenAsync(path).then(children => {
if (!children || !children.length) {
// no children, ready to remove the node.
this.removeAsync(path).then(resolve, reject);
} else {
var promises = children.map(c => this.rmrfAsync(`${path}/${c}`));
Promise.all(promises).then(() => {
// all children removed, now remove this
this.removeAsync(path).then(resolve, reject);
}, reject);
}
}, reject);
});
}
/**
* Create and return a new Transaction instance which provides a builder object that
* can be used to construct and commit a set of operations atomically.
* @returns {AsyncTransaction}
*/
transaction() {
const transaction = this._client.transaction();
const asyncTransaction = new AsyncTransaction(transaction);
return asyncTransaction;
}
}
function createAsyncClient(connectionString, options = null) {
const clientInternal = zookeeper.createClient(connectionString, options);
return new AsyncClient(clientInternal);
}
module.exports.createAsyncClient = createAsyncClient;
module.exports.AsyncClient = AsyncClient;
module.exports.AsyncTransaction = AsyncTransaction;