This repository has been archived by the owner on Jul 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
providers.js
340 lines (298 loc) · 7.51 KB
/
providers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
'use strict'
const cache = require('hashlru')
const varint = require('varint')
const each = require('async/each')
const pull = require('pull-stream')
const CID = require('cids')
const PeerId = require('peer-id')
const Key = require('interface-datastore').Key
const c = require('./constants')
const utils = require('./utils')
/**
* This class manages known providers.
* A provider is a peer that we know to have the content for a given CID.
*
* Every `cleanupInterval` providers are checked if they
* are still valid, i.e. younger than the `provideValidity`.
* If they are not, they are deleted.
*
* To ensure the list survives restarts of the daemon,
* providers are stored in the datastore, but to ensure
* access is fast there is an LRU cache in front of that.
*/
class Providers {
/**
* @param {Object} datastore
* @param {PeerId} [self]
* @param {number} [cacheSize=256]
*/
constructor (datastore, self, cacheSize) {
this.datastore = datastore
this._log = utils.logger(self, 'providers')
/**
* How often invalid records are cleaned. (in seconds)
*
* @type {number}
*/
this.cleanupInterval = c.PROVIDERS_CLEANUP_INTERVAL
/**
* How long is a provider valid for. (in seconds)
*
* @type {number}
*/
this.provideValidity = c.PROVIDERS_VALIDITY
/**
* LRU cache size
*
* @type {number}
*/
this.lruCacheSize = cacheSize || c.PROVIDERS_LRU_CACHE_SIZE
this.providers = cache(this.lruCacheSize)
}
/**
* Release any resources.
*
* @returns {undefined}
*/
stop () {
if (this._cleaner) {
clearInterval(this._cleaner)
this._cleaner = null
}
}
/**
* Check all providers if they are still valid, and if not
* delete them.
*
* @returns {undefined}
*
* @private
*/
_cleanup () {
this._getProviderCids((err, cids) => {
if (err) {
return this._log.error('Failed to get cids', err)
}
each(cids, (cid, cb) => {
this._getProvidersMap(cid, (err, provs) => {
if (err) {
return cb(err)
}
provs.forEach((time, provider) => {
this._log('comparing: %s - %s > %s', Date.now(), time, this.provideValidity)
if (Date.now() - time > this.provideValidity) {
provs.delete(provider)
}
})
if (provs.size === 0) {
return this._deleteProvidersMap(cid, cb)
}
cb()
})
}, (err) => {
if (err) {
return this._log.error('Failed to cleanup', err)
}
this._log('Cleanup successfull')
})
})
}
/**
* Get a list of all cids that providers are known for.
*
* @param {function(Error, Array<CID>)} callback
* @returns {undefined}
*
* @private
*/
_getProviderCids (callback) {
pull(
this.datastore.query({prefix: c.PROVIDERS_KEY_PREFIX}),
pull.map((entry) => {
const parts = entry.key.toString().split('/')
if (parts.length !== 4) {
this._log.error('incorrectly formatted provider entry in datastore: %s', entry.key)
return
}
let decoded
try {
decoded = utils.decodeBase32(parts[2])
} catch (err) {
this._log.error('error decoding base32 provider key: %s', parts[2])
return
}
let cid
try {
cid = new CID(decoded)
} catch (err) {
this._log.error('error converting key to cid from datastore: %s', err.message)
}
return cid
}),
pull.filter(Boolean),
pull.collect(callback)
)
}
/**
* Get the currently known provider maps for a given CID.
*
* @param {CID} cid
* @param {function(Error, Map<PeerId, Date>)} callback
* @returns {undefined}
*
* @private
*/
_getProvidersMap (cid, callback) {
const provs = this.providers.get(makeProviderKey(cid))
if (!provs) {
return loadProviders(this.datastore, cid, callback)
}
callback(null, provs)
}
/**
* Completely remove a providers map entry for a given CID.
*
* @param {CID} cid
* @param {function(Error)} callback
* @returns {undefined}
*
* @private
*/
_deleteProvidersMap (cid, callback) {
const dsKey = makeProviderKey(cid)
this.providers.set(dsKey, null)
const batch = this.datastore.batch()
pull(
this.datastore.query({
keysOnly: true,
prefix: dsKey
}),
pull.through((entry) => batch.delete(entry.key)),
pull.onEnd((err) => {
if (err) {
return callback(err)
}
batch.commit(callback)
})
)
}
get cleanupInterval () {
return this._cleanupInterval
}
set cleanupInterval (val) {
this._cleanupInterval = val
if (this._cleaner) {
clearInterval(this._cleaner)
}
this._cleaner = setInterval(
() => this._cleanup(),
this.cleanupInterval
)
}
/**
* Add a new provider.
*
* @param {CID} cid
* @param {PeerId} provider
* @param {function(Error)} callback
* @returns {undefined}
*/
addProvider (cid, provider, callback) {
this._log('addProvider %s', cid.toBaseEncodedString())
const dsKey = makeProviderKey(cid)
const provs = this.providers.get(dsKey)
const next = (err, provs) => {
if (err) {
return callback(err)
}
this._log('loaded %s provs', provs.size)
const now = Date.now()
provs.set(provider, now)
this.providers.set(dsKey, provs)
writeProviderEntry(this.datastore, cid, provider, now, callback)
}
if (!provs) {
loadProviders(this.datastore, cid, next)
} else {
next(null, provs)
}
}
/**
* Get a list of providers for the given CID.
*
* @param {CID} cid
* @param {function(Error, Array<PeerId>)} callback
* @returns {undefined}
*/
getProviders (cid, callback) {
this._log('getProviders %s', cid.toBaseEncodedString())
this._getProvidersMap(cid, (err, provs) => {
if (err) {
return callback(err)
}
callback(null, Array.from(provs.keys()))
})
}
}
/**
* Encode the given key its matching datastore key.
*
* @param {CID} cid
* @returns {string}
*
* @private
*/
function makeProviderKey (cid) {
return c.PROVIDERS_KEY_PREFIX + utils.encodeBase32(cid.buffer)
}
/**
* Write a provider into the given store.
*
* @param {Datastore} store
* @param {CID} cid
* @param {PeerId} peer
* @param {number} time
* @param {function(Error)} callback
* @returns {undefined}
*
* @private
*/
function writeProviderEntry (store, cid, peer, time, callback) {
const dsKey = [
makeProviderKey(cid),
'/',
utils.encodeBase32(peer.id)
].join('')
store.put(new Key(dsKey), Buffer.from(varint.encode(time)), callback)
}
/**
* Load providers from the store.
*
* @param {Datastore} store
* @param {CID} cid
* @param {function(Error, Map<PeerId, Date>)} callback
* @returns {undefined}
*
* @private
*/
function loadProviders (store, cid, callback) {
pull(
store.query({prefix: makeProviderKey(cid)}),
pull.map((entry) => {
const parts = entry.key.toString().split('/')
const lastPart = parts[parts.length - 1]
const rawPeerId = utils.decodeBase32(lastPart)
return [new PeerId(rawPeerId), readTime(entry.value)]
}),
pull.collect((err, res) => {
if (err) {
return callback(err)
}
return callback(null, new Map(res))
})
)
}
function readTime (buf) {
return varint.decode(buf)
}
module.exports = Providers