@cero-base/core 3.4.1 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/package.json +20 -14
- package/src/call/bridge.js +262 -0
- package/src/call/index.js +150 -0
- package/src/call/peers.js +426 -0
- package/src/database/dispatch.js +8 -3
- package/src/database/index.js +110 -18
- package/src/lib/constants.js +0 -3
- package/src/lib/spec/index.js +67 -2
- package/src/lib/spec/schema.json +55 -1
- package/src/lib/utils.js +16 -0
- package/src/mailbox/inbox.js +14 -1
- package/src/mailbox/index.js +15 -6
- package/src/network/discovery.js +95 -49
- package/src/network/index.js +306 -83
- package/src/pairing/index.js +2 -2
- package/types/call/bridge.d.ts +95 -0
- package/types/call/index.d.ts +91 -0
- package/types/call/peers.d.ts +184 -0
- package/types/database/index.d.ts +39 -7
- package/types/lib/constants.d.ts +0 -2
- package/types/lib/spec/index.d.ts +28 -0
- package/types/lib/utils.d.ts +13 -1
- package/types/mailbox/inbox.d.ts +2 -0
- package/types/mailbox/index.d.ts +2 -0
- package/types/network/discovery.d.ts +60 -23
- package/types/network/index.d.ts +119 -30
- package/src/network/presence.js +0 -135
- package/types/network/presence.d.ts +0 -63
package/src/network/index.js
CHANGED
|
@@ -7,17 +7,18 @@ import safetyCatch from 'safety-catch'
|
|
|
7
7
|
import { decode as decodeKey } from 'hypercore-id-encoding'
|
|
8
8
|
import { hash } from 'hypercore-crypto'
|
|
9
9
|
import HyperDHT from 'hyperdht'
|
|
10
|
-
import
|
|
10
|
+
import Replicator from 'hyperjoin'
|
|
11
11
|
import b4a from 'b4a'
|
|
12
12
|
|
|
13
|
-
import { ACTIVE, PASSIVE } from '../lib/constants.js'
|
|
14
13
|
import { CeroError } from '../lib/errors.js'
|
|
15
14
|
import { Discovery } from './discovery.js'
|
|
16
|
-
import { Presence } from './presence.js'
|
|
17
15
|
|
|
18
16
|
// a live remote answers our header in milliseconds; udx gives up on a silent one only after ~13 s
|
|
19
17
|
const SILENT_TIMEOUT = 3000
|
|
20
|
-
|
|
18
|
+
// the replicator runs a failed query again only in 10 min: after these, then the last over and over, while it keeps failing
|
|
19
|
+
const RELOOKUPS = [1000, 5000, 20000, 60000]
|
|
20
|
+
const DIALED = 30
|
|
21
|
+
const REDIAL = 1000
|
|
21
22
|
|
|
22
23
|
function toKey(k) {
|
|
23
24
|
return typeof k === 'string' ? decodeKey(k) : k
|
|
@@ -33,17 +34,27 @@ export function channelTopic(topic, channel) {
|
|
|
33
34
|
* @property {Array<{ host: string, port: number }>} [bootstrap] Custom DHT bootstrap nodes.
|
|
34
35
|
* @property {(remotePublicKey: Uint8Array, payload: unknown) => boolean} [firewall] Incoming-connection filter.
|
|
35
36
|
* @property {Array<string | Uint8Array>} [relayThrough] Blind relay public keys; a connection goes through one only when a direct one fails or this device sits behind a randomizing NAT.
|
|
36
|
-
* @property {number[]} [backoffs] Reconnect backoff tiers in ms; the default escalates to ~10min, far too slow for local nets.
|
|
37
37
|
* @property {string} [channel] Optional network-isolation label; only same-channel peers meet.
|
|
38
38
|
* @property {import('corestore')} store Corestore; every connection replicates it, so every core it holds rides every peer.
|
|
39
39
|
* @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached database/blob core is mirrored through them for offline sync.
|
|
40
40
|
* @property {(err: Error) => void} [onerror] Background-task error handler.
|
|
41
|
-
* @property {{ active?: number,
|
|
41
|
+
* @property {{ active?: number, idle?: number, known?: number, connections?: number }} [presence] The budget for topics in the rotation: how many announce at once besides the ones in use, and the ms a topic keeps announcing after its last use, or keeps a slot. `known` is how many devices a database remembers to dial by their keys, 0 for none. `connections` is how many connections the network keeps at once: a device that dials in past it is told to try later.
|
|
42
|
+
*
|
|
43
|
+
* @typedef {object} Entry One replicator session per topic, shared by every join of it.
|
|
44
|
+
* @property {string} id
|
|
45
|
+
* @property {import('./discovery.js').Session} session
|
|
46
|
+
* @property {import('corestore')} store The store session the replicator session lives on.
|
|
47
|
+
* @property {number} refs Joins holding the topic.
|
|
48
|
+
* @property {number} pins Joins pinning it.
|
|
49
|
+
* @property {number} used When it was last touched.
|
|
50
|
+
* @property {ReturnType<typeof setTimeout> | null} held Set while a touch keeps it announcing.
|
|
51
|
+
* @property {Uint8Array[]} known Network keys of devices that held the topic before.
|
|
52
|
+
* @property {number} dialed When they were last dialed.
|
|
42
53
|
*/
|
|
43
54
|
|
|
44
55
|
/**
|
|
45
|
-
*
|
|
46
|
-
* replicates the store.
|
|
56
|
+
* Peer discovery and connections on hyperjoin, plus a shared wakeup channel. Every connection,
|
|
57
|
+
* the replicator's or injected, replicates the store.
|
|
47
58
|
*/
|
|
48
59
|
export class Network extends ReadyResource {
|
|
49
60
|
/** @param {NetworkOpts} opts */
|
|
@@ -51,7 +62,6 @@ export class Network extends ReadyResource {
|
|
|
51
62
|
bootstrap,
|
|
52
63
|
firewall,
|
|
53
64
|
relayThrough,
|
|
54
|
-
backoffs,
|
|
55
65
|
channel,
|
|
56
66
|
store,
|
|
57
67
|
mirrors,
|
|
@@ -63,20 +73,27 @@ export class Network extends ReadyResource {
|
|
|
63
73
|
this.bootstrap = bootstrap || null
|
|
64
74
|
this.firewall = firewall || null
|
|
65
75
|
this.relayThrough = relayThrough?.map(toKey) || null
|
|
66
|
-
this.backoffs = backoffs || null
|
|
67
76
|
this.channel = channel || null
|
|
68
77
|
/** @type {import('corestore')} */
|
|
69
78
|
this.store = store
|
|
70
79
|
/** @type {Uint8Array[]} */
|
|
71
80
|
this.mirrors = (mirrors || []).map(toKey)
|
|
81
|
+
/** @type {{ active: number, idle: number, known: number, connections: number }} */
|
|
82
|
+
this.presence = { active: 8, idle: 30_000, known: 8, connections: 40 }
|
|
83
|
+
for (const [name, value] of Object.entries(presence || {})) {
|
|
84
|
+
if (value !== undefined) this.presence[name] = value
|
|
85
|
+
}
|
|
72
86
|
|
|
73
87
|
/** @private */
|
|
74
|
-
this.
|
|
88
|
+
this._replicator = null
|
|
89
|
+
/** @private */
|
|
90
|
+
this._dht = null
|
|
75
91
|
/** @type {import('protomux-wakeup')} */
|
|
76
92
|
this.wakeup = new ProtomuxWakeup()
|
|
77
|
-
this.presence = new Presence(this, presence)
|
|
78
93
|
|
|
79
|
-
/** @private */
|
|
94
|
+
/** @private @type {Map<string, Entry>} */
|
|
95
|
+
this._sessions = new Map()
|
|
96
|
+
/** @private @type {Set<Discovery>} */
|
|
80
97
|
this._discoveries = new Set()
|
|
81
98
|
/** @private */
|
|
82
99
|
this._injected = new Set()
|
|
@@ -85,61 +102,87 @@ export class Network extends ReadyResource {
|
|
|
85
102
|
/** @private */
|
|
86
103
|
this._peeringClosed = false
|
|
87
104
|
/** @private */
|
|
88
|
-
this.
|
|
105
|
+
this._listening = null
|
|
106
|
+
/** @private */
|
|
107
|
+
this._refreshing = false
|
|
108
|
+
/** @private */
|
|
109
|
+
this._resuming = null
|
|
89
110
|
/** @private */
|
|
90
111
|
this._relookup = null
|
|
91
112
|
/** @private */
|
|
92
113
|
this._onerror = onerror
|
|
93
114
|
}
|
|
94
115
|
|
|
95
|
-
/** @returns {import('
|
|
96
|
-
get
|
|
97
|
-
return this.
|
|
116
|
+
/** @returns {import('hyperjoin') | null} The underlying hyperjoin replicator, or null before ready / after close. */
|
|
117
|
+
get replicator() {
|
|
118
|
+
return this._replicator
|
|
98
119
|
}
|
|
99
120
|
|
|
100
|
-
/** @returns {
|
|
121
|
+
/** @returns {import('hyperdht') | null} The DHT the replicator and the mirrors share. */
|
|
122
|
+
get dht() {
|
|
123
|
+
return this._dht
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** @returns {Map<string, object>} Known peers keyed by public-key hex. */
|
|
101
127
|
get peers() {
|
|
102
|
-
return this.
|
|
128
|
+
return this._replicator ? this._replicator.peers : new Map()
|
|
103
129
|
}
|
|
104
130
|
|
|
105
|
-
/** @returns {Set<import('@hyperswarm/secret-stream')>} Live connection streams —
|
|
131
|
+
/** @returns {Set<import('@hyperswarm/secret-stream')>} Live connection streams — the replicator's and injected. */
|
|
106
132
|
get connections() {
|
|
107
|
-
|
|
108
|
-
|
|
133
|
+
const streams = new Set(this._injected)
|
|
134
|
+
if (this._replicator) for (const c of this._replicator.connections) streams.add(c.stream)
|
|
135
|
+
return streams
|
|
109
136
|
}
|
|
110
137
|
|
|
111
138
|
/** @returns {boolean} */
|
|
112
139
|
get suspended() {
|
|
113
|
-
return this.
|
|
140
|
+
return this._replicator?.suspended === true
|
|
114
141
|
}
|
|
115
142
|
|
|
116
143
|
/** @private */
|
|
117
144
|
async _open() {
|
|
118
|
-
// timeouts follow each node's measured round trip, not a flat second a try
|
|
119
|
-
const dht = new HyperDHT({
|
|
145
|
+
// timeouts follow each node's measured round trip, not a flat second a try
|
|
146
|
+
const dht = (this._dht = new HyperDHT({
|
|
120
147
|
bootstrap: this.bootstrap,
|
|
121
148
|
adaptiveTimeout: { min: 150, max: 1000 }
|
|
122
|
-
})
|
|
123
|
-
const opts = {
|
|
149
|
+
}))
|
|
150
|
+
const opts = {
|
|
151
|
+
dht,
|
|
152
|
+
slots: this.presence.active,
|
|
153
|
+
minActiveTime: this.presence.idle,
|
|
154
|
+
maxConnections: this.presence.connections,
|
|
155
|
+
// it dials the peers it finds up to this many, or up to the cap when that is lower
|
|
156
|
+
minConnections: Math.min(DIALED, this.presence.connections),
|
|
157
|
+
// a join owns its topic until it is destroyed
|
|
158
|
+
gcIdleTime: Infinity,
|
|
159
|
+
// dial a peer the moment it is found, where the replicator waits up to 500 ms
|
|
160
|
+
jitter: 0
|
|
161
|
+
}
|
|
124
162
|
if (this.firewall) opts.firewall = this.firewall
|
|
125
163
|
if (this.relayThrough) opts.relayThrough = this.relayThrough
|
|
126
|
-
if (this.backoffs) opts.backoffs = this.backoffs
|
|
127
164
|
|
|
128
|
-
const
|
|
165
|
+
const rep = (this._replicator = new Replicator(this.store, opts))
|
|
129
166
|
// back online after a NAT rebind or a router restart, peers may hold a stale address for us
|
|
130
167
|
dht.on('network-update', () => {
|
|
168
|
+
if (!dht.online) return
|
|
169
|
+
// the queries sent while it was away failed
|
|
170
|
+
this._watch(this._lookup()).catch(safetyCatch)
|
|
171
|
+
this._redial()
|
|
131
172
|
// a tick later: the dht's own wake-up in this event would clear a refresh made now
|
|
132
|
-
|
|
173
|
+
setTimeout(() => this.closing || rep.server.refresh(), 0)
|
|
133
174
|
})
|
|
134
|
-
|
|
175
|
+
rep.on('connected', ({ stream, info }) => {
|
|
135
176
|
if (this.closing || this.closed) {
|
|
136
177
|
stream.destroy()
|
|
137
178
|
return
|
|
138
179
|
}
|
|
139
180
|
dropIfSilent(stream)
|
|
140
|
-
stream.on('close', () => this._lose(stream.remotePublicKey))
|
|
141
181
|
this._add(stream, info)
|
|
142
182
|
})
|
|
183
|
+
await rep.ready()
|
|
184
|
+
// the server listens in the background and a topic announces only once it does; with nothing joined, a flush ends there
|
|
185
|
+
this._listening = rep.flush()
|
|
143
186
|
|
|
144
187
|
if (this.mirrors.length) this.peering()
|
|
145
188
|
}
|
|
@@ -147,7 +190,6 @@ export class Network extends ReadyResource {
|
|
|
147
190
|
/** @private */
|
|
148
191
|
async _close() {
|
|
149
192
|
clearTimeout(this._relookup)
|
|
150
|
-
this._lost.clear()
|
|
151
193
|
for (const conn of [...this._injected]) {
|
|
152
194
|
try {
|
|
153
195
|
conn.destroy()
|
|
@@ -157,18 +199,16 @@ export class Network extends ReadyResource {
|
|
|
157
199
|
}
|
|
158
200
|
this._injected.clear()
|
|
159
201
|
|
|
160
|
-
//
|
|
161
|
-
this.presence.close()
|
|
202
|
+
// leave every topic now, never await the DHT unannounce round-trips
|
|
162
203
|
for (const d of [...this._discoveries]) d.destroy().catch(safetyCatch)
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
}
|
|
204
|
+
|
|
205
|
+
// close still awaits the unannounces and a server.close round-trip; cap it
|
|
206
|
+
const rep = this._replicator
|
|
207
|
+
this._replicator = null
|
|
208
|
+
if (rep) await capped(rep.close().catch(safetyCatch), 750)
|
|
209
|
+
const dht = this._dht
|
|
210
|
+
this._dht = null
|
|
211
|
+
if (dht) await dht.destroy().catch(safetyCatch)
|
|
172
212
|
|
|
173
213
|
if (this._blindPeering) {
|
|
174
214
|
try {
|
|
@@ -199,8 +239,8 @@ export class Network extends ReadyResource {
|
|
|
199
239
|
inject(stream, { isInitiator } = {}) {
|
|
200
240
|
if (this.closing || this.closed) throw CeroError.CLOSED('Network')
|
|
201
241
|
if (!stream) throw CeroError.REQUIRED('stream')
|
|
202
|
-
// a raw duplex handshakes as the
|
|
203
|
-
const keyPair = this.
|
|
242
|
+
// a raw duplex handshakes as the replicator does
|
|
243
|
+
const keyPair = this._replicator?.keyPair ?? undefined
|
|
204
244
|
const conn =
|
|
205
245
|
stream.noiseStream === stream
|
|
206
246
|
? stream
|
|
@@ -210,6 +250,8 @@ export class Network extends ReadyResource {
|
|
|
210
250
|
conn.on('close', () => this._injected.delete(conn))
|
|
211
251
|
conn.on('error', safetyCatch) // a dropped radio link must not crash the host
|
|
212
252
|
|
|
253
|
+
// the replicator replicates the store on its own connections only
|
|
254
|
+
this.store.replicate(conn)
|
|
213
255
|
this._add(conn, { injected: true })
|
|
214
256
|
return conn
|
|
215
257
|
}
|
|
@@ -217,7 +259,6 @@ export class Network extends ReadyResource {
|
|
|
217
259
|
/** @private */
|
|
218
260
|
_add(conn, info) {
|
|
219
261
|
this.wakeup.addStream(conn)
|
|
220
|
-
this.store.replicate(conn)
|
|
221
262
|
this.emit('connection', conn, info)
|
|
222
263
|
}
|
|
223
264
|
|
|
@@ -242,7 +283,7 @@ export class Network extends ReadyResource {
|
|
|
242
283
|
peering() {
|
|
243
284
|
if (this.closing || this.closed || this._peeringClosed) throw CeroError.CLOSED('Network')
|
|
244
285
|
if (!this._blindPeering) {
|
|
245
|
-
this._blindPeering = new BlindPeering(this.
|
|
286
|
+
this._blindPeering = new BlindPeering(this._dht, this.store, {
|
|
246
287
|
blindPeers: this.mirrors.map((key) => ({ key })),
|
|
247
288
|
wakeup: this.wakeup,
|
|
248
289
|
pick: 2
|
|
@@ -252,67 +293,120 @@ export class Network extends ReadyResource {
|
|
|
252
293
|
}
|
|
253
294
|
|
|
254
295
|
/**
|
|
255
|
-
* Wait for pending DHT announces and
|
|
296
|
+
* Wait for pending DHT announces, lookups and dials to settle, bounded by timeout.
|
|
256
297
|
*
|
|
257
298
|
* @param {{ timeout?: number }} [opts]
|
|
258
299
|
* @returns {Promise<void>}
|
|
259
300
|
*/
|
|
260
301
|
async flush({ timeout = 500 } = {}) {
|
|
261
|
-
|
|
262
|
-
|
|
302
|
+
const rep = this._replicator
|
|
303
|
+
if (!rep) return
|
|
304
|
+
await capped(this._flush(rep), timeout)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** @private */
|
|
308
|
+
async _flush(rep) {
|
|
309
|
+
// a join queues its announce only when the rotation runs
|
|
310
|
+
await this._rotate()
|
|
311
|
+
await rep.flush()
|
|
263
312
|
}
|
|
264
313
|
|
|
265
314
|
/**
|
|
266
|
-
* Pause the
|
|
315
|
+
* Pause the network — keeps state, drops sockets. Idempotent.
|
|
267
316
|
*
|
|
268
317
|
* @returns {Promise<void>}
|
|
269
318
|
*/
|
|
270
319
|
async suspend() {
|
|
271
320
|
if (this.closing || this.closed) return
|
|
272
321
|
await this._blindPeering?.suspend()
|
|
273
|
-
await this.
|
|
322
|
+
await this._replicator?.suspend()
|
|
323
|
+
await this._dht?.suspend()
|
|
274
324
|
clearTimeout(this._relookup)
|
|
325
|
+
this._relookup = null
|
|
275
326
|
}
|
|
276
327
|
|
|
277
328
|
/**
|
|
278
|
-
* Resume a suspended
|
|
329
|
+
* Resume a suspended network. Idempotent.
|
|
279
330
|
*
|
|
280
331
|
* @returns {Promise<void>}
|
|
281
332
|
*/
|
|
282
333
|
async resume() {
|
|
283
334
|
if (this.closing || this.closed || !this.suspended) return
|
|
284
|
-
|
|
335
|
+
this._resuming = this._resume()
|
|
336
|
+
try {
|
|
337
|
+
await this._resuming
|
|
338
|
+
} finally {
|
|
339
|
+
this._resuming = null
|
|
340
|
+
}
|
|
285
341
|
await this._blindPeering?.resume()
|
|
286
|
-
// the
|
|
287
|
-
this.
|
|
342
|
+
// the queries the replicator runs at resume fail when they go out before the network is back
|
|
343
|
+
this._watch(this._active()).catch(safetyCatch)
|
|
344
|
+
this._redial()
|
|
288
345
|
this.emit('resume')
|
|
289
346
|
}
|
|
290
347
|
|
|
348
|
+
// the replicator resumes every session it holds and a destroyed one throws there: a leave in
|
|
349
|
+
// flight finishes first, and one that starts meanwhile waits in _leave
|
|
350
|
+
/** @private */
|
|
351
|
+
async _resume() {
|
|
352
|
+
await this._dht.resume()
|
|
353
|
+
const rep = this._replicator
|
|
354
|
+
await Promise.all([...rep.sessions.values()].map((session) => session.closing))
|
|
355
|
+
await rep.resume()
|
|
356
|
+
}
|
|
357
|
+
|
|
291
358
|
/**
|
|
292
|
-
*
|
|
359
|
+
* Join a 32-byte topic and return a Discovery handle. Pinned by default: it announces and
|
|
360
|
+
* looks up now; `pin: false` leaves it to the rotation.
|
|
293
361
|
*
|
|
294
362
|
* @param {Uint8Array} topic
|
|
295
|
-
* @param {{
|
|
363
|
+
* @param {{ pin?: boolean }} [opts]
|
|
296
364
|
* @returns {Discovery}
|
|
297
365
|
*/
|
|
298
|
-
join(topic, {
|
|
299
|
-
if (mode !== ACTIVE && mode !== PASSIVE) {
|
|
300
|
-
throw CeroError.INVALID('mode must be "active" or "passive"')
|
|
301
|
-
}
|
|
366
|
+
join(topic, { pin = true } = {}) {
|
|
302
367
|
if (this.closing || this.closed) throw CeroError.CLOSED('Network')
|
|
303
|
-
if (!this.
|
|
368
|
+
if (!this._replicator) throw CeroError.NOT_READY('Network', 'network')
|
|
304
369
|
if (!isTopic(topic)) throw CeroError.INVALID('topic must be a 32-byte buffer')
|
|
305
370
|
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
371
|
+
const key = channelTopic(topic, this.channel)
|
|
372
|
+
const id = b4a.toHex(key)
|
|
373
|
+
let entry = this._sessions.get(id)
|
|
374
|
+
if (!entry) {
|
|
375
|
+
// a store session per topic: the root store collects no listener per topic
|
|
376
|
+
const store = this.store.session()
|
|
377
|
+
const session = this._replicator.join(store, key, { deferSwarming: false })
|
|
378
|
+
const made = (entry = {
|
|
379
|
+
id,
|
|
380
|
+
session,
|
|
381
|
+
store,
|
|
382
|
+
refs: 0,
|
|
383
|
+
pins: 0,
|
|
384
|
+
used: 0,
|
|
385
|
+
held: null,
|
|
386
|
+
known: [],
|
|
387
|
+
dialed: 0
|
|
388
|
+
})
|
|
389
|
+
session.on('activate', () => this._dial(made))
|
|
390
|
+
this._sessions.set(id, entry)
|
|
391
|
+
}
|
|
392
|
+
entry.refs++
|
|
310
393
|
|
|
311
|
-
const discovery = new Discovery(this,
|
|
394
|
+
const discovery = new Discovery(this, entry, pin)
|
|
312
395
|
this._discoveries.add(discovery)
|
|
313
396
|
return discovery
|
|
314
397
|
}
|
|
315
398
|
|
|
399
|
+
/**
|
|
400
|
+
* Where a topic stands on this network.
|
|
401
|
+
*
|
|
402
|
+
* @param {Uint8Array} topic
|
|
403
|
+
* @returns {'inactive' | 'pinned' | 'autostarted' | 'discovering' | null} Its session's state, null when not joined.
|
|
404
|
+
*/
|
|
405
|
+
state(topic) {
|
|
406
|
+
const entry = this._sessions.get(b4a.toHex(channelTopic(topic, this.channel)))
|
|
407
|
+
return entry ? entry.session.state : null
|
|
408
|
+
}
|
|
409
|
+
|
|
316
410
|
/**
|
|
317
411
|
* Whether `store` replicates on this network's connections: the network's store or a session of it.
|
|
318
412
|
*
|
|
@@ -352,28 +446,157 @@ export class Network extends ReadyResource {
|
|
|
352
446
|
})
|
|
353
447
|
}
|
|
354
448
|
|
|
355
|
-
// hyperswarm stops redialing a peer after a few failed tries and looks it up again only every 10 min
|
|
356
449
|
/** @private */
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
450
|
+
async _leave(discovery) {
|
|
451
|
+
this._discoveries.delete(discovery)
|
|
452
|
+
const { entry } = discovery
|
|
453
|
+
if (--entry.refs > 0) return
|
|
454
|
+
try {
|
|
455
|
+
await this._resuming
|
|
456
|
+
} catch (err) {
|
|
457
|
+
safetyCatch(err)
|
|
458
|
+
}
|
|
459
|
+
// joined again meanwhile and the same session carries on, or another leave of it got here first
|
|
460
|
+
if (entry.refs > 0 || this._sessions.get(entry.id) !== entry) return
|
|
461
|
+
this._sessions.delete(entry.id)
|
|
462
|
+
try {
|
|
463
|
+
await entry.session.destroy()
|
|
464
|
+
await entry.store.close()
|
|
465
|
+
} catch (err) {
|
|
466
|
+
safetyCatch(err)
|
|
467
|
+
}
|
|
361
468
|
}
|
|
362
469
|
|
|
470
|
+
// up at once, down only after idle: a topic just used does not wait for a slot, and one at the edge of the
|
|
471
|
+
// budget does not churn the DHT
|
|
363
472
|
/** @private */
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
473
|
+
_use(entry) {
|
|
474
|
+
entry.used = Date.now()
|
|
475
|
+
if (entry.held === null) {
|
|
476
|
+
this._hold(entry, this.presence.idle)
|
|
477
|
+
this._apply(entry)
|
|
478
|
+
}
|
|
479
|
+
// a topic in steady use, or pinned by a join, starts no more: the devices it knows are dialed again, a round a
|
|
480
|
+
// second at most
|
|
481
|
+
if (entry.used - entry.dialed >= REDIAL) this._dial(entry)
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** @private */
|
|
485
|
+
_hold(entry, ms) {
|
|
486
|
+
entry.held = setTimeout(() => {
|
|
487
|
+
const left = entry.used + this.presence.idle - Date.now()
|
|
488
|
+
if (left > 0) {
|
|
489
|
+
this._hold(entry, left)
|
|
490
|
+
} else {
|
|
491
|
+
entry.held = null
|
|
492
|
+
this._apply(entry)
|
|
371
493
|
}
|
|
372
|
-
|
|
373
|
-
|
|
494
|
+
}, ms)
|
|
495
|
+
entry.held.unref()
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// pinned while a join pins it or a use holds it up
|
|
499
|
+
/** @private */
|
|
500
|
+
_apply(entry) {
|
|
501
|
+
const pinned = entry.pins > 0 || entry.held !== null
|
|
502
|
+
if (pinned === (entry.session.state === 'pinned')) return
|
|
503
|
+
if (pinned) entry.session.pin()
|
|
504
|
+
else entry.session.unpin()
|
|
505
|
+
this._refresh()
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// a device that held the topic before is dialed by its key: its own slots may all be on other topics, so a
|
|
509
|
+
// lookup of this one finds nobody. The replicator has no public way to dial a key
|
|
510
|
+
/** @private */
|
|
511
|
+
_dial(entry) {
|
|
512
|
+
const dialer = this._replicator?.dialer
|
|
513
|
+
if (!dialer || !entry.session.active) return
|
|
514
|
+
const now = (entry.dialed = Date.now())
|
|
515
|
+
for (const publicKey of entry.known) dialer.seen({ publicKey }, entry.session.topic, now, true)
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// the replicator drops a device it has not seen for 15 minutes, and a resume or a new address starts no topic
|
|
519
|
+
/** @private */
|
|
520
|
+
_redial() {
|
|
521
|
+
for (const entry of this._sessions.values()) this._dial(entry)
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// an announce starts when the rotation runs, and only once the server listens
|
|
525
|
+
/** @private */
|
|
526
|
+
async _settle(session) {
|
|
527
|
+
await this._listening
|
|
528
|
+
await this._rotate()
|
|
529
|
+
await session.flush()
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// many joins and touches in one tick make one rotation
|
|
533
|
+
/** @private */
|
|
534
|
+
_refresh() {
|
|
535
|
+
if (this._refreshing) return
|
|
536
|
+
this._refreshing = true
|
|
537
|
+
queueMicrotask(() => {
|
|
538
|
+
this._refreshing = false
|
|
539
|
+
this._rotate()
|
|
540
|
+
})
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// a topic leaving mid-rotation rejects it; the others had their state applied
|
|
544
|
+
/** @private */
|
|
545
|
+
async _rotate() {
|
|
546
|
+
const errors = this._errors()
|
|
547
|
+
await this._replicator?.refresh().catch(safetyCatch)
|
|
548
|
+
// a topic that starts announcing while the network is away
|
|
549
|
+
this._watch(this._active(), errors).catch(safetyCatch)
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** @private */
|
|
553
|
+
_active() {
|
|
554
|
+
const sessions = []
|
|
555
|
+
for (const { session } of this._sessions.values()) {
|
|
556
|
+
// a topic still opening has run no query
|
|
557
|
+
if (session.active && session.discovery) sessions.push(session)
|
|
558
|
+
}
|
|
559
|
+
return sessions
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** @private */
|
|
563
|
+
_lookup() {
|
|
564
|
+
const sessions = this._active()
|
|
565
|
+
for (const session of sessions) session.discovery.refresh()
|
|
566
|
+
return sessions
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// once the queries of these sessions settle: if one failed and no try waits, they are tried again
|
|
570
|
+
/** @private */
|
|
571
|
+
async _watch(sessions, errors = this._errors()) {
|
|
572
|
+
await settled(sessions)
|
|
573
|
+
if (this._errors() > errors && this._relookup === null) this._retry(0)
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// every active topic again, further apart each time, until they go through
|
|
577
|
+
/** @private */
|
|
578
|
+
_retry(i) {
|
|
579
|
+
this._relookup = setTimeout(async () => {
|
|
580
|
+
const errors = this._errors()
|
|
581
|
+
await settled(this._lookup())
|
|
582
|
+
if (this._errors() > errors) this._retry(Math.min(i + 1, RELOOKUPS.length - 1))
|
|
583
|
+
else this._relookup = null
|
|
374
584
|
}, RELOOKUPS[i])
|
|
375
585
|
this._relookup.unref()
|
|
376
586
|
}
|
|
587
|
+
|
|
588
|
+
/** @private */
|
|
589
|
+
_errors() {
|
|
590
|
+
let errors = 0
|
|
591
|
+
for (const { session } of this._sessions.values()) {
|
|
592
|
+
errors += session.discovery?.stats.errors ?? 0
|
|
593
|
+
}
|
|
594
|
+
return errors
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
function settled(sessions) {
|
|
599
|
+
return Promise.all(sessions.map((session) => session.discovery.flush()))
|
|
377
600
|
}
|
|
378
601
|
|
|
379
602
|
// data, not packets: a peer that acked our opener and froze has answered nothing
|
package/src/pairing/index.js
CHANGED
|
@@ -22,7 +22,7 @@ import { wrap } from '../database/envelope.js'
|
|
|
22
22
|
import { chainOf, linkOf } from '../database/dispatch.js'
|
|
23
23
|
import { getEncoding } from '../lib/spec/index.js'
|
|
24
24
|
import { CeroError } from '../lib/errors.js'
|
|
25
|
-
import { can, grants, isRank, isOptions, joining, INVITE, REMOVE } from '../lib/utils.js'
|
|
25
|
+
import { can, grants, isRank, isOptions, joining, inTurn, INVITE, REMOVE } from '../lib/utils.js'
|
|
26
26
|
import { NAMESPACE, MEMBER, REFUSALS, SPENT, ASKS } from '../lib/constants.js'
|
|
27
27
|
|
|
28
28
|
export { Pass } from './pass.js'
|
|
@@ -773,7 +773,7 @@ function coreOf(store, writer) {
|
|
|
773
773
|
function written(core, spec, stamp, invite, identity, writer) {
|
|
774
774
|
const id = b4a.toHex(writer.publicKey)
|
|
775
775
|
const run = () => write(core, spec, stamp, invite, identity, writer)
|
|
776
|
-
const last = (writing.get(id)
|
|
776
|
+
const last = inTurn(writing.get(id), run)
|
|
777
777
|
writing.set(id, last)
|
|
778
778
|
const done = () => writing.get(id) === last && writing.delete(id)
|
|
779
779
|
last.then(done, done)
|