@cero-base/core 2.11.0 → 3.0.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/package.json +8 -8
- package/src/blobs/codec.js +25 -0
- package/src/blobs/index.js +5 -2
- package/src/blobs/server.js +2 -2
- package/src/database/dispatch.js +805 -208
- package/src/database/encryption.js +25 -21
- package/src/database/index.js +747 -124
- package/src/database/rotation.js +333 -38
- package/src/lib/constants.js +10 -0
- package/src/lib/errors.js +8 -0
- package/src/lib/schema.js +12 -2
- package/src/lib/spec/index.js +10 -5
- package/src/lib/spec/schema.json +13 -1
- package/src/lib/utils.js +24 -3
- package/src/mailbox/inbox.js +368 -41
- package/src/mailbox/index.js +75 -20
- package/src/mailbox/post.js +13 -8
- package/src/network/index.js +12 -5
- package/src/pairing/index.js +347 -57
- package/src/pairing/invite.js +36 -12
- package/src/pairing/response.js +78 -0
- package/src/push/index.js +20 -2
- package/types/blobs/codec.d.ts +13 -0
- package/types/blobs/index.d.ts +2 -0
- package/types/database/dispatch.d.ts +52 -7
- package/types/database/encryption.d.ts +13 -5
- package/types/database/index.d.ts +199 -19
- package/types/database/rotation.d.ts +85 -2
- package/types/lib/constants.d.ts +4 -0
- package/types/lib/errors.d.ts +6 -0
- package/types/lib/schema.d.ts +11 -0
- package/types/lib/utils.d.ts +2 -0
- package/types/mailbox/inbox.d.ts +78 -10
- package/types/mailbox/index.d.ts +42 -16
- package/types/mailbox/post.d.ts +7 -5
- package/types/pairing/index.d.ts +53 -8
- package/types/pairing/invite.d.ts +27 -8
- package/types/pairing/response.d.ts +50 -0
- package/types/push/index.d.ts +12 -2
package/src/lib/utils.js
CHANGED
|
@@ -58,6 +58,13 @@ export function outranks(a, b) {
|
|
|
58
58
|
return isRank(a) && isRank(b) && RANK[a] > RANK[b]
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/** @type {(value: unknown) => boolean} */
|
|
62
|
+
export function isOptions(value) {
|
|
63
|
+
if (typeof value !== 'object' || value === null) return false
|
|
64
|
+
const proto = Object.getPrototypeOf(value)
|
|
65
|
+
return proto === Object.prototype || proto === null
|
|
66
|
+
}
|
|
67
|
+
|
|
61
68
|
/**
|
|
62
69
|
* Stream-of-snapshots primitive. Couples a `get` (returns the latest value) with a `watch`
|
|
63
70
|
* (re-fires on change) and emits the newest snapshot every time `watch` ticks.
|
|
@@ -125,11 +132,19 @@ const fold = (s) =>
|
|
|
125
132
|
const IDS = new Set(['id', 'memberId'])
|
|
126
133
|
|
|
127
134
|
export function searchHit(row, term, fields) {
|
|
128
|
-
|
|
135
|
+
return hits(row, terms(term), fields)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function terms(term) {
|
|
139
|
+
return String(term).split(/\s+/).map(fold).filter(Boolean)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** @param {Record<string, unknown>} row @param {string[]} folded @param {string[]} [fields] */
|
|
143
|
+
function hits(row, folded, fields) {
|
|
129
144
|
// ids are random z32: any term can occur in one
|
|
130
145
|
const keys = fields && fields.length ? fields : Object.keys(row).filter((k) => !IDS.has(k))
|
|
131
146
|
const hay = keys.map((k) => (typeof row[k] === 'string' ? fold(row[k]) : '')).join(' ')
|
|
132
|
-
return
|
|
147
|
+
return folded.every((t) => hay.includes(t))
|
|
133
148
|
}
|
|
134
149
|
|
|
135
150
|
/**
|
|
@@ -143,6 +158,9 @@ export function searchHit(row, term, fields) {
|
|
|
143
158
|
*/
|
|
144
159
|
export function filter(rows, query) {
|
|
145
160
|
if (!query) return rows
|
|
161
|
+
if (query.fields !== undefined && !Array.isArray(query.fields)) {
|
|
162
|
+
throw CeroError.INVALID('fields is a list of field names')
|
|
163
|
+
}
|
|
146
164
|
let out = rows
|
|
147
165
|
for (const key of Object.keys(query)) {
|
|
148
166
|
if (QUERY_RESERVED.has(key)) continue
|
|
@@ -152,7 +170,10 @@ export function filter(rows, query) {
|
|
|
152
170
|
if (query.gte !== undefined) out = out.filter((r) => r.id >= query.gte)
|
|
153
171
|
if (query.lt !== undefined) out = out.filter((r) => r.id < query.lt)
|
|
154
172
|
if (query.lte !== undefined) out = out.filter((r) => r.id <= query.lte)
|
|
155
|
-
if (query.search)
|
|
173
|
+
if (query.search) {
|
|
174
|
+
const folded = terms(query.search)
|
|
175
|
+
out = out.filter((r) => hits(r, folded, query.fields))
|
|
176
|
+
}
|
|
156
177
|
if (query.reverse) out = [...out].reverse()
|
|
157
178
|
if (query.limit !== undefined) out = out.slice(0, query.limit)
|
|
158
179
|
return out
|
package/src/mailbox/inbox.js
CHANGED
|
@@ -6,7 +6,23 @@ import b4a from 'b4a'
|
|
|
6
6
|
import { CeroError } from '../lib/errors.js'
|
|
7
7
|
|
|
8
8
|
const NS = b4a.from('cero/mailbox')
|
|
9
|
-
|
|
9
|
+
// a read holds its slot until its message was handled, `timeout` at most to open it and as long
|
|
10
|
+
// again to handle it: a peer announcing keys nobody serves holds PER_PEER of the READS at
|
|
11
|
+
// most, however often it reconnects, and the peers take their turns, so mail from the others
|
|
12
|
+
// reads in the slots left
|
|
13
|
+
const READS = 16
|
|
14
|
+
const PER_PEER = 4
|
|
15
|
+
// a connection's keys waiting: what a mirror announces of one address at once. Past it a sender's
|
|
16
|
+
// posts are asked to announce again once its queue is empty; a mirror answers no such lookup
|
|
17
|
+
const QUEUED = 32
|
|
18
|
+
// a handled id is remembered this long, so a mirror announcing it again hands nothing over.
|
|
19
|
+
// Nothing bounds how long a mirror holds a core: one it announces after this is handed over again
|
|
20
|
+
const HANDLED_FOR = 30 * 24 * 60 * 60 * 1000
|
|
21
|
+
// a ceiling far above use, past which the oldest handled id goes
|
|
22
|
+
const HANDLED = 65536
|
|
23
|
+
// no row this code wrote is older: a `handled` before it, or ahead of now, is no time
|
|
24
|
+
const EPOCH = Date.UTC(2026, 0)
|
|
25
|
+
const EMPTY = b4a.alloc(0)
|
|
10
26
|
|
|
11
27
|
/**
|
|
12
28
|
* The keypair behind the address a secret owns.
|
|
@@ -15,35 +31,77 @@ const READ_TIMEOUT = 30000
|
|
|
15
31
|
* @returns {{ publicKey: Uint8Array, secretKey: Uint8Array }}
|
|
16
32
|
*/
|
|
17
33
|
export function keyPair(secret) {
|
|
34
|
+
// Bare ends the process on a hash of what is no buffer, where Node throws
|
|
35
|
+
if (!b4a.isBuffer(secret)) throw CeroError.INVALID('secret must be a buffer')
|
|
18
36
|
return crypto.encryptionKeyPair(crypto.hash([NS, secret]))
|
|
19
37
|
}
|
|
20
38
|
|
|
21
39
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
40
|
+
* A handled row old enough to forget; one whose `handled` is no time is not.
|
|
41
|
+
*
|
|
42
|
+
* @param {import('./index.js').Mail} mail
|
|
43
|
+
* @returns {boolean}
|
|
44
|
+
*/
|
|
45
|
+
export function aged({ handled }) {
|
|
46
|
+
return isTime(handled) && Date.now() - handled >= HANDLED_FOR
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// per store, the cores being read or erased: a core opened while its purge runs reads a header
|
|
50
|
+
// half deleted and throws where no caller can catch it, so the two never overlap
|
|
51
|
+
const using = new WeakMap()
|
|
52
|
+
|
|
53
|
+
function exclusive(store, key, fn) {
|
|
54
|
+
const id = b4a.toHex(key)
|
|
55
|
+
let held = using.get(store)
|
|
56
|
+
if (!held) using.set(store, (held = new Map()))
|
|
57
|
+
const run = (held.get(id) || Promise.resolve()).then(fn)
|
|
58
|
+
const done = run.then(noop, noop)
|
|
59
|
+
held.set(id, done)
|
|
60
|
+
done.then(() => held.get(id) === done && held.delete(id))
|
|
61
|
+
return run
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Erase the core a message travelled in, once nothing reads it. Corestore leaves a core that
|
|
66
|
+
* still has a session open, and that is an error here, not silence. Nothing is erased once `live`
|
|
67
|
+
* says no, or the store is closing. Resolves true once no such core is stored.
|
|
24
68
|
*
|
|
25
69
|
* @param {import('corestore')} store
|
|
26
70
|
* @param {Uint8Array} key
|
|
27
|
-
* @
|
|
71
|
+
* @param {() => boolean} [live]
|
|
72
|
+
* @returns {Promise<boolean>}
|
|
28
73
|
*/
|
|
29
|
-
export
|
|
30
|
-
|
|
31
|
-
|
|
74
|
+
export function erase(store, key, live = () => true) {
|
|
75
|
+
return exclusive(store, key, async () => {
|
|
76
|
+
if (!live() || store.closing) return false
|
|
77
|
+
if (!(await store.storage.hasCore(crypto.discoveryKey(key)))) return true
|
|
78
|
+
const [gone] = await store.purge(key)
|
|
79
|
+
if (!gone) throw CeroError.CONFLICT(`mailbox: ${b4a.toHex(key)} is still open, not erased`)
|
|
80
|
+
return true
|
|
81
|
+
})
|
|
32
82
|
}
|
|
33
83
|
|
|
34
84
|
/**
|
|
35
|
-
* Receives at the address a secret owns, direct from the sender or from a mirror. A message
|
|
36
|
-
*
|
|
85
|
+
* Receives at the address a secret owns, direct from the sender or from a mirror. A message is
|
|
86
|
+
* kept in `box` from before its block is read until `onmessage` resolves, as a row naming its
|
|
87
|
+
* core, never the message, and its id stays there for HANDLED_FOR once handled; one that does not
|
|
88
|
+
* open in time, or that `onmessage` resolves `false` on, is dropped.
|
|
37
89
|
* A core the inbox fetched is erased once dropped, or once handled with `keep` false; one this
|
|
38
|
-
* device held already is left alone
|
|
90
|
+
* device held already is left alone, and so is one whose message is found at a start in a row
|
|
91
|
+
* written before its block was read: that row does not say the inbox fetched it, so nothing is
|
|
92
|
+
* erased for it, whatever `keep` says or `onmessage` resolves.
|
|
39
93
|
*/
|
|
40
94
|
export class Inbox extends ReadyResource {
|
|
41
95
|
/**
|
|
42
96
|
* @param {import('../network/index.js').Network} network
|
|
43
97
|
* @param {Uint8Array} secret
|
|
44
|
-
* @param {{ box: import('./index.js').Box, onmessage: (message: Uint8Array) => unknown, onerror: (err: Error) => void, keep?: boolean }} opts
|
|
98
|
+
* @param {{ box: import('./index.js').Box, onmessage: (message: Uint8Array) => unknown, onerror: (err: Error) => void, keep?: boolean, timeout?: number, after?: Promise<void>[], siblings?: () => Inbox[] }} opts `after`: closes to wait for before it opens. `siblings`: the other inboxes on its box at its address, as of the call.
|
|
45
99
|
*/
|
|
46
|
-
constructor(
|
|
100
|
+
constructor(
|
|
101
|
+
network,
|
|
102
|
+
secret,
|
|
103
|
+
{ box, onmessage, onerror, keep = true, timeout = 30000, after = [], siblings = () => [] }
|
|
104
|
+
) {
|
|
47
105
|
super()
|
|
48
106
|
this.network = network
|
|
49
107
|
this.keyPair = keyPair(secret)
|
|
@@ -52,8 +110,31 @@ export class Inbox extends ReadyResource {
|
|
|
52
110
|
this.onmessage = onmessage
|
|
53
111
|
this.onerror = onerror
|
|
54
112
|
this.keep = keep
|
|
113
|
+
this.timeout = timeout
|
|
114
|
+
/** @private */
|
|
115
|
+
this._mail = new Map() // id → { key, queued, busy }: queued by peers, or read or handled now
|
|
116
|
+
/** @private */
|
|
117
|
+
this._turns = new Map() // peer → the ids it announced, waiting, in turn order
|
|
118
|
+
/** @private */
|
|
119
|
+
this._load = new Map() // remote key → its reads in flight
|
|
120
|
+
/** @private */
|
|
121
|
+
this._behind = new Set() // peers that announced more than QUEUED
|
|
55
122
|
/** @private */
|
|
56
|
-
this.
|
|
123
|
+
this._reading = 0
|
|
124
|
+
/** @private */
|
|
125
|
+
this._kept = [] // rows found at open, still to read
|
|
126
|
+
/** @private */
|
|
127
|
+
this._handled = new Map() // id → when it was handled, oldest first
|
|
128
|
+
/** @private */
|
|
129
|
+
this._erasing = new Set()
|
|
130
|
+
/** @private */
|
|
131
|
+
this._landing = new Map() // read → its id, up to its row in the box
|
|
132
|
+
/** @private */
|
|
133
|
+
this._waiting = new Set() // cores open for a block still to come
|
|
134
|
+
/** @private */
|
|
135
|
+
this._after = after
|
|
136
|
+
/** @private */
|
|
137
|
+
this._siblings = siblings
|
|
57
138
|
/** @private */
|
|
58
139
|
this._session = null
|
|
59
140
|
/** @private */
|
|
@@ -62,16 +143,35 @@ export class Inbox extends ReadyResource {
|
|
|
62
143
|
|
|
63
144
|
/** @private */
|
|
64
145
|
async _open() {
|
|
146
|
+
// one still closing at this address may yet leave a row: the box is read once it has
|
|
147
|
+
await Promise.allSettled(this._after)
|
|
148
|
+
const handled = []
|
|
65
149
|
for (const mail of await this.box.list()) {
|
|
66
150
|
if (!b4a.equals(mail.address, this.address)) continue
|
|
67
|
-
|
|
68
|
-
|
|
151
|
+
if (mail.handled) {
|
|
152
|
+
if (!isTime(mail.handled)) {
|
|
153
|
+
mail.handled = Date.now()
|
|
154
|
+
await this.box.put({
|
|
155
|
+
id: mail.id,
|
|
156
|
+
address: this.address,
|
|
157
|
+
message: EMPTY,
|
|
158
|
+
handled: mail.handled,
|
|
159
|
+
fetched: mail.fetched
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
handled.push(mail)
|
|
163
|
+
continue
|
|
164
|
+
}
|
|
165
|
+
this._keep(mail)
|
|
69
166
|
}
|
|
167
|
+
this._next()
|
|
168
|
+
handled.sort((a, b) => a.handled - b.handled)
|
|
169
|
+
for (const mail of handled) this._handled.set(mail.id, mail.handled)
|
|
170
|
+
await this._prune()
|
|
70
171
|
this._session = this.network.wakeup.session(this.address, {
|
|
71
172
|
discoveryKey: crypto.discoveryKey(this.address),
|
|
72
|
-
onannounce: (entries) =>
|
|
73
|
-
|
|
74
|
-
}
|
|
173
|
+
onannounce: (entries, peer) => this._onannounce(entries, peer),
|
|
174
|
+
onpeerremove: (peer) => this._forget(peer)
|
|
75
175
|
})
|
|
76
176
|
// active on both ends: whichever side comes second is the one that looks the other up
|
|
77
177
|
this._discovery = this.network.join(crypto.discoveryKey(this.address))
|
|
@@ -82,47 +182,274 @@ export class Inbox extends ReadyResource {
|
|
|
82
182
|
this._session?.destroy()
|
|
83
183
|
// the unannounce is a DHT round trip, never waited on
|
|
84
184
|
this._discovery?.destroy().catch(safetyCatch)
|
|
185
|
+
// nothing more is fetched: its sender counts a message delivered once its block is stored
|
|
186
|
+
for (const core of this._waiting) core.close().catch(safetyCatch)
|
|
187
|
+
await Promise.allSettled([...this._landing.keys(), ...this._erasing])
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Take over the reads an inbox that closed at this address left unsettled: each waits for its
|
|
192
|
+
* block as it did there, so one that lands after that close is still handed over.
|
|
193
|
+
*
|
|
194
|
+
* @returns {Promise<void>}
|
|
195
|
+
*/
|
|
196
|
+
async inherit() {
|
|
197
|
+
for (const mail of await this.box.list()) {
|
|
198
|
+
if (!mail.handled && b4a.equals(mail.address, this.address)) this._keep(mail, true)
|
|
199
|
+
}
|
|
200
|
+
this._next()
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// a row to read, unless this inbox has it, or one still open at this address is reading it: it is that inbox's until its read settles or it closes
|
|
204
|
+
/** @private */
|
|
205
|
+
_keep({ id, fetched }, wait = false) {
|
|
206
|
+
if (this._mail.has(id) || this._siblings().some((inbox) => reads(inbox, id))) return
|
|
207
|
+
this._mail.set(id, { key: b4a.from(id, 'hex'), queued: 0, busy: true })
|
|
208
|
+
this._kept.push({ id, fetched, wait })
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// a key stays queued by every peer that announced it, so a read that failed is tried through the
|
|
212
|
+
// next one
|
|
213
|
+
/** @private */
|
|
214
|
+
_onannounce(entries, peer) {
|
|
215
|
+
const ids = this._turns.get(peer) || new Set()
|
|
216
|
+
for (const { key } of entries) {
|
|
217
|
+
const id = b4a.toHex(key)
|
|
218
|
+
if (ids.has(id) || this._handled.has(id)) continue
|
|
219
|
+
if (ids.size >= QUEUED) {
|
|
220
|
+
this._behind.add(peer)
|
|
221
|
+
break
|
|
222
|
+
}
|
|
223
|
+
const mail = this._mail.get(id) || { key, queued: 0, busy: false }
|
|
224
|
+
this._mail.set(id, mail)
|
|
225
|
+
mail.queued++
|
|
226
|
+
ids.add(id)
|
|
227
|
+
}
|
|
228
|
+
if (ids.size && !this._turns.has(peer)) this._turns.set(peer, ids)
|
|
229
|
+
this._next()
|
|
85
230
|
}
|
|
86
231
|
|
|
87
232
|
/** @private */
|
|
88
|
-
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
233
|
+
_forget(peer) {
|
|
234
|
+
const ids = this._turns.get(peer)
|
|
235
|
+
this._behind.delete(peer)
|
|
236
|
+
if (!ids) return
|
|
237
|
+
this._turns.delete(peer)
|
|
238
|
+
for (const id of ids) {
|
|
239
|
+
const mail = this._mail.get(id)
|
|
240
|
+
if (--mail.queued === 0 && !mail.busy) this._mail.delete(id)
|
|
241
|
+
}
|
|
94
242
|
}
|
|
95
243
|
|
|
96
244
|
/** @private */
|
|
97
|
-
|
|
245
|
+
_next() {
|
|
246
|
+
while (this._kept.length && this._reading < READS && !this.closing) {
|
|
247
|
+
this._reading++
|
|
248
|
+
const mail = this._kept.shift()
|
|
249
|
+
this._read(mail.id, this._resume(mail))
|
|
250
|
+
.catch((err) => this.onerror(err))
|
|
251
|
+
.finally(() => {
|
|
252
|
+
this._reading--
|
|
253
|
+
this._next()
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
for (const [peer, ids] of this._turns) {
|
|
257
|
+
if (this._reading >= READS || this.closing) return
|
|
258
|
+
const from = b4a.toHex(peer.stream.remotePublicKey)
|
|
259
|
+
const load = this._load.get(from) || 0
|
|
260
|
+
if (load >= PER_PEER) continue
|
|
261
|
+
const id = idle(ids, this._mail)
|
|
262
|
+
if (id === null) continue
|
|
263
|
+
ids.delete(id)
|
|
264
|
+
if (ids.size === 0 && this._behind.delete(peer)) this._session.lookup(peer)
|
|
265
|
+
// to the back of the turn
|
|
266
|
+
this._turns.delete(peer)
|
|
267
|
+
if (ids.size) this._turns.set(peer, ids)
|
|
268
|
+
const mail = this._mail.get(id)
|
|
269
|
+
mail.queued--
|
|
270
|
+
mail.busy = true
|
|
271
|
+
this._reading++
|
|
272
|
+
this._load.set(from, load + 1)
|
|
273
|
+
this._read(id, this._land(id, mail.key))
|
|
274
|
+
.catch((err) => this.onerror(err))
|
|
275
|
+
.finally(() => {
|
|
276
|
+
this._reading--
|
|
277
|
+
const left = this._load.get(from) - 1
|
|
278
|
+
if (left) this._load.set(from, left)
|
|
279
|
+
else this._load.delete(from)
|
|
280
|
+
this._next()
|
|
281
|
+
})
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// done with it, unless `retry` and a peer still has it queued
|
|
286
|
+
/** @private */
|
|
287
|
+
_settle(id, retry = false) {
|
|
288
|
+
const mail = this._mail.get(id)
|
|
289
|
+
mail.busy = false
|
|
290
|
+
if (retry && mail.queued > 0) return
|
|
291
|
+
this._mail.delete(id)
|
|
292
|
+
if (mail.queued > 0) for (const ids of this._turns.values()) ids.delete(id)
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** @private */
|
|
296
|
+
async _read(id, landing) {
|
|
297
|
+
this._landing.set(landing, id)
|
|
298
|
+
const mail = await landing.finally(() => this._landing.delete(landing))
|
|
299
|
+
if (!mail) return
|
|
300
|
+
// past it the slot is free, and the message stays in the box until its handler resolves
|
|
301
|
+
await new Promise((resolve) => {
|
|
302
|
+
const timer = setTimeout(resolve, this.timeout)
|
|
303
|
+
timer.unref()
|
|
304
|
+
this._handle(mail).finally(() => {
|
|
305
|
+
clearTimeout(timer)
|
|
306
|
+
resolve()
|
|
307
|
+
})
|
|
308
|
+
})
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// in the box before its block is asked for, with no `fetched` until it was read: killed in between, the next start hands it over and erases nothing
|
|
312
|
+
/** @private */
|
|
313
|
+
async _land(id, key) {
|
|
314
|
+
// one box for every address: a row another address keeps under this id stays as it is
|
|
315
|
+
const row = await this.box.get(id)
|
|
316
|
+
if (row && !b4a.equals(row.address, this.address)) return this._settle(id)
|
|
317
|
+
// closed while its row was looked up: nothing is written for a key it never asked for
|
|
318
|
+
if (this.closing) return this._settle(id)
|
|
319
|
+
await this.box.put({ id, address: this.address, message: EMPTY })
|
|
320
|
+
const { held, message } = await this._unseal(key, { timeout: this.timeout })
|
|
321
|
+
// a core this device already held is not the inbox's to erase, whatever is announced here
|
|
322
|
+
const fetched = !held
|
|
323
|
+
if (!message) {
|
|
324
|
+
if (this.closing) return this._settle(id)
|
|
325
|
+
await this.box.del(id)
|
|
326
|
+
await this._drop(id, fetched, true)
|
|
327
|
+
return null
|
|
328
|
+
}
|
|
329
|
+
await this.box.put({ id, address: this.address, message: EMPTY, fetched })
|
|
330
|
+
return { id, message, fetched }
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// kept from before a restart: its message is read from its core as this device holds it, never from a peer, unless `wait`
|
|
334
|
+
/** @private */
|
|
335
|
+
async _resume({ id, fetched, wait }) {
|
|
336
|
+
const opts = wait ? { timeout: this.timeout } : { wait: false }
|
|
337
|
+
const { held, message } = await this._unseal(b4a.from(id, 'hex'), opts)
|
|
338
|
+
if (message) return { id, message, fetched }
|
|
339
|
+
// a read its own close cut short says nothing of the row: it waits for the next inbox at its address
|
|
340
|
+
if (this.closing) return this._settle(id)
|
|
341
|
+
await this.box.del(id)
|
|
342
|
+
// a peer that announced it while its row waited still has it queued: it is read from there
|
|
343
|
+
await this._drop(id, fetched && held, true)
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// the message in a core, and whether this device held the core before
|
|
347
|
+
/** @private */
|
|
348
|
+
_unseal(key, opts) {
|
|
98
349
|
const { store } = this.network
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
350
|
+
return exclusive(store, key, async () => {
|
|
351
|
+
const held = await store.storage.hasCore(crypto.discoveryKey(key))
|
|
352
|
+
// checked last before the core opens: a close from here on finds it among those waiting
|
|
353
|
+
if (this.closing) opts = { wait: false }
|
|
354
|
+
if (!held && opts.wait === false) return { held, message: null }
|
|
355
|
+
const core = store.get({ key })
|
|
356
|
+
this._waiting.add(core)
|
|
357
|
+
try {
|
|
358
|
+
return { held, message: crypto.decrypt(await core.get(0, opts), this.keyPair) }
|
|
359
|
+
} catch {
|
|
360
|
+
return { held, message: null } // nobody served it in time, or the inbox closed
|
|
361
|
+
} finally {
|
|
362
|
+
this._waiting.delete(core)
|
|
363
|
+
await core.close()
|
|
364
|
+
}
|
|
365
|
+
})
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// none once closing: the next mailbox open erases what was handled with keep false
|
|
369
|
+
/** @private */
|
|
370
|
+
async _erase(key) {
|
|
371
|
+
const erasing = erase(this.network.store, key, () => !this.closing)
|
|
372
|
+
this._erasing.add(erasing)
|
|
103
373
|
try {
|
|
104
|
-
|
|
374
|
+
return await erasing
|
|
105
375
|
} finally {
|
|
106
|
-
|
|
376
|
+
this._erasing.delete(erasing)
|
|
107
377
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// nothing of it stays, so the next announce (a mirror's, a reconnect's) reads it again
|
|
381
|
+
/** @private */
|
|
382
|
+
async _drop(id, fetched, retry) {
|
|
383
|
+
try {
|
|
384
|
+
if (fetched) await this._erase(b4a.from(id, 'hex'))
|
|
385
|
+
} finally {
|
|
386
|
+
this._settle(id, retry)
|
|
111
387
|
}
|
|
112
|
-
const mail = { id, address: this.address, message, fetched }
|
|
113
|
-
await this.box.put(mail)
|
|
114
|
-
this._handle(mail)
|
|
115
388
|
}
|
|
116
389
|
|
|
117
390
|
// dropped once handled; one that throws stays for the next time this address is received
|
|
118
391
|
/** @private */
|
|
119
392
|
async _handle({ id, message, fetched }) {
|
|
393
|
+
// closing, it hands nothing over: the message waits in the box for the next inbox at its address
|
|
394
|
+
if (this.closing) return this._settle(id)
|
|
395
|
+
let taken
|
|
120
396
|
try {
|
|
121
|
-
await this.onmessage(message)
|
|
122
|
-
await this.box.del(id)
|
|
123
|
-
if (!this.keep && fetched) await erase(this.network.store, b4a.from(id, 'hex'))
|
|
397
|
+
taken = (await this.onmessage(message)) !== false
|
|
124
398
|
} catch (err) {
|
|
125
|
-
this.onerror(err)
|
|
399
|
+
return this.onerror(err)
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
// turned away as the inbox closes, it is kept as handled for the next start to erase
|
|
403
|
+
if (!taken && !(this.closing && fetched)) {
|
|
404
|
+
await this.box.del(id)
|
|
405
|
+
return await this._drop(id, fetched, false)
|
|
406
|
+
}
|
|
407
|
+
// on a handled row, `fetched` is a core still to erase: the next start does it if this cannot
|
|
408
|
+
const erasing = (!taken || !this.keep) && fetched
|
|
409
|
+
const handled = await this._remember(id, erasing)
|
|
410
|
+
if (erasing && (await this._erase(b4a.from(id, 'hex')))) {
|
|
411
|
+
await this.box.put({ id, address: this.address, message: EMPTY, handled })
|
|
412
|
+
}
|
|
413
|
+
this._settle(id)
|
|
414
|
+
} catch (err) {
|
|
415
|
+
// closed meanwhile, its box may be gone with it: unrecorded, it comes again the next time its address is received
|
|
416
|
+
if (!this.closed) this.onerror(err)
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// in place of its row
|
|
421
|
+
/** @private */
|
|
422
|
+
async _remember(id, fetched) {
|
|
423
|
+
const handled = Date.now()
|
|
424
|
+
await this.box.put({ id, address: this.address, message: EMPTY, handled, fetched })
|
|
425
|
+
this._handled.set(id, handled)
|
|
426
|
+
await this._prune()
|
|
427
|
+
return handled
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// the oldest go once HANDLED_FOR old, or past the ceiling
|
|
431
|
+
/** @private */
|
|
432
|
+
async _prune() {
|
|
433
|
+
for (const [id, handled] of this._handled) {
|
|
434
|
+
if (this._handled.size <= HANDLED && Date.now() - handled < HANDLED_FOR) break
|
|
435
|
+
this._handled.delete(id)
|
|
436
|
+
await this.box.del(id)
|
|
126
437
|
}
|
|
127
438
|
}
|
|
128
439
|
}
|
|
440
|
+
|
|
441
|
+
function noop() {}
|
|
442
|
+
|
|
443
|
+
function isTime(handled) {
|
|
444
|
+
return handled > EPOCH && handled <= Date.now()
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function reads(inbox, id) {
|
|
448
|
+
for (const read of inbox._landing.values()) if (read === id) return true
|
|
449
|
+
return false
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function idle(ids, mail) {
|
|
453
|
+
for (const id of ids) if (!mail.get(id).busy) return id
|
|
454
|
+
return null
|
|
455
|
+
}
|