Repository: stianeikeland/node-etcd
Branch: master
Commit: 1bb5f4da071e
Files: 12
Total size: 52.5 KB
Directory structure:
gitextract_xgjntaex/
├── .gitignore
├── .npmignore
├── .travis.yml
├── LICENSE
├── README.md
├── package.json
├── src/
│ ├── client.coffee
│ ├── index.coffee
│ └── watcher.coffee
└── test/
├── client.coffee
├── index.coffee
└── watcher.coffee
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
lib/
node_modules/
.DS_Store
temp/
.nyc_output
coverage
================================================
FILE: .npmignore
================================================
node_modules/
npm-debug.log
.DS_Store
.gitignore
.travis.yml
temp/
.nyc_output
coverage
================================================
FILE: .travis.yml
================================================
language: node_js
sudo: false
node_js:
- "10"
- "9"
- "8"
- "7"
- "6"
env:
- CXX="g++-4.8" CC="gcc-4.8"
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-4.8
- g++-4.8
- clang
================================================
FILE: LICENSE
================================================
Copyright (c) 2013, node-etcd authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the authors nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: README.md
================================================
# node-etcd
A nodejs library for [ETCD v2](https://coreos.com/etcd/docs/latest/v2/api.html), written in coffee-script.
[](https://travis-ci.org/stianeikeland/node-etcd)
[](https://www.npmjs.com/package/node-etcd)
## Install
For nodes >= 6.x:
```
$ npm install node-etcd
```
For nodes 4.x <= node < 6.x:
```
$ npm install node-etcd@6
```
For 0.10.x <= nodejs <= 4.x and iojs:
```
$ npm install node-etcd@5.1.0
```
For nodejs == 0.8:
```
$ npm install node-etcd@3.0.2
```
## Changes
- 7.0.0
- Fixing vulnerabilities
- Drop support for nodejs version 4 &4
- 6.0.0
- Migrate from underscore to lodash for performance / @derektbrown
- Updated package versions / @derektbrown
- Update deasync call for newer node versions / @derektbrown
- Add istanbul coverage reporting / @derektbrown
- 5.1.0
- Upgrade deasync dep (caused build problems on newer node) #67 / @jefflembeck
- Upgrade request dep (security vulnerability) #71 / @esatterwhite
- Sync functions no longer mutate input opts.
- 5.0.3
- Fix bug #56 (exception when calling mkdir with no options or callback)
- 5.0.2
- Update deasync dependency, possible fix for #47.
- 5.0.1
- Was forced to publish 5.0.0 as 5.0.1 because of previous beta tag.
- 5.0.0
- Supports basic auth, timeout, etc. See options.
- **Breaking**: Constructor changes (see below)
- **Breaking**: Must provide https url to use https
- **Breaking**: Uses new default port 2379.
- 4.2.1
- Newer deasync fixes issues with iojs 3.3.0 and nodejs 4.0.0.
- 4.1.0
- Bumps [request](https://github.com/request/request) library version to
v2.60.0, this solves an issue with HTTP proxies. `HTTP_PROXY` and `NO_PROXY`
env variables should now work as expected for all requests. See issue #40
- 4.0.2
- 307 redirects from etcd 0.4.x clusters when using SSL didn't work properly
because of a change in the underlying request library. See issue #39
- 4.0.1
- Minor fixes for syncronous operations, better handling of server failure.
- 4.0.0
- Adds support for synchronous operations (@brockwood) - See
[Synchronous Operations](#synchronous-operations).
- Adds support for iojs.
- Drops support for nodejs 0.8 (use v3.x.x).
- Upgrade dependencies.
- 3.0.2 - Handle cluster leader election periods better (etcd will disconnect us
and reject new connections until a new leader is chosen). The client will now
retry 3 times with exp backoff if it believes a cluster election is in
progress. Retry count is controllable via the `{ maxRetries: x }` option for a
request. (npm failed on me and I had to publish as 3.0.2)
- 3.0.0 - Added cluster support, library now accepts a list of servers to
connect to, see constructor changes below. All requests now return a
cancellation token, meaning you can cancel requests by calling .cancel() or
.abort(). This release might break something if you've previously depended on
the leaky abstraction to the request library (request object from request
library was returned on all api calls - this has been replaced by the
cancellation token - the current request is still available under .req on the
token if you really need it.).
- 2.1.5 - Watcher: try to resync if etcd reports cleared index
- 2.1.4 - Don't wait before reconnecting if Etcd server times out our watcher.
- 2.1.3 - Etcd sends an empty response on timeout in recent versions. Parsing
the empty message caused watcher to emit error. Now it reconnects instead.
- 2.1.2 - Exponential backoff (retry), fix spinning reconnect on error. (@ptte)
- 2.1.1 - Increase request pool.maxSockets to 100
- 2.1.0 - Use proper error objects instead of strings for errors.
- 2.0.10 - Fix error in documentation
- 2.0.9 - Added .post() alias of .create(). Added .compareAndDelete() (for etcd v0.3.0)
- 2.0.8 - Watchers can be canceled. In-order keys using #create(). Raw requests using #raw().
- 2.0.7 - Avoid calling callback if callback not given.
- 2.0.6 - Refactoring, fix responsehandler error.
- 2.0.5 - Undo use of 'x-etcd-index', this refers to global state.
- 2.0.4 - Use 'x-etcd-index' for index when watching a key.
- 2.0.3 - Watcher supports options. Watcher emits etcd action type.
- 2.0.2 - Mkdir and rmdir. Fix watcher for v2 api.
- 2.0.1 - Watch, delete and stats now use new v2 api. Added testAndSet convenience method.
- 2.0.0 - Basic support for etcd protocol v2. set, get, del now supports options.
- 0.6.1 - Fixes issue #10, missing response caused error when server connection failed / server responded incorrectly.
- 0.6.0 - Watcher now emits 'error' on invalid responses.
## Basic usage
```javascript
var Etcd = require('node-etcd');
var etcd = new Etcd();
etcd.set("key", "value");
etcd.get("key", console.log);
```
Callbacks follows the default (error, result) nodejs convention:
```javascript
function callback(err, res) {
console.log("Error: ", err);
console.log("Return: ", res);
}
etcd.get("key", callback);
// Error: null
// Return: { action: 'get', node: { key: '/key', value: 'value', modifiedIndex: 4, createdIndex: 4 } }
```
## Methods
### Etcd(hosts = ['127.0.0.1:2379'], [options])
Create a new etcd client for a single host etcd setup
```javascript
etcd = new Etcd();
etcd = new Etcd("127.0.0.1:2379");
etcd = new Etcd("http://127.0.0.1:2379");
etcd = new Etcd("https://127.0.0.1:2379");
etcd = new Etcd(["http://127.0.0.1:2379"]);
```
### Etcd(hosts, [options])
Create a new etcd client for a clustered etcd setup. Client will connect to
servers in random order. On failure it will try the next server. When all
servers have failed it will callback with error. If it suspects the cluster is
in leader election mode it will retry up to 3 times with exp backoff. Number of
retries can be controlled by adding `{ maxRetries: x }` as an option to requests.
```javascript
etcd = new Etcd(['127.0.0.1:2379','192.168.1.1:2379']);
etcd = new Etcd(['http://127.0.0.1:2379','http://192.168.1.1:2379']);
```
### .set(key, value = null, [options], [callback])
Set key to value, or create key/directory.
```javascript
etcd.set("key");
etcd.set("key", "value");
etcd.set("key", "value", console.log);
etcd.set("key", "value", { ttl: 60 }, console.log);
etcd.set("key", "value", { maxRetries: 3 }, console.log);
```
Available options include:
- `ttl` (time to live in seconds)
- `prevValue` (previous value, for compare and swap)
- `prevExist` (existance test, for compare and swap)
- `prevIndex` (previous index, for compare and swap)
Will create a directory when used without value (value=null): `etcd.set("directory/");`
### .compareAndSwap(key, value, oldvalue, [options], [callback])
Convenience method for test and set (set with {prevValue: oldvalue})
```javascript
etcd.compareAndSwap("key", "newvalue", "oldvalue");
etcd.compareAndSwap("key", "newValue", "oldValue", options, console.log);
```
Alias: `.testAndSet()`
### .get(key, [options], [callback])
Get a key or path.
```javascript
etcd.get("key", console.log);
etcd.get("key", { recursive: true }, console.log);
```
Available options include:
- `recursive` (bool, list all values in directory recursively)
- `wait` (bool, wait for changes to key)
- `waitIndex` (wait for changes after given index)
### .del(key, [options], [callback])
Delete a key or path
```javascript
etcd.del("key");
etcd.del("key", console.log);
etcd.del("key/", { recursive: true }, console.log);
```
Available options include:
- `recursive` (bool, delete recursively)
Alias: `.delete()`
### .compareAndDelete(key, oldvalue, [options], [callback])
Convenience method for test and delete (delete with {prevValue: oldvalue})
```javascript
etcd.compareAndDelete("key", "oldvalue");
etcd.compareAndDelete("key", "oldValue", options, console.log);
```
Alias: `.testAndDelete()`
### .mkdir(dir, [options], [callback])
Create a directory
```javascript
etcd.mkdir("dir");
etcd.mkdir("dir", console.log);
etcd.mkdir("dir/", options, console.log);
```
### .rmdir(dir, [options], [callback])
Remove a directory
```javascript
etcd.rmdir("dir");
etcd.rmdir("dir", console.log);
etcd.rmdir("dir/", { recursive: true }, console.log);
```
Available options include:
- `recursive` (bool, delete recursively)
### .create(path, value, [options], [callback])
Atomically create in-order keys.
```javascript
etcd.create("queue", "first")
etcd.create("queue", "next", console.log)
```
Alias: `.post()`
### .watch(key, [options], [callback])
This is a convenience method for get with `{wait: true}`.
```javascript
etcd.watch("key");
etcd.watch("key", console.log);
```
The watch command is pretty low level, it does not handle reconnects or
timeouts (Etcd will disconnect you after 5 minutes). Use the `.watcher()` below
if you do not wish to handle this yourself.
### .watchIndex(key, index, [options], callback)
This is a convenience method for get with `{wait: true, waitIndex: index}`.
```javascript
etcd.watchIndex("key", 7, console.log);
```
See `.watch()` above.
### .watcher(key, [index], [options])
Returns an eventemitter for watching for changes on a key
```javascript
watcher = etcd.watcher("key");
watcher.on("change", console.log); // Triggers on all changes
watcher.on("set", console.log); // Triggers on specific changes (set ops)
watcher.on("delete", console.log); // Triggers on delete.
watcher2 = etcd.watcher("key", null, {recursive: true});
watcher2.on("error", console.log);
```
You can cancel a watcher by calling `.stop()`.
Signals:
- `change` - emitted on value change
- `reconnect` - emitted on reconnect
- `error` - emitted on invalid content
- `<etcd action>` - the etcd action that triggered the watcher (ex: set, delete).
- `stop` - watcher was canceled.
- `resync` - watcher lost sync (server cleared and outdated the index).
It will handle reconnects and timeouts for you, it will also resync (best
effort) if it loses sync with Etcd (Etcd only keeps 1000 items in its event
history - for high frequency setups it's possible to fall behind).
Use the `.watch()` command in you need more direct control.
### .raw(method, key, value, options, callback)
Bypass the API and do raw queries.
Method must be one of: PUT, GET, POST, PATCH, DELETE
```javascript
etcd.raw("GET", "v2/stats/leader", null, {}, callback)
etcd.raw("PUT", "v2/keys/key", "value", {}, callback)
```
Remember to provide the full path, without any leading '/'
### .machines(callback)
Returns information about etcd nodes in the cluster
```javascript
etcd.machines(console.log);
```
### .leader(callback)
Return the leader in the cluster
```javascript
etcd.leader(console.log);
```
### .leaderStats(callback)
Return statistics about cluster leader
```javascript
etcd.leaderStats(console.log);
```
### .selfStats(callback)
Return statistics about connected etcd node
```javascript
etcd.selfStats(console.log);
```
## Synchronous operations
The library supports a set of basic synchronous/blocking operations that can be useful during
program startup (used like [fs.readFileSync](http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options)).
Synchronous functions perform the etcd request immediately (blocking) and return the following:
```javascript
{
err // Error message or null if request completed successfully
body // Body of the message or null if error
headers // Headers from the response
}
```
### .setSync(key, value = null, [options])
Synchronously set key to value, or create key/directory.
```javascript
etcd.setSync("key");
etcd.setSync("key", "value");
etcd.setSync("key", "value", { ttl: 60 });
etcd.setSync("key", "value", { maxRetries: 3 });
```
Same options and function as .set().
### .getSync(key, [options])
Get a key or path.
```javascript
etcd.getSync("key");
etcd.getSync("key", { recursive: true });
```
### .delSync(key, [options])
Synchronously delete a key or path
```javascript
etcd.delSync("key");
etcd.delSync("key/", { recursive: true });
```
The available options are the same as .del() above.
### .mkdirSync(dir, [options])
Synchronously create a directory
```javascript
etcd.mkdirSync("dir");
etcd.mkdirSync("dir/", options);
```
### .rmdirSync(dir, [options])
Synchronously remove a directory
```javascript
etcd.rmdirSync("dir");
etcd.rmdirSync("dir/", { recursive: true });
```
The available options are the same as .rmdir() above.
## Aborting a request
All async requests will return a cancellation token, to abort a request, do
the following:
```javascript
var token = etcd.get("key", console.log);
token.abort() // also aliased as token.cancel()
console.log("Request is cancelled: ", token.isAborted());
```
Note that there are no guarantees that aborted write operations won't have
affected server state before they were aborted. They only guarantee here is that
you won't get any callbacks from the request after calling `.abort()`.
## SSL support
Provide `ca`, `cert`, `key` as options. Remember to use `https`-url.
```javascript
var fs = require('fs');
var options = {
ca: fs.readFileSync('ca.pem'),
cert: fs.readFileSync('cert.pem'),
key: fs.readFileSync('key.pem')
};
var etcdssl = new Etcd("https://localhost:2379", options);
```
## Basic auth
Pass a hash containing username and password as auth option to use basic auth.
```javascript
var auth = {
user: "username",
pass: "password"
};
var etcd = new Etcd("localhost:2379", { auth: auth });
```
## Constructor options
Pass in a hash after server in the constructor to set options. Some useful constructor options include:
- `timeout` - Integer request timeout in milliseconds to wait for server response.
- `ca` - Ca certificate
- `cert` - Client certificate
- `key` - Client key
- `passphrase` - Client key passphrase
- `auth` - A hash containing `{user: "username", pass: "password"}` for basic auth.
```javascript
var etcd = new Etcd("127.0.0.1:2379", { timeout: 1000, ... });'
```
## Debugging
Nodejs `console.log`/`console.dir` truncates output to a couple of levels -
often hiding nested errors. Use `util.inspect` to show inner errors.
```javascript
etcd.get('key', function(err, val) {
console.log(require('util').inspect(err, true, 10));
});
//{ [Error: All servers returned error]
// [stack]: [Getter/Setter],
// [message]: 'All servers returned error',
// errors:
// [ { server: 'https://localhost:2379',
// httperror:
// { [Error: Hostname/IP doesn't match certificate's altnames: "Host: localhost. is not cert's CN: undefined"]
// [stack]: [Getter/Setter],
// [message]: 'Hostname/IP doesn\'t match certificate\'s altnames: "Host: localhost. is not cert\'s CN: undefined"',
// reason: 'Host: localhost. is not cert\'s CN: undefined',
// host: 'localhost.',
// cert:
// { subject: { C: 'USA', O: 'etcd-ca', OU: 'CA' },
// issuer: { C: 'USA', O: 'etcd-ca', OU: 'CA' } } },
// httpstatus: undefined,
// httpbody: undefined,
// response: undefined,
// timestamp: Sun Dec 27 2015 23:05:15 GMT+0100 (CET) },
// [length]: 1 ],
// retries: 0 }
```
## FAQ:
- Are there any order of execution guarantees when doing multiple requests without using callbacks?
- No, order of execution is up to NodeJS and the network. Requests run from a connection pool, meaning that if one request is delayed for some reason they'll arrive at the server out of order. Use callbacks (and maybe even a nice [async](https://github.com/caolan/async) callback handling library for convenient syntax) if ordering is important to prevent race conditions.
================================================
FILE: package.json
================================================
{
"name": "node-etcd",
"version": "7.0.0",
"description": "etcd library for node.js (etcd v2 api)",
"repository": {
"type": "git",
"url": "http://github.com/stianeikeland/node-etcd.git"
},
"licenses": [
{
"type": "BSD 3-Clause",
"url": "http://opensource.org/licenses/BSD-3-Clause"
}
],
"maintainers": [
{
"name": "Stian Eikeland",
"email": "stian@eikeland.se",
"web": "http://eikeland.se/"
}
],
"contribuitors": [
{
"name": "Stian Eikeland",
"url": "https://github.com/stianeikeland"
},
{
"name": "Derek Brown",
"email": "mail@derektbrown.com",
"url": "derektbrown.com"
},
{
"name": "Jon Morehouse",
"email": "morehousej09@gmail.com",
"url": "https://github.com/jonmorehouse"
},
{
"name": "Bryan Rockwood",
"email": "bryan.rockwood@c2fo.com",
"url": "https://github.com/brockwood"
}
],
"engines": {
"node": ">= 6.0.0"
},
"main": "lib/index.js",
"scripts": {
"build": "node_modules/.bin/coffee --bare --compile --output lib/ src/*.coffee",
"prepublish": "node_modules/.bin/coffee --bare --compile --output lib/ src/*.coffee",
"test": "node_modules/.bin/mocha --require coffee-coverage/register-istanbul --compilers coffee:coffee-script/register test/",
"coverage": "node_modules/.bin/nyc npm test",
"watch": "node_modules/.bin/mocha --compilers coffee:coffee-script/register --watch"
},
"nyc": {
"check-coverage": true,
"include": [
"src/**/*.js"
]
},
"dependencies": {
"deasync": "^0.1.13",
"lodash": "^4.17.10",
"request": "^2.87.0",
"url-parse": "^1.4.3"
},
"devDependencies": {
"coffee-coverage": "2.0.1",
"coffee-script": "1.12.7",
"mocha": "^4.0.0",
"nock": "^9.4.4",
"nyc": "^12.0.0",
"should": "11.2.1",
"simple-mock": "0.8.0"
},
"keywords": [
"etcd",
"raft"
]
}
================================================
FILE: src/client.coffee
================================================
request = require 'request'
deasync = require 'deasync'
_ = require 'lodash'
# Default options for request library
defaultRequestOptions =
pool:
maxSockets: 100
followAllRedirects: true
defaultClientOptions =
maxRetries: 3
# CancellationToken to abort a request
class CancellationToken
constructor: (@servers, @maxRetries, @retries = 0, @errors = []) ->
@aborted = false
setRequest: (req) =>
@req = req
isAborted: () =>
@aborted
abort: () =>
@aborted = true
@req.abort() if @req?
cancel: @::abort
wasAborted: @::isAborted
# HTTP Client for connecting to etcd servers
class Client
constructor: (@hosts, @options, @sslopts) ->
@syncmsg = {}
execute: (method, options, callback) =>
opt = _.defaults (_.clone options), @options, defaultRequestOptions, { method: method }
opt.clientOptions = _.defaults opt.clientOptions, defaultClientOptions
servers = _.shuffle @hosts
token = new CancellationToken servers, opt.clientOptions.maxRetries
syncResp = @_multiserverHelper servers, opt, token, callback
if options.synchronous is true
return syncResp
else
return token
put: (options, callback) => @execute "PUT", options, callback
get: (options, callback) => @execute "GET", options, callback
post: (options, callback) => @execute "POST", options, callback
patch: (options, callback) => @execute "PATCH", options, callback
delete: (options, callback) => @execute "DELETE", options, callback
# Multiserver (cluster) executer
_multiserverHelper: (servers, options, token, callback) =>
host = _.first(servers)
options.url = "#{host}#{options.path}"
return if token.isAborted() # Aborted by user?
if not host? # No servers left?
return @_retry token, options, callback if @_shouldRetry token
return @_error token, callback
reqRespHandler = (err, resp, body) =>
return if token.isAborted()
if @_isHttpError err, resp
token.errors.push
server: host
httperror: err
httpstatus: resp?.statusCode
httpbody: resp?.body
response: resp
timestamp: new Date()
# Recurse:
return @_multiserverHelper _.drop(servers), options, token, callback
# Deliver response
@_handleResponse err, resp, body, callback
syncRespHandler = (err, body, headers) =>
options.syncdone = true
@syncmsg =
err: err
body: body
headers: headers
callback = syncRespHandler if options.synchronous is true
req = @_doRequest options, reqRespHandler
token.setRequest req
if options.synchronous is true and options.syncdone is undefined
options.syncdone = false
deasync.loopWhile(() => return !options.syncdone);
delete options.syncdone
return @syncmsg
else
return req
_doRequest: (options, reqRespHandler) ->
request options, reqRespHandler
_retry: (token, options, callback) =>
doRetry = () =>
@_multiserverHelper token.servers, options, token, callback
waitTime = @_waitTime token.retries
token.retries += 1
setTimeout doRetry, waitTime
_waitTime: (retries) ->
return 1 if process.env.RUNNING_UNIT_TESTS is 'true'
### !pragma no-coverage-next ###
return 100 * Math.pow 16, retries
_shouldRetry: (token) =>
token.retries < token.maxRetries and @_isPossibleLeaderElection token.errors
# All tries (all servers, all retries) failed
_error: (token, callback) ->
error = new Error 'All servers returned error'
error.errors = token.errors
error.retries = token.retries
callback error if callback
# If all servers reject connect or return raft error it's possible the
# cluster is in leader election mode.
_isPossibleLeaderElection: (errors) ->
checkError = (e) ->
e?.httperror?.code in ['ECONNREFUSED', 'ECONNRESET'] or
e?.httpbody?.errorCode in [300, 301] or
/Not current leader/.test e?.httpbody
errors? and _.every errors, checkError
_isHttpError: (err, resp) ->
err or (resp?.statusCode? and resp.statusCode >= 500)
_handleResponse: (err, resp, body, callback) ->
return if not callback?
if body?.errorCode? # http ok, but etcd gave us an error
error = new Error body?.message || 'Etcd error'
error.errorCode = body.errorCode
error.error = body
callback error, "", (resp?.headers or {})
else
callback null, body, (resp?.headers or {})
exports = module.exports = Client
================================================
FILE: src/index.coffee
================================================
_ = require 'lodash'
Watcher = require './watcher'
Client = require './client'
HttpsAgent = (require 'https').Agent
URL = require 'url-parse'
# Etcd client for etcd protocol version 2
class Etcd
# Constructor, set etcd host and port.
# For https: provide {ca, crt, key} as sslopts.
# constructor: (hosts = ["http://127.0.0.1:2379"], options = {}) ->
constructor: (hosts = "127.0.0.1:2379", options = {}) ->
@hosts = @_cleanHostList hosts
@client = new Client(@hosts, options, null)
# Set key to value
# Usage:
# .set("key", "value", callback)
# .set("key", "value", {prevValue: "oldvalue"}, callback)
set: (key, value, options, callback) ->
[options, callback] = @_argParser options, callback
opt = @_prepareOpts ("keys/" + @_stripSlashPrefix key), "/v2", value, options
@client.put opt, callback
# Set key to value synchronously
# Usage:
# .set("key", "value")
# .set("key", "value", {prevValue: "oldvalue"})
setSync: (key, value, options = {}) ->
this.set key, value, @_synchronousOpts(options)
# Get value of key
# Usage:
# .get("key", callback)
# .get("key", {recursive: true}, callback)
get: (key, options, callback) ->
[options, callback] = @_argParser options, callback
opt = @_prepareOpts ("keys/" + @_stripSlashPrefix key), "/v2", null, options
@client.get opt, callback
# Synchronously get value of key
# Usage:
# .get("key")
# .get("key", {recursive: true})
getSync: (key, options = {}) ->
this.get key, @_synchronousOpts(options)
# Create a key (atomic in order)
# Usage:
# .create("path", "value", callback)
# .create("path", "value", options, callback)
create: (dir, value, options, callback) ->
[options, callback] = @_argParser options, callback
opt = @_prepareOpts ("keys/" + @_stripSlashPrefix dir), "/v2", value, options
@client.post opt, callback
post: @::create
# Delete a key
# Usage:
# .del("key", callback)
# .del("key", {recursive: true}, callback)
# .delete("key", callback)
del: (key, options, callback) ->
[options, callback] = @_argParser options, callback
opt = @_prepareOpts ("keys/" + @_stripSlashPrefix key), "/v2", null, options
@client.delete opt, callback
delete: @::del
# Synchronous delete a key
# Usage:
# .del("key")
# .del("key", {recursive: true}))
delSync: (key, options = {}) ->
this.del key, @_synchronousOpts(options)
# Make a directory
# Usage:
# .mkdir("dir", callback)
# .mkdir("dir", options, callback)
mkdir: (dir, options, callback) ->
[options, callback] = @_argParser options, callback
options.dir = true
@set dir, null, options, callback
# Synchronously make a directory
# Usage:
# .mkdir("dir")
# .mkdir("dir", options)
mkdirSync: (dir, options = {}) ->
this.mkdir dir, @_synchronousOpts(options)
# Remove a directory
# Usage:
# .rmdir("dir", callback)
# .rmdir("dir", {recursive: true}, callback)
rmdir: (dir, options, callback) ->
[options, callback] = @_argParser options, callback
options.dir = true
@del dir, options, callback
# Synchronously remove a directory
# Usage:
# .rmdir("dir")
# .rmdir("dir", {recursive: true})
rmdirSync: (dir, options = {}) ->
this.rmdir dir, @_synchronousOpts(options)
# Compare and swap value if unchanged
# Usage:
# .compareAndSwap("key", "newValue", "oldValue", callback)
# .compareAndSwap("key", "newValue", "oldValue", options, callback)
# .testAndSet("key", "newValue", "oldValue", options, callback)
compareAndSwap: (key, value, oldvalue, options, callback) ->
[options, callback] = @_argParser options, callback
options ?= {}
options.prevValue = oldvalue
@set key, value, options, callback
testAndSet: @::compareAndSwap
# Compare and delete if value is unchanged
# Usage:
# .compareAndDelete("key", "oldValue", options, callback)
compareAndDelete: (key, oldvalue, options, callback) ->
[options, callback] = @_argParser options, callback
options ?= {}
options.prevValue = oldvalue
@del key, options, callback
testAndDelete: @::compareAndDelete
# Execute a raw etcd query
# Where method is one of: PUT, GET, POST, PATCH, DELETE
#
# Usage:
# .raw("METHOD", "path", "value", options, callback)
# .raw("GET", "v2/stats/leader", null, {}, callback)
# .raw("PUT", "v2/keys/key", "value", {}, callback)
raw: (method, key, value, options, callback) ->
[options, callback] = @_argParser options, callback
opt = @_prepareOpts key, "", value, options
@client.execute method, opt, callback
# Watch for value changes on a key
watch: (key, options, callback) ->
[options, callback] = @_argParser options, callback
options ?= {}
options.wait = true
@get key, options, callback
# Watch for value changes on a key since a specific index
watchIndex: (key, index, options, callback) ->
[options, callback] = @_argParser options, callback
options ?= {}
options.waitIndex = index
@watch key, options, callback
# Returns an eventemitter that watches a key, emits 'change' on value change
# or 'reconnect' when trying to recover from errors.
watcher: (key, index = null, options = {}) =>
return new Watcher this, key, index, options
# Get the etcd cluster machines (server)
machines: (callback) ->
opt = @_prepareOpts "keys/_etcd/machines"
@client.get opt, callback
# List servers this etcd client will try to connect to
getHosts: () ->
_.clone(@hosts)
# Get the current cluster leader
leader: (callback) ->
opt = @_prepareOpts "leader"
@client.get opt, callback
# Get statistics about the leader
leaderStats: (callback) ->
opt = @_prepareOpts "stats/leader"
@client.get opt, callback
# Get statistics about the currently connected entity
selfStats: (callback) ->
opt = @_prepareOpts "stats/self"
@client.get opt, callback
# Get version of etcd
version: (callback) ->
opt = @_prepareOpts "version", ""
@client.get opt, callback
# Strip the prefix slash if set
_stripSlashPrefix: (key) ->
key.replace /^\//, ''
_synchronousOpts: (options) ->
_.extend {}, options, { synchronous: true }
# Prepare request options
_prepareOpts: (path, apiVersion = "/v2", value = null, allOpts = {}) ->
# serverprotocol = if @sslopts? then "https" else "http"
queryString = _.omit allOpts, 'maxRetries', 'synchronous'
clientOptions = _.pick allOpts, 'maxRetries'
opt = {
path: "#{apiVersion}/#{path}"
# serverprotocol: serverprotocol
json: true
qs: queryString
clientOptions: clientOptions
synchronous: allOpts.synchronous
form: { value: value } if value?
agentOptions: @sslopts if @sslopts?
}
# Swap callback and options if no options was given.
_argParser: (options = {}, callback) ->
if typeof options is 'function'
[{}, options]
else
[options, callback]
# Make sure hosts is a list, make sure all have protocol added
# defaults to http and remove trailing slash
_cleanHostList: (hosts) ->
hostlist = if _.isArray(hosts) then hosts else [hosts]
hostlist.map (host) ->
host = 'http://' + host if host.indexOf('http') is -1
url = new URL(host)
url.href.replace /\/$/, "" # Trailing slash
exports = module.exports = Etcd
================================================
FILE: src/watcher.coffee
================================================
{EventEmitter} = require 'events'
# A eventemitter for watching changes on a given key for etcd.
# Emits:
# 'change' - on value change
# 'reconnect' - on errors/timeouts
# '<etcd action>' - the etcd action that triggered the watcher (set, delete, etc)
#
# Automatically reconnects and backs off on errors.
#
class Watcher extends EventEmitter
constructor: (@etcd, @key, @index = null, @options = {}) ->
@stopped = false
@retryAttempts = 0
@_watch()
stop: () =>
@stopped = true
@request.abort()
@emit 'stop', "Watcher for '#{@key}' aborted."
_watch: () =>
if @index is null
@request = @etcd.watch @key, @options, @_respHandler
else
@request = @etcd.watchIndex @key, @index, @options, @_respHandler
_error: (err) =>
# Something went wrong, most likely on the network,
# maybe disconnected, or similar.
error = new Error 'Connection error, reconnecting.'
error.error = err
error.reconnectCount = @retryAttempts
@emit 'reconnect', error
@_retry()
_missingValue: (headers) =>
# Etcd sent us an empty response, it seems to do this when
# it times out a watching client.
error = new Error 'Etcd timed out watcher, reconnecting.'
error.headers = headers
@retryAttempts = 0
@emit 'reconnect', error
@_watch()
_valueChanged: (val, headers) =>
# Valid data received, value was changed.
@retryAttempts = 0
@index = val.node.modifiedIndex + 1
@emit 'change', val, headers
@emit val.action, val, headers if val.action?
@_watch()
_unexpectedData: (val, headers) =>
# Unexpected data received
error = new Error 'Received unexpected response'
error.response = val;
@emit 'error', error
@_retry()
_resync: (err) =>
@index = err.error.index
@retryAttempts = 0
@emit 'resync', err
@_watch()
_respHandler: (err, val, headers) =>
return if @stopped
if err?.errorCode is 401 and err.error?.index?
@_resync err
else if err
@_error err
else if headers?['x-etcd-index']? and not val?
@_missingValue headers
else if val?.node?.modifiedIndex?
@_valueChanged val, headers
else
@_unexpectedData val, headers
_retry: () =>
timeout = (Math.pow(2,@retryAttempts)*300) + (Math.round(Math.random() * 1000))
setTimeout @_watch, timeout
@retryAttempts++
exports = module.exports = Watcher
================================================
FILE: test/client.coffee
================================================
should = require 'should'
nock = require 'nock'
Client = require '../src/client.coffee'
describe 'Client', ->
client = new Client
# TODO: Fix these tests.. I've been stupid and tested implementation details, not api..
describe '#_handleResponse()', ->
# it 'fails on http error', ->
# client._handleResponse 'error', '', '', (err) ->
# err.error.should.equal 'error'
it 'should use error objects for errors', ->
client._handleResponse null, 'resp', {errorCode: 100}, (err) ->
err.should.be.an.instanceOf Error
it 'fails on etcd error', ->
client._handleResponse null, "resp", {errorCode: 100}, (err) ->
err.error.errorCode.should.equal 100
it 'succeeds on no errors', ->
client._handleResponse null, "resp", "data", (_, val) ->
val.should.equal "data"
it 'passthrough any headers set in response', ->
client._handleResponse null, {headers: {a: "b"}}, "data", (e, v, headers) ->
headers.a.should.equal "b"
it 'sets empty object as header if none received', ->
client._handleResponse null, null, "data", (e, v, headers) ->
headers.should.be.an.Object
Object.keys(headers).should.be.empty
it 'should not fail if callback is not given', ->
client._handleResponse null, 'resp', 'body'
================================================
FILE: test/index.coffee
================================================
should = require 'should'
nock = require 'nock'
simple = require 'simple-mock'
Etcd = require '../src/index.coffee'
# Set env var to skip timeouts
process.env.RUNNING_UNIT_TESTS = true
# Helpers
getNock = (host = 'http://127.0.0.1:2379') ->
nock host
beforeEach () ->
nock.cleanAll()
# Tests for utility functions
describe 'Utility', ->
etcd = new Etcd
describe '#_stripSlashPrefix()', ->
it 'should strip prefix-/ from key', ->
etcd._stripSlashPrefix("/key/").should.equal("key/")
etcd._stripSlashPrefix("key/").should.equal("key/")
describe '#_prepareOpts()', ->
it 'should return default request options', ->
etcd._prepareOpts('keypath/key').should.containEql {
json: true
path: '/v2/keypath/key'
}
describe 'Connecting', ->
mock = (host = 'http://127.0.0.1:2379/') ->
nock(host)
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
it 'should support empty constructor (localhost:2379)', (done) ->
etcd = new Etcd
m = mock()
etcd.get 'key', (err, val) ->
m.isDone().should.be.true
done err, val
it 'should support string as connect host', (done) ->
etcd = new Etcd "testhost.com:4009"
m = mock("http://testhost.com:4009")
etcd.get 'key', (err, val) ->
m.isDone().should.be.true
done err, val
it 'should support string prefixed by http:// as host', (done) ->
etcd = new Etcd "http://testhost.com:4009"
m = mock("http://testhost.com:4009")
etcd.get 'key', (err, val) ->
m.isDone().should.be.true
done err, val
it 'should support string postfixed by / as host', (done) ->
etcd = new Etcd "http://testhost.com:4009/"
m = mock("http://testhost.com:4009")
etcd.get 'key', (err, val) ->
m.isDone().should.be.true
done err, val
it 'should support array of strings as host', (done) ->
etcd = new Etcd ["http://testhost.com:4009"]
m = mock("http://testhost.com:4009")
etcd.get 'key', (err, val) ->
m.isDone().should.be.true
done err, val
it 'should support https strings', (done) ->
etcd = new Etcd ["https://testhost.com:1000"]
m = mock("https://testhost.com:1000")
etcd.get 'key', (err, val) ->
m.isDone().should.be.true
done err, val
describe 'Basic auth', ->
it 'should support basic auth', (done) ->
auth =
user: "username"
pass: "password"
etcd = new Etcd "localhost:2379", { auth: auth }
m = nock("http://localhost:2379")
.get("/v2/keys/key")
.basicAuth(
user: "username",
pass: "password"
)
.reply(200)
etcd.get 'key', (err, val) ->
m.isDone().should.be.true
done err, val
describe 'Basic functions', ->
etcd = new Etcd
checkVal = (done) ->
(err, val) ->
val.should.containEql { value: "value" }
done err, val
describe '#get()', ->
it 'should return entry from etcd', (done) ->
getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd.get 'key', checkVal done
it 'should send options to etcd as request url', (done) ->
getNock()
.get('/v2/keys/key?recursive=true')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd.get 'key', { recursive: true }, checkVal done
it 'should callback with error on error', (done) ->
getNock()
.get('/v2/keys/key')
.reply(404, {"errorCode": 100, "message": "Key not found"})
etcd.get 'key', (err, val) ->
err.should.be.instanceOf Error
err.error.errorCode.should.equal 100
err.message.should.equal "Key not found"
done()
describe '#getSync()', ->
it 'should synchronously return entry from etcd', (done) ->
getNock()
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
val = etcd.getSync 'key'
doneCheck = checkVal done
doneCheck val.err, val.body
it 'should synchronously return with error on error', (done) ->
getNock()
.get('/v2/keys/key')
.reply(404, {"errorCode": 100, "message": "Key not found"})
val = etcd.getSync 'key'
val.err.should.be.instanceOf Error
val.err.error.errorCode.should.equal 100
val.err.message.should.equal "Key not found"
done()
describe '#set()', ->
it 'should put to etcd', (done) ->
getNock()
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
etcd.set 'key', 'value', checkVal done
it 'should send options to etcd as request url', (done) ->
getNock()
.put('/v2/keys/key?prevValue=oldvalue', { value: "value"})
.reply(200, '{"action":"SET","key":"/key","prevValue":"oldvalue","value":"value","index":1}')
etcd.set 'key', 'value', { prevValue: "oldvalue" }, checkVal done
it 'should follow 307 redirects', (done) ->
(nock 'http://127.0.0.1:4002')
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
(nock 'http://127.0.0.1:2379')
.put('/v2/keys/key', { value: "value" })
.reply(307, "", { location: "http://127.0.0.1:4002/v2/keys/key" })
etcd.set 'key', 'value', checkVal done
describe '#setSync()', ->
it 'should synchronously put to etcd', (done) ->
getNock()
.put('/v2/keys/key', { value: "value" })
.reply(200, '{"action":"SET","key":"/key","prevValue":"value","value":"value","index":1}')
val = etcd.setSync 'key', 'value'
doneCheck = checkVal done
doneCheck val.err, val.body
describe '#create()', ->
it 'should post value to dir', (done) ->
getNock()
.post('/v2/keys/dir', { value: "value" })
.reply(200, '{"action":"create", "node":{"key":"/dir/2"}}')
etcd.create 'dir', 'value', (err, val) ->
val.should.containEql { action: "create" }
done err, val
describe '#post()', ->
it 'should post value to key', (done) ->
getNock().post('/v2/keys/key', { value: "value" }).reply(200)
etcd.post 'key', 'value', done
describe '#compareAndSwap()', ->
it 'should set using prevValue', (done) ->
getNock()
.put('/v2/keys/key?prevValue=oldvalue', { value: "value"})
.reply(200, '{"action":"SET","key":"/key","prevValue":"oldvalue","value":"value","index":1}')
etcd.compareAndSwap 'key', 'value', 'oldvalue', checkVal done
it 'has alias testAndSet', ->
etcd.testAndSet.should.equal etcd.testAndSet
describe '#compareAndDelete', ->
it 'should delete using prevValue', (done) ->
getNock().delete('/v2/keys/key?prevValue=oldvalue').reply(200)
etcd.compareAndDelete 'key', 'oldvalue', done
it 'has alias testAndDelete', ->
etcd.compareAndDelete.should.equal etcd.testAndDelete
describe '#mkdir()', ->
it 'should create directory', (done) ->
getNock()
.put('/v2/keys/key?dir=true')
.reply(200, '{"action":"create","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":1}}')
etcd.mkdir 'key', (err, val) ->
val.should.containEql {action: "create"}
val.node.should.containEql {key: "/key"}
val.node.should.containEql {dir: true}
done()
it 'should work when no options or callback given - bug #56', (done) ->
replybody = '{"action":"create", "node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":1}}'
getNock()
.put('/v2/keys/key?dir=true')
.reply(200, (uri, req, cb) ->
cb(replybody)
done()
)
etcd.mkdir 'key'
describe '#mkdirSync()', ->
it 'should synchronously create directory', (done) ->
getNock()
.put('/v2/keys/key?dir=true')
.reply(200, '{"action":"create","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":1}}')
val = etcd.mkdirSync 'key'
val.body.should.containEql {action: "create"}
val.body.node.should.containEql {key: "/key"}
val.body.node.should.containEql {dir: true}
done()
describe '#rmdir()', ->
it 'should remove directory', (done) ->
getNock().delete('/v2/keys/key?dir=true').reply(200)
etcd.rmdir 'key', done
describe '#rmdirSync()', ->
it 'should synchronously remove directory', (done) ->
getNock().delete('/v2/keys/key?dir=true')
.reply(200, '{"action":"delete","node":{"key":"/key","dir":true,"modifiedIndex":1,"createdIndex":3}}')
val = etcd.rmdirSync 'key'
val.body.should.containEql {action: "delete"}
val.body.node.should.containEql {dir: true}
done()
describe '#del()', ->
it 'should delete a given key in etcd', (done) ->
getNock().delete('/v2/keys/key').reply(200)
etcd.del 'key', done
describe '#delSync()', ->
it 'should synchronously delete a given key in etcd', (done) ->
getNock().delete('/v2/keys/key2').reply(200, '{"action":"delete"}')
val = etcd.delSync 'key2'
val.body.should.containEql {action: "delete"}
done()
describe '#watch()', ->
it 'should do a get with wait=true', (done) ->
getNock()
.get('/v2/keys/key?wait=true')
.reply(200, '{"action":"set","key":"/key","value":"value","modifiedIndex":7}')
etcd.watch 'key', checkVal done
describe '#watchIndex()', ->
it 'should do a get with wait=true and waitIndex=x', (done) ->
getNock()
.get('/v2/keys/key?waitIndex=1&wait=true')
.reply(200, '{"action":"set","key":"/key","value":"value","modifiedIndex":7}')
etcd.watchIndex 'key', 1, checkVal done
describe '#raw()', ->
it 'should use provided method', (done) ->
getNock().patch('/key').reply(200, 'ok')
etcd.raw 'PATCH', 'key', null, {}, done
it 'should send provided value', (done) ->
getNock().post('/key', { value: "value" }).reply(200, 'ok')
etcd.raw 'POST', 'key', "value", {}, done
it 'should call cb on value from etcd', (done) ->
getNock().get('/key').reply(200, 'value')
etcd.raw 'GET', 'key', null, {}, (err, val) ->
val.should.equal 'value'
done err, val
describe '#machines()', ->
it 'should ask etcd for connected machines', (done) ->
getNock().get('/v2/keys/_etcd/machines').reply(200, '{"value":"value"}')
etcd.machines checkVal done
describe '#leader()', ->
it 'should ask etcd for leader', (done) ->
getNock().get('/v2/leader').reply(200, '{"value":"value"}')
etcd.leader checkVal done
describe '#leaderStats()', ->
it 'should ask etcd for statistics for leader', (done) ->
getNock().get('/v2/stats/leader').reply(200, '{"value":"value"}')
etcd.leaderStats checkVal done
describe '#selfStats()', ->
it 'should ask etcd for statistics for connected server', (done) ->
getNock().get('/v2/stats/self').reply(200, '{"value":"value"}')
etcd.selfStats checkVal done
describe '#version()', ->
it 'should ask etcd for version', (done) ->
getNock().get('/version').reply(200, 'etcd v0.1.0-8-gaad1626')
etcd.version (err, val) ->
val.should.equal 'etcd v0.1.0-8-gaad1626'
done err, val
describe 'SSL support', ->
beforeEach () ->
nock.cleanAll()
it 'passes ssl options to request lib', (done) ->
etcdssl = new Etcd 'https://localhost:4009', {ca: 'myca', cert: 'mycert', key: 'mykey'}
simple.mock(etcdssl.client, "_doRequest").callFn (options) ->
options.should.containEql
ca: 'myca'
cert: 'mycert'
key: 'mykey'
done()
etcdssl.get 'key'
describe 'Cancellation Token', ->
beforeEach () ->
nock.cleanAll()
it 'should return token on request', ->
getNock().get('/version').reply(200, 'etcd v0.1.0-8-gaad1626')
etcd = new Etcd
token = etcd.version()
token.abort.should.be.a.function
token.isAborted().should.be.false
it 'should stop execution on abort', (done) ->
http = getNock()
.log(console.log)
.get('/v2/keys/key')
.reply(200, '{"action":"GET","key":"/key","value":"value","index":1}')
etcd = new Etcd '127.0.0.1', 2379
# This sucks a bit.. are there any better way of checking that a callback
# does not happen?
token = etcd.get "key", () -> throw new Error "Call should have been aborted"
token.abort()
setTimeout done, 50
describe 'Multiserver/Cluster support', ->
beforeEach () ->
nock.cleanAll()
it 'should accept list of servers in constructor', ->
etcd = new Etcd ['localhost:2379', 'localhost:4002']
etcd.getHosts().should.eql ['http://localhost:2379', 'http://localhost:4002']
it 'should try next server in list on http error', (done) ->
path = '/v2/keys/foo'
response = '{"action":"GET","key":"/key","value":"value","index":1}'
handler = (uri) ->
nock.cleanAll()
getNock('http://s1').get(path).reply(200, response)
getNock('http://s2').get(path).reply(200, response)
return {}
getNock('http://s1').get(path).reply(500, handler)
getNock('http://s2').get(path).reply(500, handler)
etcd = new Etcd ['s1', 's2']
etcd.get 'foo', (err, res) ->
res.value.should.eql 'value'
done()
it 'should callback error if all servers failed', (done) ->
path = '/v2/keys/foo'
getNock('http://s1').get(path).reply(500, {})
getNock('http://s2').get(path).reply(500, {})
etcd = new Etcd ['s1', 's2']
etcd.get 'foo', (err, res) ->
err.should.be.an.instanceOf Error
err.errors.should.have.lengthOf 2
done()
describe 'when cluster is doing leader elect', () ->
it 'should retry on connection refused', (done) ->
etcd = new Etcd ("localhost:#{p}" for p in [47187, 47188, 47189])
token = etcd.set 'a', 'b', (err) ->
err.errors.length.should.be.exactly 12
token.errors.length.should.be.exactly 12
token.retries.should.be.exactly 3
done()
it 'should allow maxRetries to control number of retries', (done) ->
etcd = new Etcd ("localhost:#{p}" for p in [47187, 47188, 47189])
token = etcd.set 'a', 'b', { maxRetries: 1 }, (err) ->
err.errors.length.should.be.exactly 6
token.retries.should.be.exactly 1
done()
================================================
FILE: test/watcher.coffee
================================================
should = require 'should'
nock = require 'nock'
Etcd = require '../src/index'
Watcher = require '../src/watcher.coffee'
class FakeEtcd
constructor: ->
@stopped = false
@cb = ->
abort: -> {abort: => @stopped = true}
watch: (key, options, cb) ->
key.should.equal 'key'
@cb = cb
return @abort()
watchIndex: (key, index, options, cb) ->
key.should.equal 'key'
@cb = cb
return @abort()
change: (err, val, header = {}) ->
@cb err, val, header
describe 'Watcher', ->
it 'should emit change on watch change', (done) ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
w.on 'change', (val) ->
val.should.containEql { node: { modifiedIndex: 0 } }
done()
etcd.change null, { node: { modifiedIndex: 0 } }
it 'should emit reconnect event on error', (done) ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
w.on 'reconnect', (err) ->
err.should.containEql { error: "error" }
done()
etcd.change "error", null
it 'should emit error if received content is invalid', (done) ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
w.on 'error', -> done()
etcd.change null, 'invalid content', {}
it 'should emit error object on error', (done) ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
w.on 'error', (err) ->
err.should.be.an.instanceOf Error
done()
etcd.change null, 'invalid content', {}
it 'should use provided options', (done) ->
etcd = new FakeEtcd
etcd.watch = (key, opt, cb) ->
opt.should.containEql { recursive: true }
done()
w = new Watcher etcd, 'key', null, { recursive: true }
it 'should emit action on event', (done) ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
w.on 'set', (res) -> done()
etcd.change null, { action: 'set', node: { key: '/key', value: 'value', modifiedIndex: 1, createdIndex: 1 } }
it 'should reconnect (call watch again) on error', (done) ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
etcd.watch = (key, cb) ->
w.retryAttempts.should.equal 1
done()
etcd.change "error", null
it 'should reconnect (watch again) on empty body (etcd timeout)', (done) ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
w.on 'reconnect', () ->
done()
etcd.change null, null, {'x-etcd-index': 123}
it 'should call watch on next index after getting change', (done) ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
i = 5
etcd.watchIndex = (key, index, cb) ->
index.should.equal i + 1
done()
etcd.change null, { node: { modifiedIndex: i } }
it 'should abort request when stop is called', ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
w.stop()
etcd.stopped.should.be.true
it 'should emit stop when stopped', (done) ->
etcd = new FakeEtcd
w = new Watcher etcd, 'key'
w.on 'stop', -> done()
w.stop()
describe 'Watcher resync', ->
getNock = ->
nock 'http://127.0.0.1:2379'
it 'should resync if index is outdated and cleared', (done) ->
getNock()
.get('/v2/keys/key?waitIndex=0&wait=true')
.reply(401, {
errorCode: 401
message: "The event in requested index is outdated and cleared"
cause: "the requested history has been cleared [1007/4]"
index: 2006
})
.get('/v2/keys/key?waitIndex=2006&wait=true')
.reply(200, {
action:"set"
node:
key: "/key"
value: "banan"
modifiedIndex: 2013
createdIndex: 2013
prevNode:
key: "/key"
value: "2"
modifiedIndex: 5
createdIndex: 5
})
.get('/v2/keys/key?waitIndex=2014&wait=true').reply(200,{})
w = new Watcher (new Etcd), 'key', 0
w.on 'change', (res) ->
res.node.value.should.equal 'banan'
w.stop()
done()
gitextract_xgjntaex/
├── .gitignore
├── .npmignore
├── .travis.yml
├── LICENSE
├── README.md
├── package.json
├── src/
│ ├── client.coffee
│ ├── index.coffee
│ └── watcher.coffee
└── test/
├── client.coffee
├── index.coffee
└── watcher.coffee
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (57K chars).
[
{
"path": ".gitignore",
"chars": 56,
"preview": "lib/\nnode_modules/\n.DS_Store\ntemp/\n.nyc_output\ncoverage\n"
},
{
"path": ".npmignore",
"chars": 88,
"preview": "node_modules/\nnpm-debug.log\n.DS_Store\n.gitignore\n.travis.yml\ntemp/\n.nyc_output\ncoverage\n"
},
{
"path": ".travis.yml",
"chars": 228,
"preview": "language: node_js\nsudo: false\nnode_js:\n - \"10\"\n - \"9\"\n - \"8\"\n - \"7\"\n - \"6\"\nenv:\n - CXX=\"g++-4.8\" CC=\"gcc-4.8\"\naddo"
},
{
"path": "LICENSE",
"chars": 1497,
"preview": "Copyright (c) 2013, node-etcd authors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or w"
},
{
"path": "README.md",
"chars": 15661,
"preview": "# node-etcd\n\nA nodejs library for [ETCD v2](https://coreos.com/etcd/docs/latest/v2/api.html), written in coffee-script.\n"
},
{
"path": "package.json",
"chars": 1965,
"preview": "{\n \"name\": \"node-etcd\",\n \"version\": \"7.0.0\",\n \"description\": \"etcd library for node.js (etcd v2 api)\",\n \"repository\""
},
{
"path": "src/client.coffee",
"chars": 4561,
"preview": "request = require 'request'\ndeasync = require 'deasync'\n_ = require 'lodash'\n\n\n# Default options for re"
},
{
"path": "src/index.coffee",
"chars": 7485,
"preview": "_ = require 'lodash'\nWatcher = require './watcher'\nClient = require './client'\nHttpsAgent = (require 'ht"
},
{
"path": "src/watcher.coffee",
"chars": 2429,
"preview": "{EventEmitter} = require 'events'\n\n# A eventemitter for watching changes on a given key for etcd.\n# Emits:\n# 'change' "
},
{
"path": "test/client.coffee",
"chars": 1322,
"preview": "should = require 'should'\nnock = require 'nock'\nClient = require '../src/client.coffee'\n\ndescribe 'Client', ->\n\n client"
},
{
"path": "test/index.coffee",
"chars": 14490,
"preview": "should = require 'should'\nnock = require 'nock'\nsimple = require 'simple-mock'\nEtcd = require '../src/index.coffee'\n\n\n\n#"
},
{
"path": "test/watcher.coffee",
"chars": 3952,
"preview": "should = require 'should'\nnock = require 'nock'\n\nEtcd = require '../src/index'\nWatcher = require '../src/watcher.coffee'"
}
]
About this extraction
This page contains the full source code of the stianeikeland/node-etcd GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (52.5 KB), approximately 15.5k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.