@cero-base/core 3.4.0 → 3.5.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 +1 -1
- package/package.json +14 -13
- package/src/database/dispatch.js +3 -2
- package/src/database/index.js +15 -17
- package/src/lib/constants.js +0 -3
- package/src/lib/utils.js +16 -0
- package/src/mailbox/inbox.js +14 -1
- package/src/network/discovery.js +84 -49
- package/src/network/index.js +228 -84
- package/src/pairing/index.js +2 -2
- package/types/database/index.d.ts +5 -5
- package/types/lib/constants.d.ts +0 -2
- package/types/lib/utils.d.ts +13 -1
- package/types/mailbox/inbox.d.ts +2 -0
- package/types/network/discovery.d.ts +53 -23
- package/types/network/index.d.ts +85 -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,16 @@ 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]
|
|
21
20
|
|
|
22
21
|
function toKey(k) {
|
|
23
22
|
return typeof k === 'string' ? decodeKey(k) : k
|
|
@@ -33,17 +32,23 @@ export function channelTopic(topic, channel) {
|
|
|
33
32
|
* @property {Array<{ host: string, port: number }>} [bootstrap] Custom DHT bootstrap nodes.
|
|
34
33
|
* @property {(remotePublicKey: Uint8Array, payload: unknown) => boolean} [firewall] Incoming-connection filter.
|
|
35
34
|
* @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
35
|
* @property {string} [channel] Optional network-isolation label; only same-channel peers meet.
|
|
38
36
|
* @property {import('corestore')} store Corestore; every connection replicates it, so every core it holds rides every peer.
|
|
39
37
|
* @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached database/blob core is mirrored through them for offline sync.
|
|
40
38
|
* @property {(err: Error) => void} [onerror] Background-task error handler.
|
|
41
|
-
* @property {{ active?: number,
|
|
39
|
+
* @property {{ active?: number, idle?: number }} [presence] The budget for topics in the rotation: how many announce at once, and the ms one keeps its slot before a touched one may take it.
|
|
40
|
+
*
|
|
41
|
+
* @typedef {object} Entry One replicator session per topic, shared by every join of it.
|
|
42
|
+
* @property {string} id
|
|
43
|
+
* @property {import('./discovery.js').Session} session
|
|
44
|
+
* @property {import('corestore')} store The store session the replicator session lives on.
|
|
45
|
+
* @property {number} refs Joins holding the topic.
|
|
46
|
+
* @property {number} pins Joins pinning it.
|
|
42
47
|
*/
|
|
43
48
|
|
|
44
49
|
/**
|
|
45
|
-
*
|
|
46
|
-
* replicates the store.
|
|
50
|
+
* Peer discovery and connections on hyperjoin, plus a shared wakeup channel. Every connection,
|
|
51
|
+
* the replicator's or injected, replicates the store.
|
|
47
52
|
*/
|
|
48
53
|
export class Network extends ReadyResource {
|
|
49
54
|
/** @param {NetworkOpts} opts */
|
|
@@ -51,7 +56,6 @@ export class Network extends ReadyResource {
|
|
|
51
56
|
bootstrap,
|
|
52
57
|
firewall,
|
|
53
58
|
relayThrough,
|
|
54
|
-
backoffs,
|
|
55
59
|
channel,
|
|
56
60
|
store,
|
|
57
61
|
mirrors,
|
|
@@ -63,20 +67,24 @@ export class Network extends ReadyResource {
|
|
|
63
67
|
this.bootstrap = bootstrap || null
|
|
64
68
|
this.firewall = firewall || null
|
|
65
69
|
this.relayThrough = relayThrough?.map(toKey) || null
|
|
66
|
-
this.backoffs = backoffs || null
|
|
67
70
|
this.channel = channel || null
|
|
68
71
|
/** @type {import('corestore')} */
|
|
69
72
|
this.store = store
|
|
70
73
|
/** @type {Uint8Array[]} */
|
|
71
74
|
this.mirrors = (mirrors || []).map(toKey)
|
|
75
|
+
/** @type {{ active: number, idle: number }} */
|
|
76
|
+
this.presence = { active: 8, idle: 30_000, ...presence }
|
|
72
77
|
|
|
73
78
|
/** @private */
|
|
74
|
-
this.
|
|
79
|
+
this._replicator = null
|
|
80
|
+
/** @private */
|
|
81
|
+
this._dht = null
|
|
75
82
|
/** @type {import('protomux-wakeup')} */
|
|
76
83
|
this.wakeup = new ProtomuxWakeup()
|
|
77
|
-
this.presence = new Presence(this, presence)
|
|
78
84
|
|
|
79
|
-
/** @private */
|
|
85
|
+
/** @private @type {Map<string, Entry>} */
|
|
86
|
+
this._sessions = new Map()
|
|
87
|
+
/** @private @type {Set<Discovery>} */
|
|
80
88
|
this._discoveries = new Set()
|
|
81
89
|
/** @private */
|
|
82
90
|
this._injected = new Set()
|
|
@@ -85,61 +93,83 @@ export class Network extends ReadyResource {
|
|
|
85
93
|
/** @private */
|
|
86
94
|
this._peeringClosed = false
|
|
87
95
|
/** @private */
|
|
88
|
-
this.
|
|
96
|
+
this._listening = null
|
|
97
|
+
/** @private */
|
|
98
|
+
this._refreshing = false
|
|
99
|
+
/** @private */
|
|
100
|
+
this._resuming = null
|
|
89
101
|
/** @private */
|
|
90
102
|
this._relookup = null
|
|
91
103
|
/** @private */
|
|
92
104
|
this._onerror = onerror
|
|
93
105
|
}
|
|
94
106
|
|
|
95
|
-
/** @returns {import('
|
|
96
|
-
get
|
|
97
|
-
return this.
|
|
107
|
+
/** @returns {import('hyperjoin') | null} The underlying hyperjoin replicator, or null before ready / after close. */
|
|
108
|
+
get replicator() {
|
|
109
|
+
return this._replicator
|
|
98
110
|
}
|
|
99
111
|
|
|
100
|
-
/** @returns {
|
|
112
|
+
/** @returns {import('hyperdht') | null} The DHT the replicator and the mirrors share. */
|
|
113
|
+
get dht() {
|
|
114
|
+
return this._dht
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** @returns {Map<string, object>} Known peers keyed by public-key hex. */
|
|
101
118
|
get peers() {
|
|
102
|
-
return this.
|
|
119
|
+
return this._replicator ? this._replicator.peers : new Map()
|
|
103
120
|
}
|
|
104
121
|
|
|
105
|
-
/** @returns {Set<import('@hyperswarm/secret-stream')>} Live connection streams —
|
|
122
|
+
/** @returns {Set<import('@hyperswarm/secret-stream')>} Live connection streams — the replicator's and injected. */
|
|
106
123
|
get connections() {
|
|
107
|
-
|
|
108
|
-
|
|
124
|
+
const streams = new Set(this._injected)
|
|
125
|
+
if (this._replicator) for (const c of this._replicator.connections) streams.add(c.stream)
|
|
126
|
+
return streams
|
|
109
127
|
}
|
|
110
128
|
|
|
111
129
|
/** @returns {boolean} */
|
|
112
130
|
get suspended() {
|
|
113
|
-
return this.
|
|
131
|
+
return this._replicator?.suspended === true
|
|
114
132
|
}
|
|
115
133
|
|
|
116
134
|
/** @private */
|
|
117
135
|
async _open() {
|
|
118
|
-
// timeouts follow each node's measured round trip, not a flat second a try
|
|
119
|
-
const dht = new HyperDHT({
|
|
136
|
+
// timeouts follow each node's measured round trip, not a flat second a try
|
|
137
|
+
const dht = (this._dht = new HyperDHT({
|
|
120
138
|
bootstrap: this.bootstrap,
|
|
121
139
|
adaptiveTimeout: { min: 150, max: 1000 }
|
|
122
|
-
})
|
|
123
|
-
const opts = {
|
|
140
|
+
}))
|
|
141
|
+
const opts = {
|
|
142
|
+
dht,
|
|
143
|
+
slots: this.presence.active,
|
|
144
|
+
minActiveTime: this.presence.idle,
|
|
145
|
+
// a join owns its topic until it is destroyed
|
|
146
|
+
gcIdleTime: Infinity,
|
|
147
|
+
// dial a peer the moment it is found, where the replicator waits up to 500 ms
|
|
148
|
+
jitter: 0
|
|
149
|
+
}
|
|
124
150
|
if (this.firewall) opts.firewall = this.firewall
|
|
125
151
|
if (this.relayThrough) opts.relayThrough = this.relayThrough
|
|
126
|
-
if (this.backoffs) opts.backoffs = this.backoffs
|
|
127
152
|
|
|
128
|
-
const
|
|
153
|
+
const rep = (this._replicator = new Replicator(this.store, opts))
|
|
129
154
|
// back online after a NAT rebind or a router restart, peers may hold a stale address for us
|
|
130
155
|
dht.on('network-update', () => {
|
|
156
|
+
if (!dht.online) return
|
|
157
|
+
// the queries sent while it was away failed
|
|
158
|
+
this._watch(this._lookup()).catch(safetyCatch)
|
|
131
159
|
// a tick later: the dht's own wake-up in this event would clear a refresh made now
|
|
132
|
-
|
|
160
|
+
setTimeout(() => this.closing || rep.server.refresh(), 0)
|
|
133
161
|
})
|
|
134
|
-
|
|
162
|
+
rep.on('connected', ({ stream, info }) => {
|
|
135
163
|
if (this.closing || this.closed) {
|
|
136
164
|
stream.destroy()
|
|
137
165
|
return
|
|
138
166
|
}
|
|
139
167
|
dropIfSilent(stream)
|
|
140
|
-
stream.on('close', () => this._lose(stream.remotePublicKey))
|
|
141
168
|
this._add(stream, info)
|
|
142
169
|
})
|
|
170
|
+
await rep.ready()
|
|
171
|
+
// the server listens in the background and a topic announces only once it does; with nothing joined, a flush ends there
|
|
172
|
+
this._listening = rep.flush()
|
|
143
173
|
|
|
144
174
|
if (this.mirrors.length) this.peering()
|
|
145
175
|
}
|
|
@@ -147,7 +177,6 @@ export class Network extends ReadyResource {
|
|
|
147
177
|
/** @private */
|
|
148
178
|
async _close() {
|
|
149
179
|
clearTimeout(this._relookup)
|
|
150
|
-
this._lost.clear()
|
|
151
180
|
for (const conn of [...this._injected]) {
|
|
152
181
|
try {
|
|
153
182
|
conn.destroy()
|
|
@@ -157,18 +186,16 @@ export class Network extends ReadyResource {
|
|
|
157
186
|
}
|
|
158
187
|
this._injected.clear()
|
|
159
188
|
|
|
160
|
-
//
|
|
161
|
-
this.presence.close()
|
|
189
|
+
// leave every topic now, never await the DHT unannounce round-trips
|
|
162
190
|
for (const d of [...this._discoveries]) d.destroy().catch(safetyCatch)
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
}
|
|
191
|
+
|
|
192
|
+
// close still awaits the unannounces and a server.close round-trip; cap it
|
|
193
|
+
const rep = this._replicator
|
|
194
|
+
this._replicator = null
|
|
195
|
+
if (rep) await capped(rep.close().catch(safetyCatch), 750)
|
|
196
|
+
const dht = this._dht
|
|
197
|
+
this._dht = null
|
|
198
|
+
if (dht) await dht.destroy().catch(safetyCatch)
|
|
172
199
|
|
|
173
200
|
if (this._blindPeering) {
|
|
174
201
|
try {
|
|
@@ -199,8 +226,8 @@ export class Network extends ReadyResource {
|
|
|
199
226
|
inject(stream, { isInitiator } = {}) {
|
|
200
227
|
if (this.closing || this.closed) throw CeroError.CLOSED('Network')
|
|
201
228
|
if (!stream) throw CeroError.REQUIRED('stream')
|
|
202
|
-
// a raw duplex handshakes as the
|
|
203
|
-
const keyPair = this.
|
|
229
|
+
// a raw duplex handshakes as the replicator does
|
|
230
|
+
const keyPair = this._replicator?.keyPair ?? undefined
|
|
204
231
|
const conn =
|
|
205
232
|
stream.noiseStream === stream
|
|
206
233
|
? stream
|
|
@@ -210,6 +237,8 @@ export class Network extends ReadyResource {
|
|
|
210
237
|
conn.on('close', () => this._injected.delete(conn))
|
|
211
238
|
conn.on('error', safetyCatch) // a dropped radio link must not crash the host
|
|
212
239
|
|
|
240
|
+
// the replicator replicates the store on its own connections only
|
|
241
|
+
this.store.replicate(conn)
|
|
213
242
|
this._add(conn, { injected: true })
|
|
214
243
|
return conn
|
|
215
244
|
}
|
|
@@ -217,7 +246,6 @@ export class Network extends ReadyResource {
|
|
|
217
246
|
/** @private */
|
|
218
247
|
_add(conn, info) {
|
|
219
248
|
this.wakeup.addStream(conn)
|
|
220
|
-
this.store.replicate(conn)
|
|
221
249
|
this.emit('connection', conn, info)
|
|
222
250
|
}
|
|
223
251
|
|
|
@@ -242,7 +270,7 @@ export class Network extends ReadyResource {
|
|
|
242
270
|
peering() {
|
|
243
271
|
if (this.closing || this.closed || this._peeringClosed) throw CeroError.CLOSED('Network')
|
|
244
272
|
if (!this._blindPeering) {
|
|
245
|
-
this._blindPeering = new BlindPeering(this.
|
|
273
|
+
this._blindPeering = new BlindPeering(this._dht, this.store, {
|
|
246
274
|
blindPeers: this.mirrors.map((key) => ({ key })),
|
|
247
275
|
wakeup: this.wakeup,
|
|
248
276
|
pick: 2
|
|
@@ -252,67 +280,108 @@ export class Network extends ReadyResource {
|
|
|
252
280
|
}
|
|
253
281
|
|
|
254
282
|
/**
|
|
255
|
-
* Wait for pending DHT announces and
|
|
283
|
+
* Wait for pending DHT announces, lookups and dials to settle, bounded by timeout.
|
|
256
284
|
*
|
|
257
285
|
* @param {{ timeout?: number }} [opts]
|
|
258
286
|
* @returns {Promise<void>}
|
|
259
287
|
*/
|
|
260
288
|
async flush({ timeout = 500 } = {}) {
|
|
261
|
-
|
|
262
|
-
|
|
289
|
+
const rep = this._replicator
|
|
290
|
+
if (!rep) return
|
|
291
|
+
await capped(this._flush(rep), timeout)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** @private */
|
|
295
|
+
async _flush(rep) {
|
|
296
|
+
// a join queues its announce only when the rotation runs
|
|
297
|
+
await this._rotate()
|
|
298
|
+
await rep.flush()
|
|
263
299
|
}
|
|
264
300
|
|
|
265
301
|
/**
|
|
266
|
-
* Pause the
|
|
302
|
+
* Pause the network — keeps state, drops sockets. Idempotent.
|
|
267
303
|
*
|
|
268
304
|
* @returns {Promise<void>}
|
|
269
305
|
*/
|
|
270
306
|
async suspend() {
|
|
271
307
|
if (this.closing || this.closed) return
|
|
272
308
|
await this._blindPeering?.suspend()
|
|
273
|
-
await this.
|
|
309
|
+
await this._replicator?.suspend()
|
|
310
|
+
await this._dht?.suspend()
|
|
274
311
|
clearTimeout(this._relookup)
|
|
312
|
+
this._relookup = null
|
|
275
313
|
}
|
|
276
314
|
|
|
277
315
|
/**
|
|
278
|
-
* Resume a suspended
|
|
316
|
+
* Resume a suspended network. Idempotent.
|
|
279
317
|
*
|
|
280
318
|
* @returns {Promise<void>}
|
|
281
319
|
*/
|
|
282
320
|
async resume() {
|
|
283
321
|
if (this.closing || this.closed || !this.suspended) return
|
|
284
|
-
|
|
322
|
+
this._resuming = this._resume()
|
|
323
|
+
try {
|
|
324
|
+
await this._resuming
|
|
325
|
+
} finally {
|
|
326
|
+
this._resuming = null
|
|
327
|
+
}
|
|
285
328
|
await this._blindPeering?.resume()
|
|
286
|
-
// the
|
|
287
|
-
this.
|
|
329
|
+
// the queries the replicator runs at resume fail when they go out before the network is back
|
|
330
|
+
this._watch(this._active()).catch(safetyCatch)
|
|
288
331
|
this.emit('resume')
|
|
289
332
|
}
|
|
290
333
|
|
|
334
|
+
// the replicator resumes every session it holds and a destroyed one throws there: a leave in
|
|
335
|
+
// flight finishes first, and one that starts meanwhile waits in _leave
|
|
336
|
+
/** @private */
|
|
337
|
+
async _resume() {
|
|
338
|
+
await this._dht.resume()
|
|
339
|
+
const rep = this._replicator
|
|
340
|
+
await Promise.all([...rep.sessions.values()].map((session) => session.closing))
|
|
341
|
+
await rep.resume()
|
|
342
|
+
}
|
|
343
|
+
|
|
291
344
|
/**
|
|
292
|
-
*
|
|
345
|
+
* Join a 32-byte topic and return a Discovery handle. Pinned by default: it announces and
|
|
346
|
+
* looks up now; `pin: false` leaves it to the rotation.
|
|
293
347
|
*
|
|
294
348
|
* @param {Uint8Array} topic
|
|
295
|
-
* @param {{
|
|
349
|
+
* @param {{ pin?: boolean }} [opts]
|
|
296
350
|
* @returns {Discovery}
|
|
297
351
|
*/
|
|
298
|
-
join(topic, {
|
|
299
|
-
if (mode !== ACTIVE && mode !== PASSIVE) {
|
|
300
|
-
throw CeroError.INVALID('mode must be "active" or "passive"')
|
|
301
|
-
}
|
|
352
|
+
join(topic, { pin = true } = {}) {
|
|
302
353
|
if (this.closing || this.closed) throw CeroError.CLOSED('Network')
|
|
303
|
-
if (!this.
|
|
354
|
+
if (!this._replicator) throw CeroError.NOT_READY('Network', 'network')
|
|
304
355
|
if (!isTopic(topic)) throw CeroError.INVALID('topic must be a 32-byte buffer')
|
|
305
356
|
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
357
|
+
const key = channelTopic(topic, this.channel)
|
|
358
|
+
const id = b4a.toHex(key)
|
|
359
|
+
let entry = this._sessions.get(id)
|
|
360
|
+
if (!entry) {
|
|
361
|
+
// a store session per topic: the root store collects no listener per topic
|
|
362
|
+
const store = this.store.session()
|
|
363
|
+
const session = this._replicator.join(store, key, { deferSwarming: false })
|
|
364
|
+
entry = { id, session, store, refs: 0, pins: 0 }
|
|
365
|
+
this._sessions.set(id, entry)
|
|
366
|
+
}
|
|
367
|
+
entry.refs++
|
|
310
368
|
|
|
311
|
-
const discovery = new Discovery(this,
|
|
369
|
+
const discovery = new Discovery(this, entry, pin)
|
|
312
370
|
this._discoveries.add(discovery)
|
|
313
371
|
return discovery
|
|
314
372
|
}
|
|
315
373
|
|
|
374
|
+
/**
|
|
375
|
+
* Where a topic stands on this network.
|
|
376
|
+
*
|
|
377
|
+
* @param {Uint8Array} topic
|
|
378
|
+
* @returns {'inactive' | 'pinned' | 'autostarted' | 'discovering' | null} Its session's state, null when not joined.
|
|
379
|
+
*/
|
|
380
|
+
state(topic) {
|
|
381
|
+
const entry = this._sessions.get(b4a.toHex(channelTopic(topic, this.channel)))
|
|
382
|
+
return entry ? entry.session.state : null
|
|
383
|
+
}
|
|
384
|
+
|
|
316
385
|
/**
|
|
317
386
|
* Whether `store` replicates on this network's connections: the network's store or a session of it.
|
|
318
387
|
*
|
|
@@ -352,28 +421,103 @@ export class Network extends ReadyResource {
|
|
|
352
421
|
})
|
|
353
422
|
}
|
|
354
423
|
|
|
355
|
-
// hyperswarm stops redialing a peer after a few failed tries and looks it up again only every 10 min
|
|
356
424
|
/** @private */
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
425
|
+
async _leave(discovery) {
|
|
426
|
+
this._discoveries.delete(discovery)
|
|
427
|
+
const { entry } = discovery
|
|
428
|
+
if (--entry.refs > 0) return
|
|
429
|
+
try {
|
|
430
|
+
await this._resuming
|
|
431
|
+
} catch (err) {
|
|
432
|
+
safetyCatch(err)
|
|
433
|
+
}
|
|
434
|
+
// joined again meanwhile and the same session carries on, or another leave of it got here first
|
|
435
|
+
if (entry.refs > 0 || this._sessions.get(entry.id) !== entry) return
|
|
436
|
+
this._sessions.delete(entry.id)
|
|
437
|
+
try {
|
|
438
|
+
await entry.session.destroy()
|
|
439
|
+
await entry.store.close()
|
|
440
|
+
} catch (err) {
|
|
441
|
+
safetyCatch(err)
|
|
442
|
+
}
|
|
361
443
|
}
|
|
362
444
|
|
|
445
|
+
// an announce starts when the rotation runs, and only once the server listens
|
|
363
446
|
/** @private */
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
this.
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
447
|
+
async _settle(session) {
|
|
448
|
+
await this._listening
|
|
449
|
+
await this._rotate()
|
|
450
|
+
await session.flush()
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// many joins and touches in one tick make one rotation
|
|
454
|
+
/** @private */
|
|
455
|
+
_refresh() {
|
|
456
|
+
if (this._refreshing) return
|
|
457
|
+
this._refreshing = true
|
|
458
|
+
queueMicrotask(() => {
|
|
459
|
+
this._refreshing = false
|
|
460
|
+
this._rotate()
|
|
461
|
+
})
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// a topic leaving mid-rotation rejects it; the others had their state applied
|
|
465
|
+
/** @private */
|
|
466
|
+
async _rotate() {
|
|
467
|
+
const errors = this._errors()
|
|
468
|
+
await this._replicator?.refresh().catch(safetyCatch)
|
|
469
|
+
// a topic that starts announcing while the network is away
|
|
470
|
+
this._watch(this._active(), errors).catch(safetyCatch)
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** @private */
|
|
474
|
+
_active() {
|
|
475
|
+
const sessions = []
|
|
476
|
+
for (const { session } of this._sessions.values()) {
|
|
477
|
+
// a topic still opening has run no query
|
|
478
|
+
if (session.active && session.discovery) sessions.push(session)
|
|
479
|
+
}
|
|
480
|
+
return sessions
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** @private */
|
|
484
|
+
_lookup() {
|
|
485
|
+
const sessions = this._active()
|
|
486
|
+
for (const session of sessions) session.discovery.refresh()
|
|
487
|
+
return sessions
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// once the queries of these sessions settle: if one failed and no try waits, they are tried again
|
|
491
|
+
/** @private */
|
|
492
|
+
async _watch(sessions, errors = this._errors()) {
|
|
493
|
+
await settled(sessions)
|
|
494
|
+
if (this._errors() > errors && this._relookup === null) this._retry(0)
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// every active topic again, further apart each time, until they go through
|
|
498
|
+
/** @private */
|
|
499
|
+
_retry(i) {
|
|
500
|
+
this._relookup = setTimeout(async () => {
|
|
501
|
+
const errors = this._errors()
|
|
502
|
+
await settled(this._lookup())
|
|
503
|
+
if (this._errors() > errors) this._retry(Math.min(i + 1, RELOOKUPS.length - 1))
|
|
504
|
+
else this._relookup = null
|
|
374
505
|
}, RELOOKUPS[i])
|
|
375
506
|
this._relookup.unref()
|
|
376
507
|
}
|
|
508
|
+
|
|
509
|
+
/** @private */
|
|
510
|
+
_errors() {
|
|
511
|
+
let errors = 0
|
|
512
|
+
for (const { session } of this._sessions.values()) {
|
|
513
|
+
errors += session.discovery?.stats.errors ?? 0
|
|
514
|
+
}
|
|
515
|
+
return errors
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function settled(sessions) {
|
|
520
|
+
return Promise.all(sessions.map((session) => session.discovery.flush()))
|
|
377
521
|
}
|
|
378
522
|
|
|
379
523
|
// 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)
|
|
@@ -60,7 +60,7 @@ export type DatabaseOpts = {
|
|
|
60
60
|
*/
|
|
61
61
|
key?: Uint8Array | null;
|
|
62
62
|
/**
|
|
63
|
-
* Always
|
|
63
|
+
* Always announce and look up, outside the network's presence budget. The root.
|
|
64
64
|
*/
|
|
65
65
|
pinned?: boolean;
|
|
66
66
|
/**
|
|
@@ -172,7 +172,7 @@ export type HookFn = (ctx: HookContext) => unknown;
|
|
|
172
172
|
* @property {Uint8Array} encryptionKey Encrypts it; a join hands it out, so never the identity's on a database you pair.
|
|
173
173
|
* @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
|
|
174
174
|
* @property {Uint8Array | null} [key] Existing autobee key to reopen.
|
|
175
|
-
* @property {boolean} [pinned] Always
|
|
175
|
+
* @property {boolean} [pinned] Always announce and look up, outside the network's presence budget. The root.
|
|
176
176
|
* @property {boolean} [root] The identity's own database: a device key past a removed one stands while a device of the identity is seated on it.
|
|
177
177
|
* @property {boolean} [push] Push a notification through the mirrors after a local write to a ref whose meta declares `push`, naming the ref, so members learn of it while their app is dead.
|
|
178
178
|
* @property {import('../identity/index.js').KeyPair} [keyPair] This device's writer keypair; a fresh random one by default. Never the identity's, never the database key.
|
|
@@ -313,7 +313,7 @@ export declare class Database extends ReadyResource {
|
|
|
313
313
|
}>;
|
|
314
314
|
};
|
|
315
315
|
/** @private */
|
|
316
|
-
|
|
316
|
+
_discovery;
|
|
317
317
|
/** @private */
|
|
318
318
|
_pushing;
|
|
319
319
|
/** @private */
|
|
@@ -365,8 +365,8 @@ export declare class Database extends ReadyResource {
|
|
|
365
365
|
/** @private */
|
|
366
366
|
private _close;
|
|
367
367
|
/**
|
|
368
|
-
* `true` ranks this database as just touched, `false`
|
|
369
|
-
* next update lands in it.
|
|
368
|
+
* `true` ranks this database as just touched, `false` ranks it last: it keeps its slot on the
|
|
369
|
+
* swarm only while one is spare, until the next update lands in it.
|
|
370
370
|
*
|
|
371
371
|
* @param {boolean} active
|
|
372
372
|
*/
|
package/types/lib/constants.d.ts
CHANGED
|
@@ -2,8 +2,6 @@ export declare const SINGLE = "single";
|
|
|
2
2
|
export declare const COLLECTION = "collection";
|
|
3
3
|
export declare const HANDLE = "handle";
|
|
4
4
|
export declare const ACTION = "action";
|
|
5
|
-
export declare const ACTIVE = "active";
|
|
6
|
-
export declare const PASSIVE = "passive";
|
|
7
5
|
export declare const ROCKS = "rocks";
|
|
8
6
|
export declare const BEE = "bee";
|
|
9
7
|
export declare const OWNER = "owner";
|
package/types/lib/utils.d.ts
CHANGED
|
@@ -51,7 +51,19 @@ export declare function filter<T extends Record<string, unknown>>(rows: T[], que
|
|
|
51
51
|
* @param {() => void} cb
|
|
52
52
|
* @returns {(() => void) | undefined}
|
|
53
53
|
*/
|
|
54
|
-
|
|
54
|
+
/**
|
|
55
|
+
* Run `fn` once `prev` has ended, however it ended: one after the other. `fn` is awaited as it starts, so when
|
|
56
|
+
* it fails at once, as a write on a database that closed while it waited, the promise that rejects is the one the
|
|
57
|
+
* caller already holds. Returned from a `then`, it would be rejected for a turn with nobody holding it, and Bare
|
|
58
|
+
* reports that as uncaught when a stream is destroyed in that turn.
|
|
59
|
+
*
|
|
60
|
+
* @template T
|
|
61
|
+
* @param {Promise<unknown> | null | undefined} prev
|
|
62
|
+
* @param {() => Promise<T> | T} fn
|
|
63
|
+
* @returns {Promise<T>}
|
|
64
|
+
*/
|
|
65
|
+
export declare function inTurn<T>(prev: Promise<unknown> | null | undefined, fn: () => Promise<T> | T): Promise<T>;
|
|
66
|
+
export declare function onAbort(signal: any, cb: any): () => any;
|
|
55
67
|
/** @type {<T>(row: T, createdAt?: number | null, ts?: number) => T & { createdAt: number, updatedAt: number }} */
|
|
56
68
|
export declare function stamp<T>(row: T, createdAt: number, ts?: number): T & {
|
|
57
69
|
createdAt: number;
|
package/types/mailbox/inbox.d.ts
CHANGED