@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.
@@ -1,60 +1,90 @@
1
1
  export type Session = {
2
- refresh(opts?: object): Promise<void>;
3
- flushed(): Promise<boolean>;
4
- destroy(): Promise<void>;
2
+ state: 'inactive' | 'pinned' | 'autostarted' | 'discovering' | 'destroyed';
3
+ active: boolean;
4
+ priority: number;
5
+ closing: Promise<void> | null;
6
+ discovery: {
7
+ refresh(): void;
8
+ } | null;
9
+ pin: () => void;
10
+ unpin: () => void;
11
+ discover: () => void;
12
+ flush: () => Promise<void>;
13
+ destroy: () => Promise<void>;
14
+ on: (event: string, listener: (session: Session) => void) => void;
5
15
  };
6
16
  /**
7
- * Handle for a single topic membership on a {@link Network}. Wraps a hyperswarm
8
- * PeerDiscovery session and lets it switch between active/passive announce/lookup.
17
+ * @typedef {object} Session The hyperjoin session a topic has, as far as cero uses it.
18
+ * @property {'inactive' | 'pinned' | 'autostarted' | 'discovering' | 'destroyed'} state
19
+ * @property {boolean} active
20
+ * @property {number} priority
21
+ * @property {Promise<void> | null} closing
22
+ * @property {{ refresh(): void } | null} discovery
23
+ * @property {() => void} pin
24
+ * @property {() => void} unpin
25
+ * @property {() => void} discover
26
+ * @property {() => Promise<void>} flush
27
+ * @property {() => Promise<void>} destroy
28
+ * @property {(event: string, listener: (session: Session) => void) => void} on
9
29
  */
10
30
  /**
11
- * @typedef {{ refresh(opts?: object): Promise<void>, flushed(): Promise<boolean>, destroy(): Promise<void> }} Session
12
- * The hyperswarm session `swarm.join()` returns, as far as this file uses it.
31
+ * Handle for one topic membership on a {@link Network}: a view on the session the topic has,
32
+ * shared by every join of it. Pinned, it announces and looks up until released; in the
33
+ * rotation, it announces while it holds a slot, ranked by its last touch.
13
34
  */
14
35
  export declare class Discovery {
15
36
  network: import("./index.js").Network;
16
- /** @type {Session} */
17
- session: Session;
18
37
  /** @private */
19
- _mode;
38
+ entry;
20
39
  /** @private */
21
- _destroyed;
40
+ _pinned;
22
41
  /** @private */
23
- _timer;
42
+ _destroyed;
24
43
  /**
25
44
  * @param {import('./index.js').Network} network Owning network.
26
- * @param {Session} session Hyperswarm PeerDiscovery session from `swarm.join()`.
27
- * @param {'active' | 'passive'} mode
45
+ * @param {import('./index.js').Entry} entry The topic's session, shared by every join of it.
46
+ * @param {boolean} pin
28
47
  */
29
- constructor(network: import('./index.js').Network, session: Session, mode: 'active' | 'passive');
30
- /** @returns {'active' | 'passive'} */
31
- get mode(): 'active' | 'passive';
48
+ constructor(network: import('./index.js').Network, entry: import('./index.js').Entry, pin: boolean);
49
+ /** @returns {Session} */
50
+ get session(): Session;
51
+ /** @returns {'inactive' | 'pinned' | 'autostarted' | 'discovering' | 'destroyed'} */
52
+ get state(): 'inactive' | 'pinned' | 'autostarted' | 'discovering' | 'destroyed';
53
+ /** @returns {boolean} Whether the topic announces or looks up right now. */
54
+ get active(): boolean;
32
55
  /** @returns {boolean} */
33
56
  get destroyed(): boolean;
34
57
  /**
35
- * Switch to active (client+server) announce/lookup.
58
+ * Pin the topic and look up now: it announces and looks up until `deactivate()`, outside the
59
+ * rotation's budget.
36
60
  *
37
61
  * @returns {Promise<void>}
38
62
  */
39
63
  activate(): Promise<void>;
40
64
  /**
41
- * Switch to passive announce.
65
+ * Unpin the topic: the rotation decides, by its last touch.
42
66
  *
43
67
  * @returns {Promise<void>}
44
68
  */
45
69
  deactivate(): Promise<void>;
70
+ /** Rank the topic first in the rotation, as just used. */
71
+ touch(): void;
72
+ /** Rank the topic last: it keeps a slot only while one is spare. */
73
+ release(): void;
46
74
  /**
47
- * Wait for the current announce/lookup to settle.
75
+ * Wait for the current announce or lookup to settle.
48
76
  *
49
77
  * @returns {Promise<void>}
50
78
  */
51
79
  flush(): Promise<void>;
52
- /** @private */
53
- private _requery;
54
80
  /**
55
- * Leave the topic and tear down the session. Idempotent.
81
+ * Leave the topic, once every join of it has. Idempotent.
56
82
  *
57
83
  * @returns {Promise<void>}
58
84
  */
59
85
  destroy(): Promise<void>;
86
+ /** @private */
87
+ private _pin;
88
+ /** @private */
89
+ private _rank;
60
90
  }
@@ -1,6 +1,5 @@
1
1
  import ReadyResource from 'ready-resource';
2
2
  import { Discovery } from './discovery.js';
3
- import { Presence } from './presence.js';
4
3
  /** @type {(topic: Uint8Array, channel: string | null) => Uint8Array} */
5
4
  export declare function channelTopic(topic: Uint8Array<ArrayBufferLike>, channel: string): Uint8Array<ArrayBufferLike>;
6
5
  export type NetworkOpts = {
@@ -19,10 +18,6 @@ export type NetworkOpts = {
19
18
  * Blind relay public keys; a connection goes through one only when a direct one fails or this device sits behind a randomizing NAT.
20
19
  */
21
20
  relayThrough?: Array<string | Uint8Array>;
22
- /**
23
- * Reconnect backoff tiers in ms; the default escalates to ~10min, far too slow for local nets.
24
- */
25
- backoffs?: number[];
26
21
  /**
27
22
  * Optional network-isolation label; only same-channel peers meet.
28
23
  */
@@ -40,29 +35,50 @@ export type NetworkOpts = {
40
35
  */
41
36
  onerror?: (err: Error) => void;
42
37
  /**
43
- * Swarm budget for attached databases: how many search, how many only announce, and the idle ms before the rest leave.
38
+ * 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.
44
39
  */
45
40
  presence?: {
46
41
  active?: number;
47
- announced?: number;
48
42
  idle?: number;
49
43
  };
50
44
  };
45
+ export type Entry = {
46
+ id: string;
47
+ session: import('./discovery.js').Session;
48
+ /**
49
+ * The store session the replicator session lives on.
50
+ */
51
+ store: import('corestore');
52
+ /**
53
+ * Joins holding the topic.
54
+ */
55
+ refs: number;
56
+ /**
57
+ * Joins pinning it.
58
+ */
59
+ pins: number;
60
+ };
51
61
  /**
52
62
  * @typedef {object} NetworkOpts
53
63
  * @property {Array<{ host: string, port: number }>} [bootstrap] Custom DHT bootstrap nodes.
54
64
  * @property {(remotePublicKey: Uint8Array, payload: unknown) => boolean} [firewall] Incoming-connection filter.
55
65
  * @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.
56
- * @property {number[]} [backoffs] Reconnect backoff tiers in ms; the default escalates to ~10min, far too slow for local nets.
57
66
  * @property {string} [channel] Optional network-isolation label; only same-channel peers meet.
58
67
  * @property {import('corestore')} store Corestore; every connection replicates it, so every core it holds rides every peer.
59
68
  * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached database/blob core is mirrored through them for offline sync.
60
69
  * @property {(err: Error) => void} [onerror] Background-task error handler.
61
- * @property {{ active?: number, announced?: number, idle?: number }} [presence] Swarm budget for attached databases: how many search, how many only announce, and the idle ms before the rest leave.
70
+ * @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.
71
+ *
72
+ * @typedef {object} Entry One replicator session per topic, shared by every join of it.
73
+ * @property {string} id
74
+ * @property {import('./discovery.js').Session} session
75
+ * @property {import('corestore')} store The store session the replicator session lives on.
76
+ * @property {number} refs Joins holding the topic.
77
+ * @property {number} pins Joins pinning it.
62
78
  */
63
79
  /**
64
- * Hyperswarm peer discovery plus a shared wakeup channel. Every connection, swarm or injected,
65
- * replicates the store.
80
+ * Peer discovery and connections on hyperjoin, plus a shared wakeup channel. Every connection,
81
+ * the replicator's or injected, replicates the store.
66
82
  */
67
83
  export declare class Network extends ReadyResource {
68
84
  bootstrap: {
@@ -71,18 +87,25 @@ export declare class Network extends ReadyResource {
71
87
  }[];
72
88
  firewall: (remotePublicKey: Uint8Array, payload: unknown) => boolean;
73
89
  relayThrough: any[];
74
- backoffs: number[];
75
90
  channel: string;
76
91
  /** @type {import('corestore')} */
77
92
  store: import('corestore');
78
93
  /** @type {Uint8Array[]} */
79
94
  mirrors: Uint8Array[];
95
+ /** @type {{ active: number, idle: number }} */
96
+ presence: {
97
+ active: number;
98
+ idle: number;
99
+ };
80
100
  /** @private */
81
- _swarm;
101
+ _replicator;
102
+ /** @private */
103
+ _dht;
82
104
  /** @type {import('protomux-wakeup')} */
83
105
  wakeup: import('protomux-wakeup');
84
- presence: Presence;
85
- /** @private */
106
+ /** @private @type {Map<string, Entry>} */
107
+ _sessions;
108
+ /** @private @type {Set<Discovery>} */
86
109
  _discoveries;
87
110
  /** @private */
88
111
  _injected;
@@ -91,18 +114,24 @@ export declare class Network extends ReadyResource {
91
114
  /** @private */
92
115
  _peeringClosed;
93
116
  /** @private */
94
- _lost;
117
+ _listening;
118
+ /** @private */
119
+ _refreshing;
120
+ /** @private */
121
+ _resuming;
95
122
  /** @private */
96
123
  _relookup;
97
124
  /** @private */
98
125
  _onerror;
99
126
  /** @param {NetworkOpts} opts */
100
- constructor({ bootstrap, firewall, relayThrough, backoffs, channel, store, mirrors, presence, onerror }?: NetworkOpts);
101
- /** @returns {import('hyperswarm') | null} The underlying hyperswarm, or null before ready / after close. */
102
- get swarm(): import('hyperswarm') | null;
103
- /** @returns {Map<string, object>} Known peers keyed by public-key string. */
127
+ constructor({ bootstrap, firewall, relayThrough, channel, store, mirrors, presence, onerror }?: NetworkOpts);
128
+ /** @returns {import('hyperjoin') | null} The underlying hyperjoin replicator, or null before ready / after close. */
129
+ get replicator(): import('hyperjoin') | null;
130
+ /** @returns {import('hyperdht') | null} The DHT the replicator and the mirrors share. */
131
+ get dht(): import('hyperdht') | null;
132
+ /** @returns {Map<string, object>} Known peers keyed by public-key hex. */
104
133
  get peers(): Map<string, object>;
105
- /** @returns {Set<import('@hyperswarm/secret-stream')>} Live connection streams — swarm and injected. */
134
+ /** @returns {Set<import('@hyperswarm/secret-stream')>} Live connection streams — the replicator's and injected. */
106
135
  get connections(): Set<import('@hyperswarm/secret-stream')>;
107
136
  /** @returns {boolean} */
108
137
  get suspended(): boolean;
@@ -139,7 +168,7 @@ export declare class Network extends ReadyResource {
139
168
  */
140
169
  peering(): import('blind-peering');
141
170
  /**
142
- * Wait for pending DHT announces and lookups to settle, bounded by timeout.
171
+ * Wait for pending DHT announces, lookups and dials to settle, bounded by timeout.
143
172
  *
144
173
  * @param {{ timeout?: number }} [opts]
145
174
  * @returns {Promise<void>}
@@ -147,28 +176,40 @@ export declare class Network extends ReadyResource {
147
176
  flush({ timeout }?: {
148
177
  timeout?: number;
149
178
  }): Promise<void>;
179
+ /** @private */
180
+ private _flush;
150
181
  /**
151
- * Pause the swarm — keeps state, drops sockets. Idempotent.
182
+ * Pause the network — keeps state, drops sockets. Idempotent.
152
183
  *
153
184
  * @returns {Promise<void>}
154
185
  */
155
186
  suspend(): Promise<void>;
156
187
  /**
157
- * Resume a suspended swarm. Idempotent.
188
+ * Resume a suspended network. Idempotent.
158
189
  *
159
190
  * @returns {Promise<void>}
160
191
  */
161
192
  resume(): Promise<void>;
193
+ /** @private */
194
+ private _resume;
162
195
  /**
163
- * Announce/lookup on a 32-byte topic and return a Discovery handle.
196
+ * Join a 32-byte topic and return a Discovery handle. Pinned by default: it announces and
197
+ * looks up now; `pin: false` leaves it to the rotation.
164
198
  *
165
199
  * @param {Uint8Array} topic
166
- * @param {{ mode?: 'active' | 'passive' }} [opts] `active` = client+server, `passive` = server-only
200
+ * @param {{ pin?: boolean }} [opts]
167
201
  * @returns {Discovery}
168
202
  */
169
- join(topic: Uint8Array, { mode }?: {
170
- mode?: 'active' | 'passive';
203
+ join(topic: Uint8Array, { pin }?: {
204
+ pin?: boolean;
171
205
  }): Discovery;
206
+ /**
207
+ * Where a topic stands on this network.
208
+ *
209
+ * @param {Uint8Array} topic
210
+ * @returns {'inactive' | 'pinned' | 'autostarted' | 'discovering' | null} Its session's state, null when not joined.
211
+ */
212
+ state(topic: Uint8Array): 'inactive' | 'pinned' | 'autostarted' | 'discovering' | null;
172
213
  /**
173
214
  * Whether `store` replicates on this network's connections: the network's store or a session of it.
174
215
  *
@@ -187,7 +228,21 @@ export declare class Network extends ReadyResource {
187
228
  /** @private */
188
229
  private _mirror;
189
230
  /** @private */
190
- private _lose;
231
+ private _leave;
232
+ /** @private */
233
+ private _settle;
234
+ /** @private */
235
+ private _refresh;
236
+ /** @private */
237
+ private _rotate;
238
+ /** @private */
239
+ private _active;
240
+ /** @private */
241
+ private _lookup;
242
+ /** @private */
243
+ private _watch;
244
+ /** @private */
245
+ private _retry;
191
246
  /** @private */
192
- private _relook;
247
+ private _errors;
193
248
  }
@@ -1,135 +0,0 @@
1
- import safetyCatch from 'safety-catch'
2
- import b4a from 'b4a'
3
-
4
- import { ACTIVE, PASSIVE } from '../lib/constants.js'
5
-
6
- const rank = (mode) => (mode === ACTIVE ? 2 : mode === PASSIVE ? 1 : 0)
7
-
8
- /**
9
- * Which handles swarm. Ranked by last touch: the latest `active` search and announce, the
10
- * next `announced` announce only, the rest leave their topic. A handle moves up at once and
11
- * down only after `idle` ms. A pinned handle always searches, outside the budget.
12
- *
13
- * @typedef {{ mode: 'active' | 'passive' | null, touch: () => void, off: () => void, remove: () => void }} Slot
14
- */
15
- export class Presence {
16
- /**
17
- * @param {import('./index.js').Network} network
18
- * @param {{ active?: number, announced?: number, idle?: number }} [opts]
19
- */
20
- constructor(network, { active = 8, announced = 8, idle = 30_000 } = {}) {
21
- this.network = network
22
- this.active = active
23
- this.announced = announced
24
- this.idle = idle
25
- /** @type {Map<string, { topic: Uint8Array, pinned: boolean, refs: number, touched: number, off: boolean, discovery: import('./discovery.js').Discovery | null, timer: ReturnType<typeof setTimeout> | null, pending: 'active' | 'passive' | null }>} */
26
- this.entries = new Map()
27
- }
28
-
29
- /**
30
- * Register a topic. One entry per topic, shared by every slot on it until all are removed;
31
- * a new entry starts untouched, at the bottom.
32
- *
33
- * @param {Uint8Array} topic
34
- * @param {{ pinned?: boolean }} [opts]
35
- * @returns {Slot}
36
- */
37
- add(topic, { pinned = false } = {}) {
38
- const id = b4a.toHex(topic)
39
- let e = this.entries.get(id)
40
- if (!e) {
41
- e = {
42
- topic,
43
- pinned,
44
- refs: 0,
45
- touched: 0,
46
- off: false,
47
- discovery: null,
48
- timer: null,
49
- pending: null
50
- }
51
- this.entries.set(id, e)
52
- }
53
- e.refs++
54
- this.refresh()
55
- const presence = this
56
- return {
57
- get mode() {
58
- return e.discovery ? e.discovery.mode : null
59
- },
60
- touch() {
61
- e.touched = Date.now()
62
- e.off = false
63
- presence.refresh()
64
- },
65
- off() {
66
- e.off = true
67
- presence.refresh()
68
- },
69
- remove() {
70
- if (--e.refs > 0) return
71
- presence.entries.delete(id)
72
- presence._leave(e)
73
- }
74
- }
75
- }
76
-
77
- /**
78
- * @param {Uint8Array} topic
79
- * @returns {'active' | 'passive' | null}
80
- */
81
- mode(topic) {
82
- const e = this.entries.get(b4a.toHex(topic))
83
- return e?.discovery ? e.discovery.mode : null
84
- }
85
-
86
- refresh() {
87
- if (this.network.closing || this.network.closed) return
88
- const ranked = []
89
- for (const e of this.entries.values()) {
90
- if (e.pinned) this._want(e, ACTIVE)
91
- else if (e.off) this._want(e, null)
92
- else ranked.push(e)
93
- }
94
- ranked.sort((a, b) => b.touched - a.touched)
95
- ranked.forEach((e, i) => {
96
- this._want(e, i < this.active ? ACTIVE : i < this.active + this.announced ? PASSIVE : null)
97
- })
98
- }
99
-
100
- close() {
101
- for (const e of this.entries.values()) clearTimeout(e.timer)
102
- this.entries.clear()
103
- }
104
-
105
- // up at once, down after idle: a database at the edge of the budget must not churn the DHT
106
- /** @private */
107
- _want(e, mode) {
108
- const current = e.discovery ? e.discovery.mode : null
109
- if (rank(mode) < rank(current)) {
110
- e.pending = mode
111
- if (!e.timer) e.timer = setTimeout(() => this._settle(e), this.idle)
112
- return
113
- }
114
- clearTimeout(e.timer)
115
- e.timer = null
116
- if (mode === current) return
117
- if (!e.discovery) e.discovery = this.network.join(e.topic, { mode })
118
- else e.discovery.activate().catch(safetyCatch)
119
- }
120
-
121
- /** @private */
122
- _settle(e) {
123
- e.timer = null
124
- if (e.pending === PASSIVE) e.discovery.deactivate().catch(safetyCatch)
125
- else this._leave(e)
126
- }
127
-
128
- /** @private */
129
- _leave(e) {
130
- clearTimeout(e.timer)
131
- e.timer = null
132
- e.discovery?.destroy().catch(safetyCatch)
133
- e.discovery = null
134
- }
135
- }
@@ -1,63 +0,0 @@
1
- export type Slot = {
2
- mode: 'active' | 'passive' | null;
3
- touch: () => void;
4
- off: () => void;
5
- remove: () => void;
6
- };
7
- /**
8
- * Which handles swarm. Ranked by last touch: the latest `active` search and announce, the
9
- * next `announced` announce only, the rest leave their topic. A handle moves up at once and
10
- * down only after `idle` ms. A pinned handle always searches, outside the budget.
11
- *
12
- * @typedef {{ mode: 'active' | 'passive' | null, touch: () => void, off: () => void, remove: () => void }} Slot
13
- */
14
- export declare class Presence {
15
- network: import("./index.js").Network;
16
- active: number;
17
- announced: number;
18
- idle: number;
19
- /** @type {Map<string, { topic: Uint8Array, pinned: boolean, refs: number, touched: number, off: boolean, discovery: import('./discovery.js').Discovery | null, timer: ReturnType<typeof setTimeout> | null, pending: 'active' | 'passive' | null }>} */
20
- entries: Map<string, {
21
- topic: Uint8Array;
22
- pinned: boolean;
23
- refs: number;
24
- touched: number;
25
- off: boolean;
26
- discovery: import('./discovery.js').Discovery | null;
27
- timer: ReturnType<typeof setTimeout> | null;
28
- pending: 'active' | 'passive' | null;
29
- }>;
30
- /**
31
- * @param {import('./index.js').Network} network
32
- * @param {{ active?: number, announced?: number, idle?: number }} [opts]
33
- */
34
- constructor(network: import('./index.js').Network, { active, announced, idle }?: {
35
- active?: number;
36
- announced?: number;
37
- idle?: number;
38
- });
39
- /**
40
- * Register a topic. One entry per topic, shared by every slot on it until all are removed;
41
- * a new entry starts untouched, at the bottom.
42
- *
43
- * @param {Uint8Array} topic
44
- * @param {{ pinned?: boolean }} [opts]
45
- * @returns {Slot}
46
- */
47
- add(topic: Uint8Array, { pinned }?: {
48
- pinned?: boolean;
49
- }): Slot;
50
- /**
51
- * @param {Uint8Array} topic
52
- * @returns {'active' | 'passive' | null}
53
- */
54
- mode(topic: Uint8Array): 'active' | 'passive' | null;
55
- refresh(): void;
56
- close(): void;
57
- /** @private */
58
- private _want;
59
- /** @private */
60
- private _settle;
61
- /** @private */
62
- private _leave;
63
- }