Blame view

node_modules/loopback-datasource-juggler/lib/connectors/kv-memory.js 5.86 KB
f7563de62   Palak Handa   first commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
  'use strict';
  
  var g = require('strong-globalize')();
  
  var assert = require('assert');
  var Connector = require('loopback-connector').Connector;
  var debug = require('debug')('loopback:connector:kv-memory');
  var minimatch = require('minimatch');
  var util = require('util');
  
  exports.initialize = function initializeDataSource(dataSource, cb) {
    var settings = dataSource.settings;
    dataSource.connector = new KeyValueMemoryConnector(settings, dataSource);
    if (cb) process.nextTick(cb);
  };
  
  function KeyValueMemoryConnector(settings, dataSource) {
    Connector.call(this, 'kv-memory', settings);
  
    debug('Connector settings', settings);
  
    this.dataSource = dataSource;
    this.DataAccessObject = dataSource.juggler.KeyValueAccessObject;
  
    this._store = Object.create(null);
  
    this._setupRegularCleanup();
  };
  util.inherits(KeyValueMemoryConnector, Connector);
  
  KeyValueMemoryConnector.prototype._setupRegularCleanup = function() {
    // Scan the database for expired keys at a regular interval
    // in order to release memory. Note that GET operation checks
    // key expiration too, the scheduled cleanup is merely a performance
    // optimization.
    var self = this;
    var timer = this._cleanupTimer = setInterval(
      function() {
        if (self && self._removeExpiredItems) {
          self._removeExpiredItems();
        } else {
          // The datasource/connector was destroyed - cancel the timer
          clearInterval(timer);
        }
      },
      1000);
    this._cleanupTimer.unref();
  };
  
  KeyValueMemoryConnector._removeExpiredItems = function() {
    debug('Running scheduled cleanup of expired items.');
    for (var modelName in this._store) {
      var modelStore = this._store[modelName];
      for (var key in modelStore) {
        if (modelStore[key].isExpired()) {
          debug('Removing expired key', key);
          delete modelStore[key];
        }
      }
    }
  };
  
  KeyValueMemoryConnector.prototype._getStoreForModel = function(modelName) {
    if (!(modelName in this._store)) {
      this._store[modelName] = Object.create(null);
    }
    return this._store[modelName];
  };
  
  KeyValueMemoryConnector.prototype._removeIfExpired = function(modelName, key) {
    var store = this._getStoreForModel(modelName);
    var item = store[key];
    if (item && item.isExpired()) {
      debug('Removing expired key', key);
      delete store[key];
      item = undefined;
      return true;
    }
    return false;
  };
  
  KeyValueMemoryConnector.prototype.get =
  function(modelName, key, options, callback) {
    this._removeIfExpired(modelName, key);
  
    var store = this._getStoreForModel(modelName);
    var item = store[key];
    var value = item ? item.value : null;
    debug('GET %j %j -> %s', modelName, key, value);
  
    if (/^buffer:/.test(value)) {
      value = new Buffer(value.slice(7), 'base64');
    } else if (/^date:/.test(value)) {
      value = new Date(value.slice(5));
    } else if (value != null) {
      value = JSON.parse(value);
    }
  
    process.nextTick(function() {
      callback(null, value);
    });
  };
  
  KeyValueMemoryConnector.prototype.set =
  function(modelName, key, value, options, callback) {
    var store = this._getStoreForModel(modelName);
    var value;
    if (Buffer.isBuffer(value)) {
      value = 'buffer:' + value.toString('base64');
    } else if (value instanceof Date) {
      value = 'date:' + value.toISOString();
    } else {
      value = JSON.stringify(value);
    }
  
    debug('SET %j %j %s %j', modelName, key, value, options);
    store[key] = new StoreItem(value, options && options.ttl);
  
    process.nextTick(callback);
  };
  
  KeyValueMemoryConnector.prototype.expire =
  function(modelName, key, ttl, options, callback) {
    this._removeIfExpired(modelName, key);
  
    var store = this._getStoreForModel(modelName);
  
    if (!(key in store)) {
      return process.nextTick(function() {
        var err = new Error(g.f('Cannot expire unknown key %j', key));
        err.statusCode = 404;
        callback(err);
      });
    }
  
    debug('EXPIRE %j %j %s', modelName, key, ttl || '(never)');
    store[key].setTtl(ttl);
    process.nextTick(callback);
  };
  
  KeyValueMemoryConnector.prototype.ttl =
  function(modelName, key, options, callback) {
    this._removeIfExpired(modelName, key);
  
    var store = this._getStoreForModel(modelName);
  
    // key is unknown
    if (!(key in store)) {
      return process.nextTick(function() {
        var err = new Error(g.f('Cannot get TTL for unknown key %j', key));
        err.statusCode = 404;
        callback(err);
      });
    }
  
    var ttl = store[key].getTtl();
    debug('TTL %j %j -> %s', modelName, key, ttl);
  
    process.nextTick(function() {
      callback(null, ttl);
    });
  };
  
  KeyValueMemoryConnector.prototype.iterateKeys =
  function(modelName, filter, options, callback) {
    var store = this._getStoreForModel(modelName);
    var self = this;
    var checkFilter = createMatcher(filter.match);
  
    var keys = Object.keys(store).filter(function(key) {
      return !self._removeIfExpired(modelName, key) && checkFilter(key);
    });
  
    debug('ITERATE KEYS %j -> %s keys', modelName, keys.length);
  
    var ix = 0;
    return {
      next: function(cb) {
        var value = ix < keys.length ? keys[ix++] : undefined;
        setImmediate(function() { cb(null, value); });
      },
    };
  };
  
  function createMatcher(pattern) {
    if (!pattern) return function matchAll() { return true; };
  
    return minimatch.filter(pattern, {
      nobrace: true,
      noglobstar: true,
      dot: true,
      noext: true,
      nocomment: true,
    });
  }
  
  KeyValueMemoryConnector.prototype.disconnect = function(callback) {
    if (this._cleanupTimer)
      clearInterval(this._cleanupTimer);
    this._cleanupTimer = null;
    process.nextTick(callback);
  };
  
  function StoreItem(value, ttl) {
    this.value = value;
    this.setTtl(ttl);
  }
  
  StoreItem.prototype.isExpired = function() {
    return this.expires && this.expires <= Date.now();
  };
  
  StoreItem.prototype.setTtl = function(ttl) {
    if (ttl) {
      this.expires = Date.now() + ttl;
    } else {
      this.expires = undefined;
    }
  };
  
  StoreItem.prototype.getTtl = function() {
    return !this.expires ? undefined : this.expires - Date.now();
  };