Compare commits

...

10 Commits

9 changed files with 246 additions and 80 deletions

View File

@ -27,6 +27,7 @@ Simplistic miniature etcd replacement based on [TinyRaft](https://git.yourcmc.ru
- [/v3/lease/grant](#v3-lease-grant) - [/v3/lease/grant](#v3-lease-grant)
- [/v3/lease/keepalive](#v3-lease-keepalive) - [/v3/lease/keepalive](#v3-lease-keepalive)
- [/v3/lease/revoke or /v3/kv/lease/revoke](#v3-lease-revoke-or-v3-kv-lease-revoke) - [/v3/lease/revoke or /v3/kv/lease/revoke](#v3-lease-revoke-or-v3-kv-lease-revoke)
- [/v3/maintenance/status](#v3-maintenance-status)
- [Websocket-based watch APIs](#websocket-based-watch-apis) - [Websocket-based watch APIs](#websocket-based-watch-apis)
- [HTTP Error Codes](#http-error-codes) - [HTTP Error Codes](#http-error-codes)
@ -104,6 +105,9 @@ Specify &lt;ca&gt; = &lt;cert&gt; if your certificate is self-signed.</dd>
<dt>--ws_keepalive_interval 30000</dt> <dt>--ws_keepalive_interval 30000</dt>
<dd>Client websocket ping (keepalive) interval in milliseconds</dd> <dd>Client websocket ping (keepalive) interval in milliseconds</dd>
<dt>--use_base64 1</dt>
<dd>Use base64 encoding of keys and values, like in etcd (enabled by default).</dd>
</dl> </dl>
### Persistence ### Persistence
@ -450,6 +454,33 @@ type LeaseRevokeResponse = {
} }
``` ```
### /v3/maintenance/status
Request:
```{}```
Response:
```ts
type MaintenanceStatusResponse = {
header: {
member_id?: string,
revision: number,
compact_revision: number,
raft_term?: number,
},
version: string,
cluster?: { [string]: string },
leader?: string,
followers?: string[],
raftTerm?: string,
raftState?: 'leader'|'follower'|'candidate',
// dbSize actually reports process memory usage
dbSize: number,
}
```
### Websocket-based watch APIs ### Websocket-based watch APIs
Client-to-server message format: Client-to-server message format:

View File

@ -332,9 +332,9 @@ class AntiCluster
{ {
if (path == 'kv_txn') if (path == 'kv_txn')
{ {
return ((!data.compare || !data.compare.length) && return (data.compare && data.compare.length ||
(!data.success || !data.success.filter(f => f.request_put || f.requestPut || f.request_delete_range || f.requestDeleteRange).length) && data.success && data.success.filter(f => f.request_put || f.requestPut || f.request_delete_range || f.requestDeleteRange).length ||
(!data.failure || !data.failure.filter(f => f.request_put || f.requestPut || f.request_delete_range || f.requestDeleteRange).length)); data.failure && data.failure.filter(f => f.request_put || f.requestPut || f.request_delete_range || f.requestDeleteRange).length);
} }
return path != 'kv_range'; return path != 'kv_range';
} }

View File

@ -12,10 +12,10 @@ License: Mozilla Public License 2.0 or Vitastor Network Public License 1.1
Usage: Usage:
${process.argv[0]} ${process.argv[1]} \ ${process.argv[0]} ${process.argv[1]} \n\
[--cert ssl.crt] [--key ssl.key] [--port 12379] \ [--cert ssl.crt] [--key ssl.key] [--port 12379] \n\
[--data data.gz] [--persist-filter ./filter.js] [--persist_interval 500] \ [--data data.gz] [--persist-filter ./filter.js] [--persist_interval 500] \n\
[--node_id node1 --cluster_key abcdef --cluster node1=http://localhost:12379,node2=http://localhost:12380,node3=http://localhost:12381] \ [--node_id node1 --cluster_key abcdef --cluster node1=http://localhost:12379,node2=http://localhost:12380,node3=http://localhost:12381] \n\
[other options] [other options]
Supported etcd REST APIs: Supported etcd REST APIs:
@ -43,6 +43,11 @@ HTTP:
Require TLS client certificates signed by <ca> or by default CA to connect. Require TLS client certificates signed by <ca> or by default CA to connect.
--ws_keepalive_interval 30000 --ws_keepalive_interval 30000
Client websocket ping (keepalive) interval in milliseconds Client websocket ping (keepalive) interval in milliseconds
--merge_watches 1
Antietcd merges all watcher events into a single websocket message to provide
more ordering/transaction guarantees. Set to 0 to disable this behaviour.
--use_base64 1
Use base64 encoding of keys and values, like in etcd (enabled by default).
Persistence: Persistence:
@ -105,7 +110,6 @@ function parse()
options[arg.substr(2)] = process.argv[++i]; options[arg.substr(2)] = process.argv[++i];
} }
} }
options['stale_read'] = options['stale_read'] === '1' || options['stale_read'] === 'yes' || options['stale_read'] === 'true';
if (options['persist_filter']) if (options['persist_filter'])
{ {
options['persist_filter'] = require(options['persist_filter'])(options); options['persist_filter'] = require(options['persist_filter'])(options);

View File

@ -15,13 +15,18 @@ const ws = require('ws');
const EtcTree = require('./etctree.js'); const EtcTree = require('./etctree.js');
const AntiPersistence = require('./antipersistence.js'); const AntiPersistence = require('./antipersistence.js');
const AntiCluster = require('./anticluster.js'); const AntiCluster = require('./anticluster.js');
const { runCallbacks, RequestError } = require('./common.js'); const { runCallbacks, de64, b64, RequestError } = require('./common.js');
const VERSION = '1.0.9';
class AntiEtcd extends EventEmitter class AntiEtcd extends EventEmitter
{ {
constructor(cfg) constructor(cfg)
{ {
super(); super();
cfg['merge_watches'] = !('merge_watches' in cfg) || is_true(cfg['merge_watches']);
cfg['stale_read'] = !('stale_read' in cfg) || is_true(cfg['stale_read']);
cfg['use_base64'] = !('use_base64' in cfg) || is_true(cfg['use_base64']);
this.clients = {}; this.clients = {};
this.client_id = 1; this.client_id = 1;
this.etctree = new EtcTree(true); this.etctree = new EtcTree(true);
@ -72,7 +77,7 @@ class AntiEtcd extends EventEmitter
{ {
this.server = http.createServer((req, res) => this._handleRequest(req, res)); this.server = http.createServer((req, res) => this._handleRequest(req, res));
} }
this.wss = new ws.WebSocketServer({ server: this.server }); this.wss = new ws.Server({ server: this.server });
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
this.wss.on('connection', (conn, req) => this._startWebsocket(conn, null)); this.wss.on('connection', (conn, req) => this._startWebsocket(conn, null));
this.server.listen(this.cfg.port || 2379, this.cfg.ip || undefined); this.server.listen(this.cfg.port || 2379, this.cfg.ip || undefined);
@ -118,7 +123,7 @@ class AntiEtcd extends EventEmitter
let done = 0; let done = 0;
await new Promise((allOk, allNo) => await new Promise((allOk, allNo) =>
{ {
res.map(promise => promise.then(res => res.map(promise => promise.then(r =>
{ {
if ((++done) == res.length) if ((++done) == res.length)
allOk(); allOk();
@ -181,13 +186,13 @@ class AntiEtcd extends EventEmitter
if (e instanceof RequestError) if (e instanceof RequestError)
{ {
code = e.code; code = e.code;
reply = e.message; reply = e.message+'\n';
} }
else else
{ {
console.error(e); console.error(e);
code = 500; code = 500;
reply = 'Internal error: '+e.message; reply = 'Internal error: '+e.message+'\n';
} }
} }
try try
@ -329,7 +334,7 @@ class AntiEtcd extends EventEmitter
if ((e instanceof RequestError) && e.code == 404) if ((e instanceof RequestError) && e.code == 404)
{ {
throw new RequestError(404, 'Supported APIs: /v3/kv/txn, /v3/kv/range, /v3/kv/put, /v3/kv/deleterange, '+ throw new RequestError(404, 'Supported APIs: /v3/kv/txn, /v3/kv/range, /v3/kv/put, /v3/kv/deleterange, '+
'/v3/lease/grant, /v3/lease/revoke, /v3/kv/lease/revoke, /v3/lease/keepalive'); '/v3/lease/grant, /v3/lease/revoke, /v3/kv/lease/revoke, /v3/lease/keepalive, /v3/maintenance/status');
} }
else else
{ {
@ -345,7 +350,7 @@ class AntiEtcd extends EventEmitter
{ {
throw new RequestError(502, 'Server is stopping'); throw new RequestError(502, 'Server is stopping');
} }
if (path !== 'dump' && this.cluster) if (this.cluster && path !== 'dump' && path != 'maintenance_status')
{ {
const res = await this.cluster.checkRaftState( const res = await this.cluster.checkRaftState(
path, path,
@ -409,9 +414,9 @@ class AntiEtcd extends EventEmitter
} }
// public watch API // public watch API
async create_watch(params, callback) async create_watch(params, callback, stream_id)
{ {
const watch = this.etctree.api_create_watch({ ...params, watch_id: null }, callback); const watch = this.etctree.api_create_watch(this._encodeWatch(params), (msg) => callback(this._encodeMsg(msg)), stream_id);
if (!watch.created) if (!watch.created)
{ {
throw new RequestError(400, 'Requested watch revision is compacted', { compact_revision: watch.compact_revision }); throw new RequestError(400, 'Requested watch revision is compacted', { compact_revision: watch.compact_revision });
@ -428,31 +433,71 @@ class AntiEtcd extends EventEmitter
{ {
throw new RequestError(400, 'Watch not found'); throw new RequestError(400, 'Watch not found');
} }
this.etctree.api_cancel_watch({ watch_id: mapped_id }); this.etctree.api_cancel_watch(mapped_id);
delete this.api_watches[watch_id]; delete this.api_watches[watch_id];
} }
// internal handlers // internal handlers
async _handle_kv_txn(data) async _handle_kv_txn(data)
{ {
return await this.etctree.api_txn(data); if (this.cfg.use_base64)
{
for (const item of data.compare||[])
{
if (item.key != null)
item.key = de64(item.key);
}
for (const items of [ data.success, data.failure ])
{
for (const item of items||[])
{
const req = item.request_range || item.requestRange ||
item.request_put || item.requestPut ||
item.request_delete_range || item.requestDeleteRange;
if (req.key != null)
req.key = de64(req.key);
if (req.range_end != null)
req.range_end = de64(req.range_end);
if (req.value != null)
req.value = de64(req.value);
}
}
}
const result = await this.etctree.api_txn(data);
if (this.cfg.use_base64)
{
for (const item of result.responses||[])
{
if (item.response_range)
{
for (const kv of item.response_range.kvs)
{
if (kv.key != null)
kv.key = b64(kv.key);
if (kv.value != null)
kv.value = b64(kv.value);
}
}
}
}
return result;
} }
async _handle_kv_range(data) async _handle_kv_range(data)
{ {
const r = await this.etctree.api_txn({ success: [ { request_range: data } ] }); const r = await this._handle_kv_txn({ success: [ { request_range: data } ] });
return { header: r.header, ...r.responses[0].response_range }; return { header: r.header, ...r.responses[0].response_range };
} }
async _handle_kv_put(data) async _handle_kv_put(data)
{ {
const r = await this.etctree.api_txn({ success: [ { request_put: data } ] }); const r = await this._handle_kv_txn({ success: [ { request_put: data } ] });
return { header: r.header, ...r.responses[0].response_put }; return { header: r.header, ...r.responses[0].response_put };
} }
async _handle_kv_deleterange(data) async _handle_kv_deleterange(data)
{ {
const r = await this.etctree.api_txn({ success: [ { request_delete_range: data } ] }); const r = await this._handle_kv_txn({ success: [ { request_delete_range: data } ] });
return { header: r.header, ...r.responses[0].response_delete_range }; return { header: r.header, ...r.responses[0].response_delete_range };
} }
@ -476,6 +521,26 @@ class AntiEtcd extends EventEmitter
return this.etctree.api_keepalive_lease(data); return this.etctree.api_keepalive_lease(data);
} }
_handle_maintenance_status(/*data*/)
{
const raft = this.cluster && this.cluster.raft;
return {
header: {
member_id: this.cfg.node_id || undefined,
revision: this.etctree.mod_revision,
compact_revision: this.etctree.compact_revision || 0,
raft_term: raft && raft.term || undefined,
},
version: 'antietcd '+AntiEtcd.VERSION,
cluster: this.cfg.cluster || undefined,
leader: raft && raft.leader || undefined,
followers: raft && raft.followers || undefined,
raftTerm: raft && raft.term || undefined,
raftState: raft && raft.state || undefined,
dbSize: process.memoryUsage().heapUsed,
};
}
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
_handle_dump(data) _handle_dump(data)
{ {
@ -494,8 +559,9 @@ class AntiEtcd extends EventEmitter
const create_request = msg.create_request; const create_request = msg.create_request;
if (!create_request.watch_id || !client.watches[create_request.watch_id]) if (!create_request.watch_id || !client.watches[create_request.watch_id])
{ {
client.send_cb = client.send_cb || (msg => socket.send(JSON.stringify(this._encodeMsg(msg))));
const watch = this.etctree.api_create_watch( const watch = this.etctree.api_create_watch(
{ ...create_request, watch_id: null }, (msg) => socket.send(JSON.stringify(msg)) this._encodeWatch(create_request), client.send_cb, (this.cfg.merge_watches ? 'C'+client_id : null)
); );
if (!watch.created) if (!watch.created)
{ {
@ -514,7 +580,7 @@ class AntiEtcd extends EventEmitter
const mapped_id = client.watches[msg.cancel_request.watch_id]; const mapped_id = client.watches[msg.cancel_request.watch_id];
if (mapped_id) if (mapped_id)
{ {
this.etctree.api_cancel_watch({ watch_id: mapped_id }); this.etctree.api_cancel_watch(mapped_id);
delete client.watches[msg.cancel_request.watch_id]; delete client.watches[msg.cancel_request.watch_id];
socket.send(JSON.stringify({ result: { header: { revision: this.etctree.mod_revision }, watch_id: msg.cancel_request.watch_id, canceled: true } })); socket.send(JSON.stringify({ result: { header: { revision: this.etctree.mod_revision }, watch_id: msg.cancel_request.watch_id, canceled: true } }));
} }
@ -533,6 +599,35 @@ class AntiEtcd extends EventEmitter
} }
} }
_encodeWatch(create_request)
{
const req = { ...create_request, watch_id: null };
if (this.cfg.use_base64)
{
if (req.key != null)
req.key = de64(req.key);
if (req.range_end != null)
req.range_end = de64(req.range_end);
}
return req;
}
_encodeMsg(msg)
{
if (this.cfg.use_base64 && msg.result && msg.result.events)
{
return { ...msg, result: { ...msg.result, events: msg.result.events.map(ev => ({
...ev,
kv: !ev.kv ? ev.kv : {
...ev.kv,
key: b64(ev.kv.key),
value: b64(ev.kv.value),
},
})) } };
}
return msg;
}
_unsubscribeClient(client_id) _unsubscribeClient(client_id)
{ {
if (!this.clients[client_id]) if (!this.clients[client_id])
@ -542,11 +637,18 @@ class AntiEtcd extends EventEmitter
for (const watch_id in this.clients[client_id].watches) for (const watch_id in this.clients[client_id].watches)
{ {
const mapped_id = this.clients[client_id].watches[watch_id]; const mapped_id = this.clients[client_id].watches[watch_id];
this.etctree.api_cancel_watch({ watch_id: mapped_id }); this.etctree.api_cancel_watch(mapped_id);
} }
} }
} }
function is_true(s)
{
return s === true || s === 1 || s === '1' || s === 'yes' || s === 'true' || s === 'on';
}
AntiEtcd.RequestError = RequestError; AntiEtcd.RequestError = RequestError;
AntiEtcd.VERSION = VERSION;
module.exports = AntiEtcd; module.exports = AntiEtcd;

View File

@ -8,7 +8,7 @@ const zlib = require('zlib');
const stableStringify = require('./stable-stringify.js'); const stableStringify = require('./stable-stringify.js');
const EtcTree = require('./etctree.js'); const EtcTree = require('./etctree.js');
const { de64, runCallbacks } = require('./common.js'); const { runCallbacks } = require('./common.js');
class AntiPersistence class AntiPersistence
{ {
@ -60,20 +60,18 @@ class AntiPersistence
if (ev.lease) if (ev.lease)
{ {
// Values with lease are never persisted // Values with lease are never persisted
const key = de64(ev.key); if (this.prev_value[ev.key] !== undefined)
if (this.prev_value[key] !== undefined)
{ {
delete this.prev_value[key]; delete this.prev_value[ev.key];
changed = true; changed = true;
} }
} }
else else
{ {
const key = de64(ev.key); const filtered = this.cfg.persist_filter(ev.key, ev.value == null ? undefined : ev.value);
const filtered = this.cfg.persist_filter(key, ev.value == null ? undefined : de64(ev.value)); if (!EtcTree.eq(filtered, this.prev_value[ev.key]))
if (!EtcTree.eq(filtered, this.prev_value[key]))
{ {
this.prev_value[key] = filtered; this.prev_value[ev.key] = filtered;
changed = true; changed = true;
} }
} }

View File

@ -19,6 +19,13 @@ function de64(k)
return Buffer.from(k, 'base64').toString(); return Buffer.from(k, 'base64').toString();
} }
function b64(k)
{
if (k == null) // null or undefined
return k;
return Buffer.from(k).toString('base64');
}
function runCallbacks(obj, key, new_value) function runCallbacks(obj, key, new_value)
{ {
const cbs = obj[key]; const cbs = obj[key];
@ -35,5 +42,6 @@ function runCallbacks(obj, key, new_value)
module.exports = { module.exports = {
RequestError, RequestError,
de64, de64,
b64,
runCallbacks, runCallbacks,
}; };

View File

@ -19,7 +19,7 @@ const { RequestError } = require('./common.js');
class EtcTree class EtcTree
{ {
constructor(use_base64) constructor()
{ {
this.state = {}; this.state = {};
this.leases = {}; this.leases = {};
@ -27,7 +27,6 @@ class EtcTree
this.watcher_id = 0; this.watcher_id = 0;
this.mod_revision = 0; this.mod_revision = 0;
this.compact_revision = 0; this.compact_revision = 0;
this.use_base64 = use_base64;
this.replicate = null; this.replicate = null;
this.paused = false; this.paused = false;
this.active_immediate = []; this.active_immediate = [];
@ -51,23 +50,9 @@ class EtcTree
this.replicate = replicate; this.replicate = replicate;
} }
de64(k)
{
if (k == null) // null or undefined
return k;
return this.use_base64 ? Buffer.from(k, 'base64').toString() : k;
}
b64(k)
{
if (k == null) // null or undefined
return k;
return this.use_base64 ? Buffer.from(k).toString('base64') : k;
}
_check(chk) _check(chk)
{ {
const parts = this._key_parts(this.de64(chk.key)); const parts = this._key_parts(chk.key);
const { cur } = this._get_subtree(parts, false, false); const { cur } = this._get_subtree(parts, false, false);
let check_value, ref_value; let check_value, ref_value;
if (chk.target === 'MOD') if (chk.target === 'MOD')
@ -118,8 +103,8 @@ class EtcTree
_get_range(req) _get_range(req)
{ {
const key = this.de64(req.key); const key = req.key;
const end = this.de64(req.range_end); const end = req.range_end;
if (end != null && (key !== '' && end !== '') && (key[key.length-1] != '/' || end[end.length-1] != '0' || if (end != null && (key !== '' && end !== '') && (key[key.length-1] != '/' || end[end.length-1] != '0' ||
end.substr(0, end.length-1) !== key.substr(0, key.length-1))) end.substr(0, end.length-1) !== key.substr(0, key.length-1)))
{ {
@ -279,7 +264,7 @@ class EtcTree
{ {
cur_old.value = cur_new.value; cur_old.value = cur_new.value;
const key_watchers = (cur_old.key_watchers ? [ ...watchers, ...(cur_old.key_watchers||[]) ] : watchers); const key_watchers = (cur_old.key_watchers ? [ ...watchers, ...(cur_old.key_watchers||[]) ] : watchers);
const notify = { watchers: key_watchers, key: this.b64(key), value: this.b64(cur_new.value), mod_revision: cur_new.mod_revision }; const notify = { watchers: key_watchers, key, value: cur_new.value, mod_revision: cur_new.mod_revision };
if (cur_new.lease) if (cur_new.lease)
{ {
notify.lease = cur_new.lease; notify.lease = cur_new.lease;
@ -444,7 +429,12 @@ class EtcTree
} }
for (const key in this.leases[id].keys) for (const key in this.leases[id].keys)
{ {
this._delete_range({ key: this.use_base64 ? this.b64(key) : key }, next_revision, notifications); this._delete_range({ key }, next_revision, notifications);
}
if (this.leases[id].timer_id)
{
clearTimeout(this.leases[id].timer_id);
this.leases[id].timer_id = null;
} }
delete this.leases[id]; delete this.leases[id];
} }
@ -539,7 +529,7 @@ class EtcTree
} }
} }
api_create_watch(req, send) api_create_watch(req, send, stream_id)
{ {
const { parts, all } = this._get_range(req); const { parts, all } = this._get_range(req);
if (req.start_revision && this.compact_revision && this.compact_revision > req.start_revision) if (req.start_revision && this.compact_revision && this.compact_revision > req.start_revision)
@ -561,6 +551,7 @@ class EtcTree
this.watchers[watch_id] = { this.watchers[watch_id] = {
paths: [], paths: [],
send, send,
stream_id,
}; };
} }
this.watchers[watch_id].paths.push(parts); this.watchers[watch_id].paths.push(parts);
@ -597,9 +588,9 @@ class EtcTree
{ {
const ev = { const ev = {
type: cur.value == null ? 'DELETE' : 'PUT', type: cur.value == null ? 'DELETE' : 'PUT',
kv: cur.value == null ? { key: this.b64(prefix === null ? '' : prefix) } : { kv: cur.value == null ? { key: (prefix === null ? '' : prefix) } : {
key: this.b64(prefix), key: prefix,
value: this.b64(cur.value), value: cur.value,
mod_revision: cur.mod_revision, mod_revision: cur.mod_revision,
}, },
}; };
@ -662,15 +653,15 @@ class EtcTree
{ {
if (this.watchers[wid]) if (this.watchers[wid])
{ {
by_watcher[wid] = by_watcher[wid] || { header: { revision: this.mod_revision }, events: {} }; const stream_id = this.watchers[wid].stream_id || wid;
by_watcher[wid].events[notif.key] = conv; by_watcher[stream_id] = by_watcher[stream_id] || { send: this.watchers[wid].send, events: {} };
by_watcher[stream_id].events[notif.key] = conv;
} }
} }
} }
for (const wid in by_watcher) for (const stream_id in by_watcher)
{ {
by_watcher[wid].events = Object.values(by_watcher[wid].events); by_watcher[stream_id].send({ result: { header: { revision: this.mod_revision }, events: Object.values(by_watcher[stream_id].events) } });
this.watchers[wid].send({ result: by_watcher[wid] });
} }
} }
@ -727,9 +718,9 @@ class EtcTree
_put(request_put, cur_revision, notifications) _put(request_put, cur_revision, notifications)
{ {
// FIXME: prev_kv, ignore_value(?), ignore_lease(?) // FIXME: prev_kv, ignore_value(?), ignore_lease(?)
const parts = this._key_parts(this.de64(request_put.key)); const parts = this._key_parts(request_put.key);
const key = parts.join('/'); const key = parts.join('/');
const value = this.de64(request_put.value); const value = request_put.value;
const { cur, watchers } = this._get_subtree(parts, true, true); const { cur, watchers } = this._get_subtree(parts, true, true);
if (cur.key_watchers) if (cur.key_watchers)
{ {
@ -762,7 +753,7 @@ class EtcTree
cur.create_revision = cur_revision; cur.create_revision = cur_revision;
} }
cur.value = value; cur.value = value;
const notify = { watchers, key: this.b64(key), value: this.b64(value), mod_revision: cur.mod_revision }; const notify = { watchers, key, value, mod_revision: cur.mod_revision };
if (cur.lease) if (cur.lease)
{ {
notify.lease = cur.lease; notify.lease = cur.lease;
@ -793,10 +784,10 @@ class EtcTree
} }
if (cur.value != null) if (cur.value != null)
{ {
const item = { key: this.b64(prefix === null ? '' : prefix) }; const item = { key: (prefix === null ? '' : prefix) };
if (!req.keys_only) if (!req.keys_only)
{ {
item.value = this.b64(cur.value); item.value = cur.value;
item.mod_revision = cur.mod_revision; item.mod_revision = cur.mod_revision;
//item.create_revision = cur.create_revision; //item.create_revision = cur.create_revision;
//item.version = cur.version; //item.version = cur.version;
@ -833,7 +824,7 @@ class EtcTree
this.mod_revision = cur_revision; this.mod_revision = cur_revision;
notifications.push({ notifications.push({
watchers: cur.key_watchers ? [ ...watchers, ...cur.key_watchers ] : watchers, watchers: cur.key_watchers ? [ ...watchers, ...cur.key_watchers ] : watchers,
key: this.b64(prefix === null ? '' : prefix), key: (prefix === null ? '' : prefix),
mod_revision: cur_revision, mod_revision: cur_revision,
}); });
} }

View File

@ -64,7 +64,7 @@ tests['read/write'] = async () =>
); );
expect( expect(
t.dump(false), t.dump(false),
{"state":{"children":{"":{"children":{"vitastor":{"children":{"config":{"children":{"global":{"version":2,"mod_revision":2,"create_revision":1,"value":{"hello":"world2"}}}}}}}}}},"mod_revision":2,"leases":{}} {"state":{"children":{"":{"children":{"vitastor":{"children":{"config":{"children":{"global":{"version":2,"mod_revision":2,"create_revision":1,"value":{"hello":"world2"}}}}}}}}}},"mod_revision":2,"compact_revision":0,"leases":{}}
); );
t.destroy(); t.destroy();
}; };
@ -80,7 +80,7 @@ tests['watch'] = async () =>
); );
expect( expect(
t.api_create_watch({ watch_id: 1, key: '/vitastor/', range_end: '/vitastor0' }, send), t.api_create_watch({ watch_id: 1, key: '/vitastor/', range_end: '/vitastor0' }, send),
{ watch_id: 1, created: true } { header: { revision: 1 }, watch_id: 1, created: true }
); );
expect(sent, []); expect(sent, []);
expect( expect(
@ -91,6 +91,38 @@ tests['watch'] = async () =>
t.destroy(); t.destroy();
}; };
tests['merge watch'] = async () =>
{
const t = new EtcTree();
const sent = [];
const send = (event) => sent.push(event);
expect(
await t.api_txn({ success: [ { request_put: { key: '/vitastor//config/pgs', value: { items: {} } } } ] }),
{ header: { revision: 1 }, succeeded: true, responses: [ { response_put: {} } ] }
);
expect(
t.api_create_watch({ watch_id: 1, key: '/vitastor/config/pgs' }, send, 'X1' /* stream_id */),
{ header: { revision: 1 }, watch_id: 1, created: true }
);
expect(
t.api_create_watch({ watch_id: 2, key: '/vitastor/pg/history/', range_end: '/vitastor/pg/history0' }, send, 'X1' /* stream_id */),
{ header: { revision: 1 }, watch_id: 2, created: true },
);
expect(sent, []);
expect(
await t.api_txn({ success: [
{ request_put: { key: '/vitastor/config/pgs', value: { items: { 1: { 1: { osd_set: [ 1, 2, 3 ] } } } } } },
{ request_put: { key: '/vitastor/pg/history/1/1', value: { all_peers: [ 1, 2, 3, 4, 5 ] } } },
] }),
{ header: { revision: 2 }, succeeded: true, responses: [ { response_put: {} }, { response_put: {} } ] }
);
expect(sent, [ { result: { header: { revision: 2 }, events: [
{ type: 'PUT', kv: { key: '/vitastor/config/pgs', value: { items: { 1: { 1: { osd_set: [ 1, 2, 3 ] } } } }, mod_revision: 2 } },
{ type: 'PUT', kv: { key: '/vitastor/pg/history/1/1', value: { all_peers: [ 1, 2, 3, 4, 5 ] }, mod_revision: 2 } },
] } } ]);
t.destroy();
};
tests['lease'] = async () => tests['lease'] = async () =>
{ {
const t = new EtcTree(); const t = new EtcTree();
@ -100,18 +132,18 @@ tests['lease'] = async () =>
expect(leaseID != null, true); expect(leaseID != null, true);
expect( expect(
await t.api_txn({ success: [ { request_put: { key: '/vitastor/osd/state/1', lease: leaseID, value: { ip: '1.2.3.4' } } } ] }), await t.api_txn({ success: [ { request_put: { key: '/vitastor/osd/state/1', lease: leaseID, value: { ip: '1.2.3.4' } } } ] }),
{ header: { revision: 1 }, succeeded: true, responses: [ { response_put: {} } ] } { header: { revision: 2 }, succeeded: true, responses: [ { response_put: {} } ] }
); );
expect( expect(
t.api_create_watch({ watch_id: 1, key: '/vitastor/', range_end: '/vitastor0' }, send), t.api_create_watch({ watch_id: 1, key: '/vitastor/', range_end: '/vitastor0' }, send),
{ watch_id: 1, created: true } { header: { revision: 2 }, watch_id: 1, created: true }
); );
expect(sent, []); expect(sent, []);
const dump = t.dump(false); const dump = t.dump(false);
const expires = dump.leases[leaseID].expires; const expires = dump.leases[leaseID].expires;
expect(dump, {"state":{"children":{"":{"children":{"vitastor":{"children":{"osd":{"children":{"state":{"children":{"1":{"lease":leaseID,"version":1,"mod_revision":1,"create_revision":1,"value":{"ip":"1.2.3.4"}}}}}}}}}}}},"mod_revision":1,"leases":{[leaseID]:{"ttl":0.5,"expires":expires}}}); expect(dump, {"state":{"children":{"":{"children":{"vitastor":{"children":{"osd":{"children":{"state":{"children":{"1":{"lease":leaseID,"version":1,"mod_revision":2,"create_revision":2,"value":{"ip":"1.2.3.4"}}}}}}}}}}}},"mod_revision":2,"compact_revision":0,"leases":{[leaseID]:{"ttl":0.5,"expires":expires}}});
await new Promise(ok => setTimeout(ok, 600)); await new Promise(ok => setTimeout(ok, 600));
expect(sent, [ { result: { header: { revision: 2 }, events: [ { type: 'DELETE', kv: { key: '/vitastor/osd/state/1', mod_revision: 2 } } ] } } ]); expect(sent, [ { result: { header: { revision: 3 }, events: [ { type: 'DELETE', kv: { key: '/vitastor/osd/state/1', mod_revision: 3 } } ] } } ]);
t.pause_leases(); t.pause_leases();
t.load(dump); t.load(dump);
expect(t.dump(false), dump); expect(t.dump(false), dump);
@ -131,7 +163,7 @@ tests['update'] = async () =>
expect(leaseID != null, true); expect(leaseID != null, true);
expect( expect(
await t1.api_txn({ success: [ { request_put: { key: '/vitastor/osd/state/1', lease: leaseID, value: { ip: '1.2.3.4' } } } ] }), await t1.api_txn({ success: [ { request_put: { key: '/vitastor/osd/state/1', lease: leaseID, value: { ip: '1.2.3.4' } } } ] }),
{ header: { revision: 1 }, succeeded: true, responses: [ { response_put: {} } ] } { header: { revision: 2 }, succeeded: true, responses: [ { response_put: {} } ] }
); );
expect( expect(
await t2.api_txn({ success: [ { request_put: { key: '/vitastor/osd/state/1', value: { ip: '1.2.3.6' } } } ] }), await t2.api_txn({ success: [ { request_put: { key: '/vitastor/osd/state/1', value: { ip: '1.2.3.6' } } } ] }),
@ -139,15 +171,15 @@ tests['update'] = async () =>
); );
expect( expect(
await t1.api_txn({ success: [ { request_put: { key: '/vitastor/osd/state/1', lease: leaseID, value: { ip: '1.2.3.5' } } } ] }), await t1.api_txn({ success: [ { request_put: { key: '/vitastor/osd/state/1', lease: leaseID, value: { ip: '1.2.3.5' } } } ] }),
{ header: { revision: 2 }, succeeded: true, responses: [ { response_put: {} } ] } { header: { revision: 3 }, succeeded: true, responses: [ { response_put: {} } ] }
); );
let dump2 = t2.dump(); let dump2 = t2.dump();
t2.load(t1.dump(), true); t2.load(t1.dump(), true);
t1.load(dump2, true); t1.load(dump2, true);
let dump = t2.dump(false); let dump = t2.dump(false);
let expires = dump.leases[leaseID].expires; let expires = dump.leases[leaseID].expires;
expect(dump, {"state":{"children":{"":{"children":{"vitastor":{"children":{"osd":{"children":{"state":{"children":{"1":{"lease":leaseID,"version":2,"mod_revision":2,"create_revision":1,"value":{"ip":"1.2.3.5"}}}}}}}}}}}},"mod_revision":2,"leases":{[leaseID]:{"ttl":0.5,"expires":expires}}}); expect(dump, {"state":{"children":{"":{"children":{"vitastor":{"children":{"osd":{"children":{"state":{"children":{"1":{"lease":leaseID,"version":2,"mod_revision":3,"create_revision":2,"value":{"ip":"1.2.3.5"}}}}}}}}}}}},"mod_revision":3,"compact_revision":0,"leases":{[leaseID]:{"ttl":0.5,"expires":expires}}});
expect(t1.dump(false), {"state":{"children":{"":{"children":{"vitastor":{"children":{"osd":{"children":{"state":{"children":{"1":{"lease":leaseID,"version":2,"mod_revision":2,"create_revision":1,"value":{"ip":"1.2.3.5"}}}}}}}}}}}},"mod_revision":2,"leases":{[leaseID]:{"ttl":0.5,"expires":expires}}}); expect(t1.dump(false), {"state":{"children":{"":{"children":{"vitastor":{"children":{"osd":{"children":{"state":{"children":{"1":{"lease":leaseID,"version":2,"mod_revision":3,"create_revision":2,"value":{"ip":"1.2.3.5"}}}}}}}}}}}},"mod_revision":3,"compact_revision":0,"leases":{[leaseID]:{"ttl":0.5,"expires":expires}}});
t1.destroy(); t1.destroy();
t2.destroy(); t2.destroy();
}; };

View File

@ -1,6 +1,6 @@
{ {
"name": "antietcd", "name": "antietcd",
"version": "1.0.4", "version": "1.0.9",
"description": "Simplistic etcd replacement based on TinyRaft", "description": "Simplistic etcd replacement based on TinyRaft",
"main": "antietcd.js", "main": "antietcd.js",
"scripts": { "scripts": {