This repository was archived by the owner on Sep 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathentry-io.js.html
231 lines (189 loc) · 7.96 KB
/
entry-io.js.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: entry-io.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: entry-io.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>'use strict'
const pMap = require('p-map')
const pDoWhilst = require('p-do-whilst')
const Entry = require('./entry')
const hasItems = arr => arr && arr.length > 0
class EntryIO {
// Fetch log graphs in parallel
static async fetchParallel (ipfs, hashes, { length, exclude = [], timeout, concurrency, onProgressCallback }) {
const fetchOne = async (hash) => EntryIO.fetchAll(ipfs, hash, { length, exclude, timeout, onProgressCallback, concurrency })
const concatArrays = (arr1, arr2) => arr1.concat(arr2)
const flatten = (arr) => arr.reduce(concatArrays, [])
const res = await pMap(hashes, fetchOne, { concurrency: Math.max(concurrency || hashes.length, 1) })
return flatten(res)
}
/**
* Fetch log entries
*
* @param {IPFS} [ipfs] An IPFS instance
* @param {string} [hash] Multihash of the entry to fetch
* @param {string} [parent] Parent of the node to be fetched
* @param {Object} [all] Entries to skip
* @param {Number} [amount=-1] How many entries to fetch
* @param {Number} [depth=0] Current depth of the recursion
* @param {function(hash, entry, parent, depth)} onProgressCallback
* @returns {Promise<Array<Entry>>}
*/
static async fetchAll (ipfs, hashes, { length = -1, exclude = [], timeout, onProgressCallback, onStartProgressCallback, concurrency = 32, delay = 0 } = {}) {
const result = []
const cache = {}
const loadingCache = {}
const loadingQueue = Array.isArray(hashes)
? { 0: hashes.slice() }
: { 0: [hashes] }
let running = 0 // keep track of how many entries are being fetched at any time
let maxClock = 0 // keep track of the latest clock time during load
let minClock = 0 // keep track of the minimum clock time during load
// Does the loading queue have more to process?
const loadingQueueHasMore = () => Object.values(loadingQueue).find(hasItems) !== undefined
// Add a multihash to the loading queue
const addToLoadingQueue = (e, idx) => {
if (!loadingCache[e]) {
if (!loadingQueue[idx]) loadingQueue[idx] = []
if (!loadingQueue[idx].includes(e)) {
loadingQueue[idx].push(e)
}
loadingCache[e] = true
}
}
// Get the next items to process from the loading queue
const getNextFromQueue = (length = 1) => {
const getNext = (res, key, idx) => {
const nextItems = loadingQueue[key]
while (nextItems.length > 0 && res.length < length) {
const hash = nextItems.shift()
res.push(hash)
}
if (nextItems.length === 0) {
delete loadingQueue[key]
}
return res
}
return Object.keys(loadingQueue).reduce(getNext, [])
}
// Add entries that we don't need to fetch to the "cache"
const addToExcludeCache = e => { cache[e.hash] = true }
// Fetch one entry and add it to the results
const fetchEntry = async (hash) => {
if (!hash || cache[hash]) {
return
}
return new Promise((resolve, reject) => {
// Resolve the promise after a timeout (if given) in order to
// not get stuck loading a block that is unreachable
const timer = timeout && timeout > 0
? setTimeout(() => {
console.warn(`Warning: Couldn't fetch entry '${hash}', request timed out (${timeout}ms)`)
resolve()
}, timeout)
: null
const addToResults = (entry) => {
if (Entry.isEntry(entry)) {
const ts = entry.clock.time
// Update min/max clocks
maxClock = Math.max(maxClock, ts)
minClock = result.length > 0
? Math.min(result[result.length - 1].clock.time, minClock)
: maxClock
const isLater = (result.length >= length && ts >= minClock)
const calculateIndex = (idx) => maxClock - ts + ((idx + 1) * idx)
// Add the entry to the results if
// 1) we're fetching all entries
// 2) results is not filled yet
// the clock of the entry is later than current known minimum clock time
if (length < 0 || result.length < length || isLater) {
result.push(entry)
cache[hash] = true
if (onProgressCallback) {
onProgressCallback(hash, entry, result.length, result.length)
}
}
if (length < 0) {
// If we're fetching all entries (length === -1), adds nexts and refs to the queue
entry.next.forEach(addToLoadingQueue)
if (entry.refs) entry.refs.forEach(addToLoadingQueue)
} else {
// If we're fetching entries up to certain length,
// fetch the next if result is filled up, to make sure we "check"
// the next entry if its clock is later than what we have in the result
if (result.length < length || ts > minClock || (ts === minClock && !cache[entry.hash])) {
entry.next.forEach(e => addToLoadingQueue(e, calculateIndex(0)))
}
if (entry.refs && (result.length + entry.refs.length <= length)) {
entry.refs.forEach((e, i) => addToLoadingQueue(e, calculateIndex(i)))
}
}
}
}
if (onStartProgressCallback) {
onStartProgressCallback(hash, null, 0, result.length)
}
// Load the entry
Entry.fromMultihash(ipfs, hash).then(async (entry) => {
try {
// Add it to the results
addToResults(entry)
// Simulate network latency (for debugging purposes)
if (delay > 0) {
const sleep = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms))
await sleep(delay)
}
resolve()
} catch (e) {
reject(e)
} finally {
clearTimeout(timer)
}
}).catch(reject)
})
}
// One loop of processing the loading queue
const _processQueue = async () => {
if (running < concurrency) {
const nexts = getNextFromQueue(concurrency)
running += nexts.length
await pMap(nexts, fetchEntry)
running -= nexts.length
}
}
// Add entries to exclude from processing to the cache before we start
exclude.forEach(addToExcludeCache)
// Fetch entries
await pDoWhilst(_processQueue, loadingQueueHasMore)
return result
}
}
module.exports = EntryIO
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="GSet.html">GSet</a></li><li><a href="Log.html">Log</a></li></ul><h3>Global</h3><ul><li><a href="global.html#LastWriteWins">LastWriteWins</a></li><li><a href="global.html#NoZeroes">NoZeroes</a></li><li><a href="global.html#SortByClockId">SortByClockId</a></li><li><a href="global.html#SortByClocks">SortByClocks</a></li><li><a href="global.html#SortByEntryHash">SortByEntryHash</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.6</a> on Fri Dec 11 2020 17:11:17 GMT-0500 (Eastern Standard Time)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>