-
Notifications
You must be signed in to change notification settings - Fork 28
/
server.js
238 lines (203 loc) · 7.03 KB
/
server.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
const path = require('path')
const os = require('os')
const Corestore = require('corestore')
const Networker = require('@corestore/networker')
const HypercoreCache = require('hypercore-cache')
const HypercoreProtocol = require('hypercore-protocol')
const hypercoreStorage = require('hypercore-default-storage')
const { NanoresourcePromise: Nanoresource } = require('nanoresource-promise/emitter')
const HRPC = require('@hyperspace/rpc')
const getNetworkOptions = require('@hyperspace/rpc/socket')
const HyperspaceDb = require('./lib/db')
const SessionState = require('./lib/session-state')
const CorestoreSession = require('./lib/sessions/corestore')
const HypercoreSession = require('./lib/sessions/hypercore')
const NetworkSession = require('./lib/sessions/network')
const startTrieExtension = require('./extensions/trie')
const TOTAL_CACHE_SIZE = 1024 * 1024 * 512
const CACHE_RATIO = 0.5
const TREE_CACHE_SIZE = TOTAL_CACHE_SIZE * CACHE_RATIO
const DATA_CACHE_SIZE = TOTAL_CACHE_SIZE * (1 - CACHE_RATIO)
const DEFAULT_STORAGE_DIR = path.join(os.homedir(), '.hyperspace', 'storage')
const MAX_PEERS = 256
const SWARM_PORT = 49737
const NAMESPACE = '@hypercore-protocol/hyperspace'
module.exports = class Hyperspace extends Nanoresource {
constructor (opts = {}) {
super()
var storage = opts.storage || DEFAULT_STORAGE_DIR
if (typeof storage === 'string') {
const storagePath = storage
storage = p => hypercoreStorage(path.join(storagePath, p))
}
const corestoreOpts = {
storage,
cacheSize: opts.cacheSize,
sparse: opts.sparse !== false,
// Collect networking statistics.
stats: true,
cache: {
data: new HypercoreCache({
maxByteSize: DATA_CACHE_SIZE,
estimateSize: val => val.length
}),
tree: new HypercoreCache({
maxByteSize: TREE_CACHE_SIZE,
estimateSize: val => 40
})
},
ifAvailable: true
}
this.corestore = new Corestore(corestoreOpts.storage, corestoreOpts)
startTrieExtension(this.corestore)
this.server = HRPC.createServer(opts.server, this._onConnection.bind(this))
this.db = new HyperspaceDb(this.corestore)
this.networker = null
this.noAnnounce = !!opts.noAnnounce
this._networkOpts = {
announceLocalNetwork: true,
preferredPort: SWARM_PORT,
maxPeers: MAX_PEERS,
...opts.network
}
this._socketOpts = getNetworkOptions(opts)
this._networkState = new Map()
}
// Nanoresource Methods
async _open () {
await this.corestore.ready()
await this.db.open()
// Note: This API is not exposed anymore -- this is a temporary fix.
const seed = this.corestore.inner._deriveSecret(NAMESPACE, 'replication-keypair')
const swarmId = this.corestore.inner._deriveSecret(NAMESPACE, 'swarm-id')
this.networker = new Networker(this.corestore, {
keyPair: HypercoreProtocol.keyPair(seed),
id: swarmId,
...this._networkOpts
})
await this.networker.listen()
this._registerCoreTimeouts()
await this._rejoin()
await this.server.listen(this._socketOpts)
}
async _close () {
await this.server.close()
await this.networker.close()
await this.db.close()
await new Promise((resolve, reject) => {
this.corestore.close(err => {
if (err) return reject(err)
return resolve(null)
})
})
}
// Public Methods
ready () {
return this.open()
}
// Private Methods
async _rejoin () {
if (this.noAnnounce) return
const networkConfigurations = await this.db.listNetworkConfigurations()
for (const config of networkConfigurations) {
if (!config.announce) continue
const joinProm = this.networker.configure(config.discoveryKey, {
announce: config.announce,
lookup: config.lookup,
// remember/discoveryKey are passed so that they will be saved in the networker's internal configurations list.
remember: true,
discoveryKey: config.discoveryKey
})
joinProm.catch(err => this.emit('swarm-error', err))
}
}
/**
* This is where we define our main heuristic for allowing hypercore gets/updates to proceed.
*/
_registerCoreTimeouts () {
const flushSets = new Map()
this.networker.on('flushed', dkey => {
const keyString = dkey.toString('hex')
if (!flushSets.has(keyString)) return
const { flushSet, peerAddSet } = flushSets.get(keyString)
callAllInSet(flushSet)
callAllInSet(peerAddSet)
})
this.corestore.on('feed', core => {
const discoveryKey = core.discoveryKey
const peerAddSet = new Set()
const flushSet = new Set()
var globalFlushed = false
if (!this.networker.swarm || this.networker.swarm.destroyed) return
this.networker.swarm.flush(() => {
if (this.networker.joined(discoveryKey)) return
globalFlushed = true
callAllInSet(flushSet)
callAllInSet(peerAddSet)
})
flushSets.set(discoveryKey.toString('hex'), { flushSet, peerAddSet })
core.once('peer-add', () => {
callAllInSet(peerAddSet)
})
const timeouts = {
get: (cb) => {
if (this.networker.joined(discoveryKey)) {
if (this.networker.flushed(discoveryKey)) return cb()
return flushSet.add(cb)
}
if (globalFlushed) return cb()
return flushSet.add(cb)
},
update: (cb) => {
const oldCb = cb
cb = (...args) => {
oldCb(...args)
}
if (core.peers.length) return cb()
if (this.networker.joined(discoveryKey)) {
if (this.networker.flushed(discoveryKey) && !core.peers.length) return cb()
return peerAddSet.add(cb)
}
if (globalFlushed) return cb()
return peerAddSet.add(cb)
}
}
core.timeouts = timeouts
})
}
_onConnection (client) {
const sessionState = new SessionState(this.corestore)
this.emit('client-open', client)
client.on('close', () => {
sessionState.deleteAll()
this.emit('client-close', client)
})
client.hyperspace.onRequest(this)
client.corestore.onRequest(new CorestoreSession(client, sessionState, this.corestore))
client.hypercore.onRequest(new HypercoreSession(client, sessionState))
client.network.onRequest(new NetworkSession(client, sessionState, this.corestore, this.networker, this.db, this._networkState, {
noAnnounce: this.noAnnounce
}))
}
// Top-level RPC Methods
status () {
const swarm = this.networker && this.networker.swarm
const remoteAddress = swarm && swarm.remoteAddress()
const holepunchable = swarm && swarm.holepunchable()
return {
version: require('./package.json').version,
apiVersion: require('@hyperspace/rpc/package.json').version,
holepunchable: holepunchable,
remoteAddress: remoteAddress ? remoteAddress.host + ':' + remoteAddress.port : ''
}
}
stop () {
return this.close()
}
}
function callAllInSet (set) {
for (const cb of set) {
cb()
}
set.clear()
}