|
| 1 | +var consul = require('consul'); |
| 2 | +var winston = require('winston'); |
| 3 | + |
| 4 | +var CachingStoreWrapper = require('ldclient-node/caching_store_wrapper'); |
| 5 | + |
| 6 | +var defaultCacheTTLSeconds = 15; |
| 7 | +var defaultPrefix = 'launchdarkly'; |
| 8 | +var notFoundError = 'not found'; // unfortunately the Consul client doesn't have error classes or codes |
| 9 | + |
| 10 | +function ConsulFeatureStore(options) { |
| 11 | + var ttl = options && options.cacheTTL; |
| 12 | + if (ttl === null || ttl === undefined) { |
| 13 | + ttl = defaultCacheTTLSeconds; |
| 14 | + } |
| 15 | + return new CachingStoreWrapper(consulFeatureStoreInternal(options), ttl); |
| 16 | +} |
| 17 | + |
| 18 | +function consulFeatureStoreInternal(options) { |
| 19 | + options = options || {}; |
| 20 | + var logger = (options.logger || |
| 21 | + new winston.Logger({ |
| 22 | + level: 'info', |
| 23 | + transports: [ |
| 24 | + new (winston.transports.Console)(), |
| 25 | + ] |
| 26 | + }) |
| 27 | + ); |
| 28 | + var client = consul(Object.assign({}, options.consulOptions, { promisify: true })); |
| 29 | + // Note, "promisify: true" causes the client to decorate all of its methods so they return Promises |
| 30 | + // instead of taking callbacks. That's the reason why we can't let the caller pass an already-created |
| 31 | + // client to us - because our code wouldn't work if it wasn't in Promise mode. |
| 32 | + var prefix = (options.prefix || defaultPrefix) + '/'; |
| 33 | + |
| 34 | + var store = {}; |
| 35 | + |
| 36 | + function kindKey(kind) { |
| 37 | + return prefix + kind.namespace + '/'; |
| 38 | + } |
| 39 | + |
| 40 | + function itemKey(kind, key) { |
| 41 | + return kindKey(kind) + key; |
| 42 | + } |
| 43 | + |
| 44 | + function initedKey() { |
| 45 | + return prefix + '$inited'; |
| 46 | + } |
| 47 | + |
| 48 | + // The issue here is that this Consul client is very literal-minded about what is an error, so if Consul |
| 49 | + // returns a 404, it treats that as a failed operation rather than just "the query didn't return anything." |
| 50 | + function suppressNotFoundErrors(promise) { |
| 51 | + return promise.catch(function(err) { |
| 52 | + if (err.message == notFoundError) { |
| 53 | + return Promise.resolve(); |
| 54 | + } |
| 55 | + }); |
| 56 | + } |
| 57 | + |
| 58 | + function logError(err, actionDesc) { |
| 59 | + logger.error('Consul error on ' + actionDesc + ': ' + err); |
| 60 | + } |
| 61 | + |
| 62 | + function errorHandler(cb, failValue, message) { |
| 63 | + return function(err) { |
| 64 | + logError(err, message); |
| 65 | + cb(failValue); |
| 66 | + }; |
| 67 | + } |
| 68 | + |
| 69 | + store.getInternal = function(kind, key, cb) { |
| 70 | + suppressNotFoundErrors(client.kv.get({ key: itemKey(kind, key) })) |
| 71 | + .then(function(result) { |
| 72 | + cb(result ? JSON.parse(result.Value) : null); |
| 73 | + }) |
| 74 | + .catch(errorHandler(cb, null, 'query of ' + kind.namespace + ' ' + key)); |
| 75 | + }; |
| 76 | + |
| 77 | + store.getAllInternal = function(kind, cb) { |
| 78 | + suppressNotFoundErrors(client.kv.get({ key: kindKey(kind), recurse: true })) |
| 79 | + .then(function(result) { |
| 80 | + var itemsOut = {}; |
| 81 | + if (result) { |
| 82 | + result.forEach(function(value) { |
| 83 | + var item = JSON.parse(value.Value); |
| 84 | + itemsOut[item.key] = item; |
| 85 | + }); |
| 86 | + } |
| 87 | + cb(itemsOut); |
| 88 | + }) |
| 89 | + .catch(errorHandler(cb, {}, 'query of all ' + kind.namespace)); |
| 90 | + }; |
| 91 | + |
| 92 | + store.initOrderedInternal = function(allData, cb) { |
| 93 | + suppressNotFoundErrors(client.kv.keys({ key: prefix })) |
| 94 | + .then(function(keys) { |
| 95 | + var oldKeys = new Set(keys || []); |
| 96 | + oldKeys.delete(initedKey()); |
| 97 | + |
| 98 | + // Write all initial data (without version checks). Note that on other platforms, we batch |
| 99 | + // these operations using the KV.txn endpoint, but the Node Consul client doesn't support that. |
| 100 | + var promises = []; |
| 101 | + allData.forEach(function(collection) { |
| 102 | + var kind = collection.kind; |
| 103 | + collection.items.forEach(function(item) { |
| 104 | + var key = itemKey(kind, item.key); |
| 105 | + oldKeys.delete(key); |
| 106 | + var op = client.kv.set({ key: key, value: JSON.stringify(item) }); |
| 107 | + promises.push(op); |
| 108 | + }); |
| 109 | + }); |
| 110 | + |
| 111 | + // Remove existing data that is not in the new list. |
| 112 | + oldKeys.forEach(function(key) { |
| 113 | + var op = client.kv.del({ key: key }); |
| 114 | + promises.push(op); |
| 115 | + }); |
| 116 | + |
| 117 | + // Always write the initialized token when we initialize. |
| 118 | + var op = client.kv.set({ key: initedKey(), value: '' }); |
| 119 | + promises.push(op); |
| 120 | + |
| 121 | + return Promise.all(promises); |
| 122 | + }) |
| 123 | + .then(function() { cb(); }) |
| 124 | + .catch(errorHandler(cb, null, 'init')); |
| 125 | + }; |
| 126 | + |
| 127 | + store.upsertInternal = function(kind, newItem, cb) { |
| 128 | + var key = itemKey(kind, newItem.key); |
| 129 | + var json = JSON.stringify(newItem); |
| 130 | + |
| 131 | + var tryUpdate = function() { |
| 132 | + return suppressNotFoundErrors(client.kv.get({ key: key })) |
| 133 | + .then(function(oldValue) { |
| 134 | + // instrumentation for unit tests |
| 135 | + if (store.testUpdateHook) { |
| 136 | + return new Promise(store.testUpdateHook).then(function() { return oldValue; }); |
| 137 | + } else { |
| 138 | + return oldValue; |
| 139 | + } |
| 140 | + }) |
| 141 | + .then(function(oldValue) { |
| 142 | + var oldItem = oldValue && JSON.parse(oldValue.Value); |
| 143 | + |
| 144 | + // Check whether the item is stale. If so, don't do the update (and return the existing item to |
| 145 | + // FeatureStoreWrapper so it can be cached) |
| 146 | + if (oldItem && oldItem.version >= newItem.version) { |
| 147 | + return oldItem; |
| 148 | + } |
| 149 | + |
| 150 | + // Otherwise, try to write. We will do a compare-and-set operation, so the write will only succeed if |
| 151 | + // the key's ModifyIndex is still equal to the previous value returned by getEvenIfDeleted. If the |
| 152 | + // previous ModifyIndex was zero, it means the key did not previously exist and the write will only |
| 153 | + // succeed if it still doesn't exist. |
| 154 | + var modifyIndex = oldValue ? oldValue.ModifyIndex : 0; |
| 155 | + var p = client.kv.set({ key: key, value: json, cas: modifyIndex }); |
| 156 | + return p.then(function(result) { |
| 157 | + return result ? newItem : tryUpdate(); // start over if the compare-and-set failed |
| 158 | + }); |
| 159 | + }); |
| 160 | + }; |
| 161 | + |
| 162 | + tryUpdate().then( |
| 163 | + function(result) { cb(null, result); }, |
| 164 | + function(err) { |
| 165 | + logger.error('failed to update: ' + err); |
| 166 | + cb(err, null); |
| 167 | + }); |
| 168 | + }; |
| 169 | + |
| 170 | + store.initializedInternal = function(cb) { |
| 171 | + suppressNotFoundErrors(client.kv.get({ key: initedKey() })) |
| 172 | + .then(function(result) { cb(!!result); }) |
| 173 | + .catch(errorHandler(cb, false, 'initialized check')); |
| 174 | + }; |
| 175 | + |
| 176 | + store.close = function() { |
| 177 | + // nothing to do here |
| 178 | + }; |
| 179 | + |
| 180 | + return store; |
| 181 | +} |
| 182 | + |
| 183 | +module.exports = ConsulFeatureStore; |
0 commit comments