@cero-base/cero 2.12.0 → 3.0.1

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.
@@ -79,6 +79,10 @@ export class Local extends ReadyResource {
79
79
  export function box(store, name) {
80
80
  return {
81
81
  list: async () => (await store.get(name)).data.map(unpack),
82
+ get: async (id) => {
83
+ const { data } = await store.get(name, id)
84
+ return data && unpack(data)
85
+ },
82
86
  put: (mail) => store.put(name, pack(mail)),
83
87
  del: (id) => store.del(name, id)
84
88
  }
@@ -89,8 +93,8 @@ function pack({ mirrors = [], keep = true, ...mail }) {
89
93
  return { ...mail, mirrors: b4a.concat(mirrors), erase: !keep }
90
94
  }
91
95
 
92
- function unpack({ id, address, message, mirrors, name, erase, fetched }) {
96
+ function unpack({ id, address, message, mirrors, name, erase, fetched, handled, sealed }) {
93
97
  const keys = []
94
98
  for (let i = 0; i < (mirrors?.byteLength || 0); i += 32) keys.push(mirrors.subarray(i, i + 32))
95
- return { id, address, message, mirrors: keys, name, keep: !erase, fetched }
99
+ return { id, address, message, mirrors: keys, name, keep: !erase, fetched, handled, sealed }
96
100
  }
package/src/push/index.js CHANGED
@@ -4,32 +4,42 @@ import b4a from 'b4a'
4
4
  import safetyCatch from 'safety-catch'
5
5
 
6
6
  import c from 'compact-encoding'
7
- import { verify, decrypt } from '@cero-base/core/push'
7
+ import { verify, decrypt, topic } from '@cero-base/core/push'
8
8
  import { CeroError } from '@cero-base/core/errors'
9
9
  import { epochEntries } from '@cero-base/core/database/encryption'
10
10
 
11
11
  import { Local } from '../local/index.js'
12
- import { current } from '../lib/swap.js'
12
+ import { current, lock } from '../lib/swap.js'
13
13
 
14
14
  /**
15
- * A push verified against the handles the topics rows name, with the row it wrote when the block
16
- * rode along and this device holds the handle's keys.
15
+ * A push verified against the handle its topic names, read from that handle's `topics` row alone,
16
+ * with the row it wrote when the block rode along and this device holds the handle's keys.
17
17
  *
18
18
  * @param {import('hypercore-storage')} storage
19
19
  * @param {import('../lib/spec.js').Spec} spec
20
20
  * @param {Uint8Array} payload
21
- * @param {Array<{ id: string, handle: string, type: string, key: Uint8Array, name: string | null, encryptionKey?: Uint8Array | null, epochs?: Uint8Array | null }>} rows The root's `topics` rows.
21
+ * @param {import('@cero-base/core/storage').Storage} store The root's local store, which keeps the `topics` rows.
22
22
  * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
23
23
  */
24
- export async function read(storage, spec, payload, rows) {
25
- const handles = rows.map(({ handle, key, type, name }) => ({ id: handle, key, type, name }))
26
- const hit = await verify(storage, payload, handles)
24
+ export async function read(storage, spec, payload, store) {
25
+ const id = topic(payload)
26
+ const keys = id && (await store.get('topics', id)).data
27
+ if (!keys) return null
28
+ const { handle, key, type, name, writers } = keys
29
+ const hit = await verify(storage, payload, [
30
+ { id: handle, key, type, name, writers: keysOf(writers) }
31
+ ])
27
32
  if (!hit) return null
28
- const keys = rows.find((r) => r.handle === hit.id)
29
33
  const row = await rowOf(storage, spec, hit, keys)
30
34
  return { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer, ref: hit.ref, row }
31
35
  }
32
36
 
37
+ function keysOf(bytes) {
38
+ const out = []
39
+ for (let i = 0; i < (bytes?.byteLength || 0); i += 32) out.push(bytes.subarray(i, i + 32))
40
+ return out
41
+ }
42
+
33
43
  // the row a push's block holds: null when none rode along, or it does not decode with what we hold
34
44
  async function rowOf(storage, spec, hit, { encryptionKey, epochs }) {
35
45
  if (!hit.block || !encryptionKey) return null
@@ -57,23 +67,26 @@ async function rowOf(storage, spec, hit, { encryptionKey, epochs }) {
57
67
  * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
58
68
  */
59
69
  export async function receive(dir, spec, payload, { storageKey } = {}) {
60
- const storage = new HypercoreStorage(await current(dir), { readOnly: true })
70
+ let held = null
71
+ let storage = null
61
72
  let store = null
62
73
  let local = null
63
74
  try {
75
+ held = await lock(dir)
76
+ storage = new HypercoreStorage(await current(dir), { readOnly: true })
64
77
  await storage.ready()
65
78
  store = new Corestore(storage, { manifestVersion: 2 })
66
79
  local = new Local(null, spec, { store, storageKey })
67
80
  await local.ready()
68
- const { data: rows } = await local.store.get('topics')
69
- return await read(storage, spec, payload, rows)
81
+ return await read(storage, spec, payload, local.store)
70
82
  } catch (err) {
71
83
  safetyCatch(err)
72
84
  return null
73
85
  } finally {
74
86
  await local?.close().catch(safetyCatch)
75
87
  await store?.close().catch(safetyCatch)
76
- await storage.close().catch(safetyCatch)
88
+ await storage?.close().catch(safetyCatch)
89
+ await held?.close().catch(safetyCatch)
77
90
  }
78
91
  }
79
92
 
package/src/rpc/client.js CHANGED
@@ -5,7 +5,7 @@ import { CeroError } from '@cero-base/core/errors'
5
5
  import { checkFields, checkRequired } from '@cero-base/core/utils'
6
6
  import c from 'compact-encoding'
7
7
  import z32 from 'z32'
8
- import { decodeId } from '@cero-base/core/blobs/codec'
8
+ import { decodeId, servedType } from '@cero-base/core/blobs/codec'
9
9
 
10
10
  import { Ref } from '../lib/refs.js'
11
11
  import { follow } from './push.js'
@@ -22,6 +22,7 @@ export const {
22
22
  del,
23
23
  watch,
24
24
  call,
25
+ supports,
25
26
  open,
26
27
  invite,
27
28
  revoke,
@@ -56,6 +57,13 @@ export { t, schema }
56
57
  * @property {string|null} name
57
58
  *
58
59
  * @typedef {(Client | Handle) & Record<string, Ref>} Context A UI's root or handle: the verbs take it like an in-process one.
60
+ *
61
+ * @typedef {object} ClientOpts
62
+ * @property {(err: Error) => void} [onerror] Where the worker's background errors go, the console without one.
63
+ * @property {import('./push.js').Messaging} [push] The platform's messaging service, to follow the handles' push topics.
64
+ * @property {string} [phrase] On a worker whose store is new, it recovers the identity of this phrase, as `cero(dir, spec, { phrase })`.
65
+ * @property {string} [invite] On a worker whose store is new, it links to the identity of this device invite, as `cero(dir, spec, { invite })`.
66
+ * @property {(id: string) => void} [onrequest] With `invite`: the request's id as it is sent.
59
67
  */
60
68
 
61
69
  const blobIdEnc = {
@@ -114,11 +122,11 @@ const operators = {
114
122
  const base = root._fileBase || ''
115
123
  const token = root._fileToken || ''
116
124
  const { coreKey, blobId, type } = decodeId(id)
125
+ const served = servedType(type)
117
126
  const key = z32.encode(coreKey)
118
127
  const blob = z32.encode(c.encode(blobIdEnc, blobId))
119
- const tp = type ? `&type=${encodeURIComponent(type)}` : ''
120
128
  const tok = token ? `&token=${token}` : ''
121
- return `${base}/?key=${key}&blob=${blob}${tp}${tok}`
129
+ return `${base}/?key=${key}&blob=${blob}&type=${encodeURIComponent(served)}${tok}`
122
130
  },
123
131
 
124
132
  /**
@@ -428,8 +436,8 @@ const operators = {
428
436
  }
429
437
 
430
438
  /**
431
- * Re-initialize a `Client` from a recovery phrase. Closes the existing
432
- * local state and reseeds identity from the phrase.
439
+ * Switch the app to the identity of a recovery phrase, as `cero.restore` does in the worker: the
440
+ * client is then that identity.
433
441
  *
434
442
  * @param {Client} me
435
443
  * @param {string} phrase
@@ -503,11 +511,13 @@ export class Client extends RPCClient {
503
511
  /**
504
512
  * @param {import('streamx').Duplex} ipc Framed IPC stream (must be writable).
505
513
  * @param {Spec} spec Compiled cero spec (schema + rpc + handles).
506
- * @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts] Where the worker's background errors go, the console without one; `push`: the platform's messaging service, to follow the handles' push topics.
514
+ * @param {ClientOpts} [opts]
507
515
  */
508
- constructor(ipc, spec, { onerror, push } = {}) {
516
+ constructor(ipc, spec, { onerror, push, phrase, invite, onrequest } = {}) {
509
517
  super(ipc, spec)
510
518
  /** @private */
519
+ this._how = { phrase, invite, onrequest }
520
+ /** @private */
511
521
  this._push = push || null
512
522
  if (spec.local?.schema && !spec.local.codec) bindCodec(spec.local)
513
523
  Object.assign(this, operators)
@@ -545,7 +555,11 @@ export class Client extends RPCClient {
545
555
  /** @private */
546
556
  async _open() {
547
557
  await super._open()
548
- this._identify(await this.rpc.init({}))
558
+ const { phrase, invite, onrequest } = this._how
559
+ // a worker on a new store opens as these say; on one with an identity they switch to another
560
+ if (phrase) await restore(this, phrase)
561
+ else if (invite) await link(this, invite, { onrequest })
562
+ else this._identify(await this.rpc.init({}))
549
563
  Ref.attach(this, /** @type {Spec} */ (this.spec).meta.refs)
550
564
  if (/** @type {Spec} */ (this.spec).meta.local?.refs) this.local = new LocalRefs(this)
551
565
  this._pumpErrors()
@@ -652,7 +666,7 @@ class Handle {
652
666
  *
653
667
  * @param {import('streamx').Duplex} ipc
654
668
  * @param {Spec} spec
655
- * @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts]
669
+ * @param {ClientOpts} [opts]
656
670
  * @returns {Promise<Client>}
657
671
  */
658
672
  export async function connect(ipc, spec, opts) {
@@ -667,7 +681,7 @@ export async function connect(ipc, spec, opts) {
667
681
  *
668
682
  * @param {import('streamx').Duplex} ipc Framed IPC duplex stream.
669
683
  * @param {Spec} spec Built cero spec.
670
- * @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts]
684
+ * @param {ClientOpts} [opts]
671
685
  * @returns {Promise<Context>}
672
686
  */
673
687
  function start(ipc, spec, opts) {
package/src/rpc/push.js CHANGED
@@ -1,4 +1,4 @@
1
- import { watch, get, open, activate, receive } from '../lib/operators.js'
1
+ import { watch, get, open, close, activate, receive } from '../lib/operators.js'
2
2
 
3
3
  /**
4
4
  * @typedef {object} Messaging The platform's messaging service, as `connect` takes it for push.
@@ -48,10 +48,16 @@ export function follow(me, messaging) {
48
48
  }
49
49
  }
50
50
 
51
- // while the app sleeps the OS shows the push; the handle syncs first once it wakes on its own
51
+ // while the app sleeps the OS shows the push; the handle syncs first once it wakes on its own, for
52
+ // as long as it stays idle after this close
52
53
  async function wake(me, payload) {
53
54
  if ((await get(me.status)).data.suspended) return
54
55
  const hit = await receive(me, payload)
55
56
  if (!hit?.newer) return
56
- await activate(await open(me[hit.type], { id: hit.id }))
57
+ const h = await open(me[hit.type], { id: hit.id })
58
+ try {
59
+ await activate(h)
60
+ } finally {
61
+ await close(h)
62
+ }
57
63
  }
package/src/rpc/server.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import c from 'compact-encoding'
2
2
  import safetyCatch from 'safety-catch'
3
+ import AbortController from 'bare-abort-controller'
3
4
 
4
5
  import { RPCServer, bindCodec } from '@cero-base/core/rpc'
5
6
  import { CeroError } from '@cero-base/core/errors'
6
7
 
7
8
  import { cero, restore, link } from '../index.js'
9
+ import { peek } from '../lib/peek.js'
8
10
  import {
9
11
  put,
10
12
  set,
@@ -75,9 +77,9 @@ const VERBS = new Map(
75
77
  */
76
78
 
77
79
  /**
78
- * IPC-side RPC server for cero. Bridges an `hrpc` channel to a live `Handle` tree: boots the
79
- * root via `cero()` as soon as it opens, so the network is up while the UI still loads, then
80
- * exposes data ops, pairing, and handle lifecycle.
80
+ * IPC-side RPC server for cero. Bridges an `hrpc` channel to a live `Handle` tree: a store that holds an identity
81
+ * boots its root via `cero()` as soon as it opens, so the network is up while the UI still loads; a new one waits
82
+ * for the client to say how, by init, restore or link. Then it exposes data ops, pairing, and handle lifecycle.
81
83
  */
82
84
  export class Server extends RPCServer {
83
85
  /**
@@ -97,6 +99,8 @@ export class Server extends RPCServer {
97
99
  this.opts = { ...opts, onerror: (err) => this._onerror(err) }
98
100
  /** @type {Set<object>} open error streams, one per connected client */
99
101
  this._errors = new Set()
102
+ /** @private */
103
+ this._reported = new WeakSet()
100
104
  /** @type {Context | null} */
101
105
  this.me = null
102
106
  /** @type {Map<string, Context>} */
@@ -107,7 +111,13 @@ export class Server extends RPCServer {
107
111
  this._held = new Map()
108
112
  /** @private */
109
113
  this._booting = null
114
+ /** @private */
115
+ this._adopting = null
116
+ /** @private */
117
+ this._stop = new AbortController()
110
118
  this._wireInit()
119
+ this._wireRestore()
120
+ this._wireLink()
111
121
  }
112
122
 
113
123
  /**
@@ -131,34 +141,78 @@ export class Server extends RPCServer {
131
141
  /** @private */
132
142
  async _open() {
133
143
  await super._open()
134
- this._booting = this._boot()
135
- // it surfaces on init
136
- this._booting.catch(() => {})
144
+ // its error is the app's even with no request waiting on it, unless the close stopped it
145
+ if (await peek(this.storage, this.spec, this.opts)) {
146
+ this._start().catch((err) => this.closing || this._onerror(err))
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Open the root, as `how` says on a new store: a phrase recovers, an invite links, neither creates.
152
+ * @private
153
+ */
154
+ _start(how = {}) {
155
+ const booting = this._boot(how)
156
+ this._booting = booting
157
+ // it surfaces on the request that waits for it; the next one starts over
158
+ booting.catch(() => {
159
+ if (this._booting === booting) this._booting = null
160
+ })
161
+ return booting
137
162
  }
138
163
 
139
164
  /** @private */
140
- async _boot() {
141
- this.me = await cero(this.storage, this.spec, this.opts)
165
+ async _boot(how) {
166
+ // a close stops a recovery or a link still waiting for a device: the next open goes on with it
167
+ const opts = { ...this.opts, ...how, signal: this._stop.signal }
168
+ this.me = await cero(this.storage, this.spec, opts)
169
+ try {
170
+ await this.me.fileServer.listen()
171
+ this._wireData()
172
+ this._wireHandles()
173
+ this._wireVerbs()
174
+ } catch (err) {
175
+ // the next start opens the same store, whose lock a root left open here still holds
176
+ const me = this.me
177
+ this.me = null
178
+ await me.close().catch(this.opts.onerror)
179
+ throw err
180
+ }
142
181
  this.handles.set(this.me.id, this.me)
143
- await this.me.fileServer.listen()
144
- this._wireData()
145
- this._wireHandles()
146
- this._wireVerbs()
147
- this._wireRestore()
148
- this._wireLink()
149
182
  }
150
183
 
151
184
  /** @private */
152
185
  async _close() {
186
+ this._stop.abort()
153
187
  await this._booting?.catch(() => {})
154
188
  if (this.me) {
155
189
  try {
156
190
  await this.me.close()
157
191
  } catch {}
158
192
  }
193
+ // a link or a restore past its commit resolves with an open root, closed before this ends
194
+ await this._adopting
159
195
  await super._close()
160
196
  }
161
197
 
198
+ /**
199
+ * The root a restore or a link resolves with is the one served from here on; with the server closing it closes.
200
+ * @private
201
+ */
202
+ _adopt(swapping) {
203
+ const adopted = swapping.then(async (me) => {
204
+ if (this.closing) {
205
+ await me.close()
206
+ throw CeroError.CLOSED('Server')
207
+ }
208
+ this.me = me
209
+ this.handles = new Map([[me.id, me]])
210
+ this._held.clear()
211
+ })
212
+ this._adopting = adopted.catch(() => {})
213
+ return adopted
214
+ }
215
+
162
216
  /**
163
217
  * End every watch stream bound to a handle (e.g. when it closes or leaves).
164
218
  * @private
@@ -172,6 +226,9 @@ export class Server extends RPCServer {
172
226
 
173
227
  /** @private */
174
228
  _onerror(err) {
229
+ // a failed start rejects every request that waits on it, and reaches onerror once
230
+ if (this._reported.has(err)) return
231
+ if (err instanceof Error) this._reported.add(err)
175
232
  if (!this._errors.size) return this._report(err)
176
233
  const frame = {
177
234
  message: err?.message || String(err),
@@ -188,12 +245,14 @@ export class Server extends RPCServer {
188
245
  */
189
246
  _wireInit() {
190
247
  this.rpc.onErrors((stream) => {
248
+ closeWithWire(stream)
191
249
  this._errors.add(stream)
192
250
  stream.on('error', safetyCatch)
193
251
  stream.on('close', () => this._errors.delete(stream))
194
252
  })
195
- this.rpc.onInit(async () => {
196
- await this._booting
253
+ this._on('onInit', async () => {
254
+ await this.ready()
255
+ await (this._booting ?? this._start())
197
256
  // a reloaded UI is a new client on the same worker: it re-attaches, its old streams end, and every open the old
198
257
  // page held is let go for it, as it never closes them
199
258
  for (const handle of this._watchStreams.keys()) this._endWatches(handle)
@@ -207,11 +266,13 @@ export class Server extends RPCServer {
207
266
  * @private
208
267
  */
209
268
  _wireRestore() {
210
- this.rpc.onRestore(async ({ phrase }) => {
211
- if (!this.me) throw CeroError.NOT_READY('Server', 'server')
212
- this.me = await restore(this.me, phrase)
213
- this.handles = new Map([[this.me.id, this.me]])
214
- this._held.clear()
269
+ this._on('onRestore', async ({ phrase }) => {
270
+ await this.ready()
271
+ if (!this._booting) await this._start({ phrase })
272
+ else {
273
+ await this._booting
274
+ await this._adopt(restore(this.me, phrase))
275
+ }
215
276
  return this._identity()
216
277
  })
217
278
  }
@@ -222,14 +283,18 @@ export class Server extends RPCServer {
222
283
  */
223
284
  _wireLink() {
224
285
  this.rpc.onLink((stream) => {
286
+ closeWithWire(stream)
225
287
  stream.on('error', safetyCatch)
226
288
  const run = async () => {
227
- if (!this.me) throw CeroError.NOT_READY('Server', 'server')
228
- this.me = await link(this.me, stream.data.invite, {
229
- onrequest: (id) => stream.write({ request: id })
230
- })
231
- this.handles = new Map([[this.me.id, this.me]])
232
- this._held.clear()
289
+ await this.ready()
290
+ const { invite } = stream.data
291
+ const onrequest = (id) => stream.write({ request: id })
292
+ // as link() waits: the invite's lifetime, a denial ends it
293
+ if (!this._booting) await this._start({ invite, onrequest, recoveryTimeout: 0 })
294
+ else {
295
+ await this._booting
296
+ await this._adopt(link(this.me, invite, { onrequest }))
297
+ }
233
298
  stream.write({ request: '', ...this._identity() })
234
299
  stream.end()
235
300
  }
@@ -246,42 +311,42 @@ export class Server extends RPCServer {
246
311
  * @private
247
312
  */
248
313
  _wireData() {
249
- this.rpc.onAddFile(async ({ handle, data, name, type }) => {
314
+ this._on('onAddFile', async ({ handle, data, name, type }) => {
250
315
  const h = this._resolve(handle)
251
316
  const { data: file } = await put(h.files, { data, type: type || '', name: name || null })
252
317
  const { data: row } = await get(h.files, file.id)
253
318
  return { data: h.spec.codec.encodeRow(h.files.schema, row) }
254
319
  })
255
320
 
256
- this.rpc.onAddRow(async ({ handle, ref, data, local }) => {
321
+ this._on('onAddRow', async ({ handle, ref, data, local }) => {
257
322
  const { ref: r, codec, info } = this._refOf(handle, ref, local)
258
323
  const { data: row } = await put(r, received(codec.decodeRow(r.schema, data), info))
259
324
  return { data: codec.encodeRow(r.schema, row) }
260
325
  })
261
326
 
262
- this.rpc.onSet(async ({ handle, ref, data, fields, local, noUpsert }) => {
327
+ this._on('onSet', async ({ handle, ref, data, fields, local, noUpsert }) => {
263
328
  const { ref: r, codec, info } = this._refOf(handle, ref, local)
264
329
  const row = received(codec.decodeRow(r.schema, data), info, fields)
265
330
  const result = await set(r, row, { upsert: !noUpsert })
266
331
  return { data: result ? codec.encodeRow(r.schema, result.data) : null }
267
332
  })
268
333
 
269
- this.rpc.onGet(async ({ handle, ref, query, local }) => {
334
+ this._on('onGet', async ({ handle, ref, query, local }) => {
270
335
  const { ref: r, codec } = this._refOf(handle, ref, local)
271
336
  const q = fromWire(query)
272
337
  return encodeGet(r, codec, q, await get(r, q))
273
338
  })
274
339
 
275
- this.rpc.onDel(async ({ handle, ref, id, local }) => {
340
+ this._on('onDel', async ({ handle, ref, id, local }) => {
276
341
  await del(this._refOf(handle, ref, local).ref, id)
277
342
  return {}
278
343
  })
279
344
 
280
345
  this.rpc.onWatch((stream) => {
281
346
  const { handle, ref, local } = stream.data
282
- const query = fromWire(stream.data.query)
283
- let r, codec, live
347
+ let query, r, codec, live
284
348
  try {
349
+ query = fromWire(stream.data.query)
285
350
  ;({ ref: r, codec } = this._refOf(handle, ref, local))
286
351
  live = watch(r, query)
287
352
  } catch (err) {
@@ -317,6 +382,7 @@ export class Server extends RPCServer {
317
382
  // a watch ending with its handle ends the client's
318
383
  live.once('close', () => stream.destroy())
319
384
  // channel teardown destroys the stream with CHANNEL_CLOSED; 'close' cleans up
385
+ closeWithWire(stream)
320
386
  stream.on('error', safetyCatch)
321
387
  stream.on('close', () => {
322
388
  live.off('data', onData)
@@ -325,7 +391,7 @@ export class Server extends RPCServer {
325
391
  })
326
392
  })
327
393
 
328
- this.rpc.onCall(async ({ handle, op, data }) => {
394
+ this._on('onCall', async ({ handle, op, data }) => {
329
395
  const h = this._resolve(handle)
330
396
  const r = h[op]
331
397
  if (!r) throw CeroError.UNKNOWN('ref', op)
@@ -339,7 +405,7 @@ export class Server extends RPCServer {
339
405
  * @private
340
406
  */
341
407
  _wireHandles() {
342
- this.rpc.onAddHandle(async ({ handle, ref, data }) => {
408
+ this._on('onAddHandle', async ({ handle, ref, data }) => {
343
409
  const parent = this._resolve(handle)
344
410
  const info = parent.spec.meta.refs?.[ref] || parent.spec.handles?.[ref]
345
411
  if (!info) throw CeroError.UNKNOWN('handle type', ref)
@@ -351,16 +417,16 @@ export class Server extends RPCServer {
351
417
  return { id, type: ref, name: opts.name || '' }
352
418
  })
353
419
 
354
- this.rpc.onOpenHandle(async ({ parent, row, type }) => {
420
+ this._on('onOpenHandle', async ({ parent, row, type }) => {
355
421
  if (this._resolve(parent) !== this.me) throw CeroError.UNSUPPORTED('nested handles')
356
422
  const { data } = await this.me.store.get('handles', row)
357
- if (!data) throw CeroError.UNKNOWN('handle', row)
423
+ if (!data?.encryptionKey) throw CeroError.UNKNOWN('handle', row)
358
424
  const child = await this.me._load(type, row)
359
425
  this._hold(row, child)
360
426
  return { id: row, type: data.type, name: data.name || '' }
361
427
  })
362
428
 
363
- this.rpc.onJoin(async ({ parent, ref, invite }) => {
429
+ this._on('onJoin', async ({ parent, ref, invite }) => {
364
430
  if (this._resolve(parent) !== this.me) throw CeroError.UNSUPPORTED('nested handles')
365
431
  let child
366
432
  try {
@@ -374,14 +440,14 @@ export class Server extends RPCServer {
374
440
  return { id, type: ref, name: '' }
375
441
  })
376
442
 
377
- this.rpc.onCloseHandle(async ({ handle }) => {
443
+ this._on('onCloseHandle', async ({ handle }) => {
378
444
  const h = this.handles.get(handle)
379
445
  if (!h || h === this.me) return {}
380
446
  await this._release(handle, h)
381
447
  return {}
382
448
  })
383
449
 
384
- this.rpc.onLeave(async ({ handle }) => {
450
+ this._on('onLeave', async ({ handle }) => {
385
451
  await leave(this._resolve(handle))
386
452
  this._held.delete(handle)
387
453
  this._endWatches(handle)
@@ -402,7 +468,7 @@ export class Server extends RPCServer {
402
468
  if (n > 0) this._held.set(id, n)
403
469
  else this._held.delete(id)
404
470
  await h.close()
405
- // another holder on this device keeps it, with its watches; a reopen while it lingers registers it again
471
+ // another holder on this device keeps it, with its watches; a reopen while it is idle registers it again
406
472
  if (h._refs > 0) return
407
473
  this._endWatches(id)
408
474
  this.handles.delete(id)
@@ -422,17 +488,27 @@ export class Server extends RPCServer {
422
488
  * @private
423
489
  */
424
490
  _wireVerbs() {
425
- this.rpc.onVerb(async ({ handle, verb, args }) => {
491
+ this._on('onVerb', async ({ handle, verb, args }) => {
426
492
  const run = VERBS.get(verb)
427
493
  if (!run) throw CeroError.UNKNOWN('verb', verb)
428
- let data
494
+ const data = await run(this._resolve(handle), ...c.decode(c.any, args))
495
+ return { data: data === undefined ? null : c.encode(c.any, data) }
496
+ })
497
+ }
498
+
499
+ /**
500
+ * Register a request handler whose error fails only its call.
501
+ * @private
502
+ */
503
+ _on(name, fn) {
504
+ this.rpc[name](async (req) => {
429
505
  try {
430
- data = await run(this._resolve(handle), ...c.decode(c.any, args))
506
+ return await fn(req)
431
507
  } catch (err) {
432
- // bare-rpc rethrows a TypeError and ends the worker: a bad argument fails only the call
433
- throw Object.assign(new Error(err.message), { code: err.code })
508
+ if (!CeroError.isCeroError(err)) this._onerror(err)
509
+ // bare-rpc rethrows a TypeError or a RangeError and ends the worker
510
+ throw Object.assign(new Error(err.message), { code: err.code, reason: err.reason })
434
511
  }
435
- return { data: data === undefined ? null : c.encode(c.any, data) }
436
512
  })
437
513
  }
438
514
 
@@ -467,9 +543,9 @@ export class Server extends RPCServer {
467
543
  return { ref: this.me.local[name], codec: this.spec.local.codec, info }
468
544
  }
469
545
  const h = this._resolve(id)
470
- const r = h[name]
471
- if (!r) throw CeroError.UNKNOWN('ref', name)
472
- return { ref: r, codec: h.spec.codec, info: h.spec.meta?.refs?.[name] }
546
+ const info = h.spec.meta.refs?.[name]
547
+ if (!info) throw CeroError.UNKNOWN('ref', name)
548
+ return { ref: h[name], codec: h.spec.codec, info }
473
549
  }
474
550
 
475
551
  /**
@@ -504,6 +580,11 @@ export async function serve(ipc, spec, opts) {
504
580
  return server
505
581
  }
506
582
 
583
+ // hrpc destroys only the wire's stream when the client drops it, never the one a handler holds
584
+ function closeWithWire(stream) {
585
+ stream.writeStream.once('close', () => stream.destroy())
586
+ }
587
+
507
588
  // a query crosses as the client wrote it; no bytes is no query
508
589
  function fromWire(buf) {
509
590
  return buf ? c.decode(c.any, buf) : undefined