@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.
package/src/index.js CHANGED
@@ -23,8 +23,8 @@ import * as verbs from './lib/operators.js'
23
23
  import { peek } from './lib/peek.js'
24
24
  import { address } from './lib/mail.js'
25
25
  import { t, schema } from './lib/spec.js'
26
- import { FLUSH, TIMEOUT } from './lib/constants.js'
27
- import { commit, nextOf, settle, staging } from './lib/swap.js'
26
+ import { TIMEOUT } from './lib/constants.js'
27
+ import { commit, flush, lock, nextOf, settle, staging, sweep } from './lib/swap.js'
28
28
 
29
29
  export { Handle, Ref, Local }
30
30
  export * from './lib/operators.js'
@@ -52,7 +52,7 @@ export { t, schema } from './lib/spec.js'
52
52
  * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys. Handles and files are mirrored through them so peers sync even when never online at the same time. Mirrors hold only encrypted blocks — they never read your data.
53
53
  * @property {{ active?: number, announced?: number, idle?: number }} [presence] How many handles search, how many only announce, and the idle ms before the rest leave the swarm.
54
54
  * @property {(err: Error) => void} [onerror] Where background errors go; the console without one.
55
- * @property {number} [linger] Ms a handle stays open after its last close, for a quick reopen; 0 closes at once. Defaults to 20000.
55
+ * @property {number} [keepOpen] How many handles stay open after their last close, for a reopen; one more closes the least recently used, 0 closes at once. Defaults to 16.
56
56
  * @property {number} [recoveryTimeout] Max wait to find another device and be admitted, in ms. Defaults to 30000.
57
57
  * @property {Uint8Array} [storageKey] 32-byte key encrypting local key material (master seed, device keypairs) at rest. Source it from the OS keychain — cero never stores it.
58
58
  * @property {import('./extensions/index.js').Extension[]} [extensions] The extensions this instance runs, instead of the ones the spec carries. Build with the same list.
@@ -74,9 +74,12 @@ async function start(dir, spec, opts = {}) {
74
74
  if (typeof bt !== 'object') {
75
75
  throw CeroError.INVALID('bluetooth takes { on, topic, pipe, maxOutbound, maxInbound }')
76
76
  }
77
+ // refused before anything is stored
78
+ if (opts.phrase) Identity.toSeed(opts.phrase)
77
79
 
78
- await settle(dir)
79
- const storage = new HypercoreStorage(`${dir}/main`)
80
+ // a swap hands on the lock it holds
81
+ const held = opts.lock ?? (await lock(dir, opts.recoveryTimeout ?? TIMEOUT))
82
+ let storage = null
80
83
  let store = null
81
84
  let local = null
82
85
  let network = null
@@ -88,7 +91,11 @@ async function start(dir, spec, opts = {}) {
88
91
  opts = { ...opts, onerror }
89
92
  // any failure during open must close what opened, or the storage lock leaks
90
93
  try {
94
+ await settle(dir)
95
+ storage = new HypercoreStorage(`${dir}/main`)
91
96
  await storage.ready()
97
+ await sweep(dir)
98
+ await held.close()
92
99
  await fs.promises.chmod(`${dir}/main`, 0o700)
93
100
  store = new Corestore(storage, { manifestVersion: 2 })
94
101
  await store.ready()
@@ -108,7 +115,9 @@ async function start(dir, spec, opts = {}) {
108
115
  throw CeroError.INVALID('dir holds an identity: a device invite needs a fresh one')
109
116
  }
110
117
  // a device invite, this launch's or the one a killed launch was waiting on
111
- const pending = done || opts.phrase ? null : await pendingLink(local)
118
+ const left = await pendingLink(local)
119
+ if (done && left) await local.store.del('joins', left.id)
120
+ const pending = done || opts.phrase ? null : left
112
121
  const linking = !done && !opts.phrase && !!(opts.invite || pending)
113
122
  const resolved = linking ? null : await resolveIdentity(opts, local, done)
114
123
  // cero creates only an identity it minted, in this launch or in the killed one it resumes
@@ -154,25 +163,18 @@ async function start(dir, spec, opts = {}) {
154
163
  ? await ask(local, network, spec, { ...opts, writer: keyPair, timeout }, pending)
155
164
  : null
156
165
  const identity = linked ? linked.identity : resolved.identity
157
- const fresh = resolved?.fresh === true
158
166
  // the radio before the pointer read: a phrase recovers from a device in range, no internet
159
167
  bluetooth = new Bluetooth(network, { ...bt, identity, keyPair })
160
168
  await bluetooth.ready()
161
169
  discovery = network.join(identity.topic)
162
- // a fresh identity has no peers yet, flushing the announce would only delay onboarding
163
- if (!fresh) await Promise.race([discovery.flush(), new Promise((r) => setTimeout(r, FLUSH))])
164
170
 
165
171
  // the pointer core: identity-signed, written once by the creating device, holds the root key
166
- const manifest = pointerManifest(store, identity)
167
- const pointer = store.get(
168
- creating
169
- ? { keyPair: await Identity.keyPair(identity.seed), manifest }
170
- : { key: Hypercore.key(manifest) }
171
- )
172
+ const pointer = store.get({ manifest: pointerManifest(store, identity) })
172
173
  await pointer.ready()
173
174
  network.attach(pointer)
174
175
 
175
- // a swap replaced while it waits stops reading
176
+ // a swap replaced or closed while it waits stops reading
177
+ if (opts.signal?.aborted) throw CeroError.CLOSED('Swap')
176
178
  opts.signal?.addEventListener('abort', () => pointer.close().catch(safetyCatch))
177
179
  const key = recovering ? await readPointer(pointer, timeout) : linked?.key
178
180
 
@@ -199,6 +201,10 @@ async function start(dir, spec, opts = {}) {
199
201
  timeout
200
202
  }
201
203
  })
204
+ // stopped before it has its seat, it stops waiting: the device that seats it may be gone. Seated, it opens whole
205
+ opts.signal?.addEventListener('abort', () => {
206
+ if (!me.store.writable) me.store.close().catch(safetyCatch)
207
+ })
202
208
  // an extension's hooks see every op the root applies; what else it calls waits for the open
203
209
  const setups = Promise.all(me.extensions.map(async (ext) => ext.setup?.(me)))
204
210
  setups.catch(() => {}) // a failed setup surfaces below, once the root can close
@@ -207,13 +213,14 @@ async function start(dir, spec, opts = {}) {
207
213
 
208
214
  if (!done) {
209
215
  if (creating && pointer.length === 0) {
210
- await pointer.append(c.encode(c.fixed32, me.store.key))
211
- }
212
- if (linked) {
213
- await local.store.set('device', pack(identity))
214
- await local.store.del('joins', linked.id)
216
+ // signed per append: a keypair handed to the store would be kept on disk
217
+ const signer = await Identity.keyPair(identity.seed)
218
+ await pointer.append(c.encode(c.fixed32, me.store.key), { keyPair: signer })
215
219
  }
220
+ if (linked) await local.store.set('device', pack(identity))
221
+ // the join row goes last: until the setup clears, a killed launch resumes the link from it
216
222
  await local.store.set('keypair', { setup: null })
223
+ if (linked) await local.store.del('joins', linked.id)
217
224
  }
218
225
 
219
226
  for (const off of await setups) {
@@ -231,14 +238,17 @@ async function start(dir, spec, opts = {}) {
231
238
  await network?.close().catch(safetyCatch)
232
239
  await local?.close().catch(safetyCatch)
233
240
  await store?.close().catch(safetyCatch)
234
- await storage.close().catch(safetyCatch)
241
+ await storage?.close().catch(safetyCatch)
235
242
  }
243
+ await held.close().catch(safetyCatch)
236
244
  throw err
237
245
  }
238
246
  }
239
247
 
240
248
  /**
241
- * Restore a cero instance from a recovery phrase.
249
+ * Switch this device to the identity of a recovery phrase. That identity opens beside `me` and
250
+ * recovers from a device of it; once it has opened, `me` closes and its data is deleted. A failure
251
+ * leaves `me` as it was, and the phrase of `me`'s own identity resolves `me`.
242
252
  *
243
253
  * @param {Context} me The root to restore.
244
254
  * @param {string} phrase The identity's BIP-39 phrase, as `cero.phrase(me)` gives it.
@@ -254,8 +264,9 @@ export async function restore(me, phrase) {
254
264
  }
255
265
 
256
266
  /**
257
- * Link this device to the identity behind a device invite: closes `me`, deletes `dir/main` and
258
- * opens the directory with `invite`, as a new device of that identity, with no phrase on it.
267
+ * Link this device to the identity behind a device invite, as a new device of it with no phrase on
268
+ * it. It opens beside `me`; once accepted, `me` closes and its data is deleted. A denial or a failure
269
+ * leaves `me` as it was.
259
270
  *
260
271
  * @param {Context} me The root to replace.
261
272
  * @param {string} invite A device invite, as `cero.invite(me)` gives it on a device of that identity.
@@ -272,17 +283,26 @@ export async function link(me, invite, { onrequest } = {}) {
272
283
  }
273
284
 
274
285
  // Another identity comes in beside this one: `me` stays open and untouched until the new one has opened, so a
275
- // failed, denied or replaced restore or link leaves the device as it was. A newer swap replaces one still waiting
286
+ // failed, denied or replaced restore or link leaves the device as it was. A newer swap replaces one still waiting,
287
+ // and a close of `me` stops it until it commits
276
288
  async function swap(me, opts) {
277
- await me._swap?.abort()
289
+ // several may wait on the same one: each stops whichever runs by its turn, so one runs at a time
290
+ while (me._swap) await me._swap.abort()
278
291
  if (me.closing || me.closed) throw CeroError.CLOSED('Handle')
279
292
  // everything carries over except the identity, the channel above all
280
293
  const { _dir: dir, spec, _opts: was } = me
281
- const carried = { ...was, phrase: undefined, invite: undefined, onrequest: undefined }
294
+ const carried = {
295
+ ...was,
296
+ phrase: undefined,
297
+ invite: undefined,
298
+ onrequest: undefined,
299
+ lock: undefined
300
+ }
301
+ let held = null
282
302
  const ac = new AbortController()
283
303
  let finished = () => {}
284
304
  const done = new Promise((resolve) => (finished = resolve))
285
- const running = { abort: () => (ac.abort(), done) }
305
+ const running = { done, committing: false, abort: () => (ac.abort(), done) }
286
306
  me._swap = running
287
307
  try {
288
308
  // one radio: the incoming identity takes it while it opens, and gives it back if it does not
@@ -291,19 +311,25 @@ async function swap(me, opts) {
291
311
  let opened = null
292
312
  try {
293
313
  opened = await start(nextOf(dir), spec, { ...carried, ...opts, signal: ac.signal })
294
- if (ac.signal.aborted) throw CeroError.CLOSED('Swap')
295
314
  await opened.close()
315
+ await flush(dir)
316
+ // from before this identity closes until the new one is open in its place, no launch opens the dir
317
+ held = await lock(dir, carried.recoveryTimeout ?? TIMEOUT)
318
+ // checked and marked in one step: a close of `me` stopped it by now, or waits for it from here
319
+ if (ac.signal.aborted) throw CeroError.CLOSED('Swap')
320
+ running.committing = true
296
321
  } catch (err) {
297
322
  await opened?.close().catch(safetyCatch)
298
323
  await me._bluetooth?.resume().catch(safetyCatch)
299
324
  throw ac.signal.aborted ? CeroError.CLOSED('Swap') : err
300
325
  }
301
326
  // past here the new identity is whole on disk: a failed rename leaves main.old for the next launch to settle
302
- await me.close()
327
+ await me._end()
303
328
  await commit(dir)
304
329
  })
305
- return await start(dir, spec, carried)
330
+ return await start(dir, spec, { ...carried, lock: held })
306
331
  } finally {
332
+ await held?.close().catch(safetyCatch)
307
333
  if (me._swap === running) me._swap = null
308
334
  finished()
309
335
  }
@@ -330,15 +356,18 @@ async function resolveIdentity(opts, local, done) {
330
356
  const provided = opts.phrase ? Identity.toSeed(opts.phrase) : null
331
357
  const seed = (await local.store.get('master')).data?.seed ?? null
332
358
  const row = (await local.store.get('device')).data
333
- if (seed && !row) throw CeroError.INVALID('this storage predates device keys: recreate it')
359
+ if (done && seed && !row) {
360
+ throw CeroError.INVALID('this storage predates device keys: recreate it')
361
+ }
334
362
  const same =
335
363
  row && provided ? b4a.equals((await Identity.keyPair(provided)).publicKey, row.identity) : true
336
364
  // another identity comes in only through restore, which wipes this one first
337
365
  if (done && !same) throw CeroError.INVALID('dir holds another identity: switch with cero.restore')
338
366
  // a phrase given to an unfinished setup takes over from the identity it minted
339
367
  if (row && same) return { identity: unpack(row, seed), fresh: false, minted: false }
340
- const identity = await Identity.create({ seed: provided, words: opts.words })
341
- return { identity, fresh: !provided, minted: true }
368
+ // a launch killed before its device row goes on from the seed it stored
369
+ const identity = await Identity.create({ seed: provided ?? seed, words: opts.words })
370
+ return { identity, fresh: !provided && !seed, minted: true }
342
371
  }
343
372
 
344
373
  // the root's own join in the joins rows
@@ -394,6 +423,10 @@ async function ask(local, network, spec, { invite, writer, onrequest, timeout, s
394
423
  keep,
395
424
  signal
396
425
  })
426
+ } catch (err) {
427
+ // an expired invite leaves no join a later launch could resume
428
+ if (err.code === 'EXPIRED') await local.store.del('joins', row.id)
429
+ throw err
397
430
  } finally {
398
431
  await mailbox.close()
399
432
  }
@@ -4,10 +4,10 @@ export const EPOCHS = 'epochs'
4
4
  export const REMOVALS = 'removals'
5
5
  export const REFUSALS = 'refusals'
6
6
  export const SPENT = 'spent'
7
+ export const ASKS = 'owed'
7
8
 
8
- // Writer-admission / pairing timeout (ms), and the initial discovery-flush wait (ms).
9
+ // Writer-admission / pairing timeout (ms).
9
10
  export const TIMEOUT = 30000
10
- export const FLUSH = 500
11
11
 
12
- // How long a handle its last holder closed stays open for a quick reopen (ms).
13
- export const LINGER = 20000
12
+ // How many handles nobody holds stay open for a reopen.
13
+ export const KEEP_OPEN = 16
@@ -1,7 +1,7 @@
1
1
  import { Readable } from 'streamx'
2
2
 
3
- import { encodeId, decodeId } from '@cero-base/core/blobs/codec'
4
- import { onAbort, subscribe } from '@cero-base/core/utils'
3
+ import { encodeId, decodeId, checkType } from '@cero-base/core/blobs/codec'
4
+ import { onAbort, subscribe, isOptions } from '@cero-base/core/utils'
5
5
  import { CeroError } from '@cero-base/core/errors'
6
6
 
7
7
  /**
@@ -48,6 +48,7 @@ async function putFile(ref, row) {
48
48
  const handle = ref.handle
49
49
  if (handle.rpc) return handle.put('files', row)
50
50
  const { data, type, name = null, from = null } = row
51
+ checkType(type)
51
52
  const blobs = handle.blobs // captured once — the instance carries its epoch stamp
52
53
  await blobs.ready()
53
54
  const blobId = await blobs.put(data)
@@ -78,7 +79,16 @@ export async function set(ref, row, opts) {
78
79
  */
79
80
  export async function del(ref, id) {
80
81
  if (ref.handle.opened === false) await ref.handle.ready()
81
- return ref.handle.store.del(ref.name, id)
82
+ if (ref.kind === 'handle') {
83
+ const store = parentStore(ref)
84
+ const { data: row } = await store.get('handles', id)
85
+ // a room still in use keeps its key there: `cero.leave` ends it
86
+ if (row && !ENDED.has(row.state || 'in')) throw CeroError.REFUSED('state')
87
+ return store.del('handles', id)
88
+ }
89
+ await ref.handle.store.del(ref.name, id)
90
+ // a device removed is cut from every room open here, with its new key, before this resolves
91
+ if (ref.name === 'devices' && ref.handle.children) await ref.handle._pruneAll()
82
92
  }
83
93
 
84
94
  /**
@@ -94,6 +104,7 @@ export async function call(ref, d) {
94
104
  }
95
105
 
96
106
  const WRITES = { single: ['set', 'del'], collection: ['put', 'set', 'del'] }
107
+ const ENDED = new Set(['left', 'removed', 'denied', 'expired', 'cancelled'])
97
108
 
98
109
  /**
99
110
  * Rule that runs before a write to `ref` lands, or before an action does: at apply, on every
@@ -164,6 +175,9 @@ const parentStore = (ref) => (ref.handle.root ? ref.handle.root.store : ref.hand
164
175
  const ofType = (ref, q) => (typeof q === 'string' ? q : { ...q, type: ref.name })
165
176
  const typed = (row, name) => ({ data: row?.type === name ? row : null })
166
177
 
178
+ // a list of handles is the ones the identity is in, unless it names a state
179
+ const standing = (q) => (typeof q === 'string' || q?.state ? q : { ...q, state: 'in' })
180
+
167
181
  function resolveResult(ref, res) {
168
182
  if (res == null || res.data == null) return res
169
183
  const data = Array.isArray(res.data)
@@ -206,11 +220,33 @@ export async function get(ref, q) {
206
220
  const live = ref.handle._live?.[ref.name]
207
221
  if (live) return live.get(q)
208
222
  if (ref.kind === 'handle') {
209
- const res = await parentStore(ref).get('handles', ofType(ref, q))
223
+ const res = await parentStore(ref).get('handles', ofType(ref, standing(q)))
210
224
  return typeof q === 'string' ? typed(res.data, ref.name) : res
211
225
  }
212
- const res = await ref.handle.store.get(ref.name, q)
213
- return resolveResult(ref, res)
226
+ if (ref.name === 'handles') q = standing(q)
227
+ return resolveResult(ref, await ref.handle.store.get(ref.name, q))
228
+ }
229
+
230
+ /**
231
+ * Whether a handle has turned on a collection, a single or an action, or a field of one with
232
+ * `field`. What a release holds back with `t.later` turns on once the handle's `status.version`
233
+ * reaches the release that brought it; until then a write naming it fails with `UNSUPPORTED`.
234
+ *
235
+ * @param {Ref} ref A ref of the root or of an open handle (`room.notes`).
236
+ * @param {string} [field]
237
+ * @returns {Promise<boolean>}
238
+ */
239
+ export async function supports(ref, field) {
240
+ const status = !ref.type && ref.handle.status
241
+ if (!status) throw CeroError.INVALID('supports takes the ref of the root or of an open handle')
242
+ const { meta } = ref.handle.spec
243
+ const info = meta.refs[ref.name]
244
+ const fields = meta.since?.types[info.schema] ?? {}
245
+ if (field !== undefined && !(field in fields)) {
246
+ throw CeroError.UNKNOWN('field', `${ref.name}.${field}`)
247
+ }
248
+ const { data } = await get(status)
249
+ return Math.max(info.since ?? 0, fields[field] ?? 0) <= data.version
214
250
  }
215
251
 
216
252
  // a watch stream dies with its handle, or with the signal
@@ -250,8 +286,9 @@ function source(ref, q) {
250
286
  }
251
287
  if (ref.kind === 'handle') {
252
288
  const map = typeof q === 'string' ? (snap) => typed(snap?.data, ref.name) : (res) => res
253
- return { src: parentStore(ref).watch('handles', ofType(ref, q)), map }
289
+ return { src: parentStore(ref).watch('handles', ofType(ref, standing(q))), map }
254
290
  }
291
+ if (ref.name === 'handles') q = standing(q)
255
292
  return { src: ref.handle.store.watch(ref.name, q), map: (res) => resolveResult(ref, res) }
256
293
  }
257
294
 
@@ -352,7 +389,9 @@ const OPENS = new Set(['invite', 'id', 'name'])
352
389
  * @param {import('@cero-base/core/pairing').InviteOpts} [opts]
353
390
  * @returns {Promise<string>}
354
391
  */
355
- export function invite(ctx, opts) {
392
+ export async function invite(ctx, opts = {}) {
393
+ // checked before anything crosses to the worker, which would carry an ArrayBuffer or a Map as {}
394
+ if (!isOptions(opts)) throw CeroError.INVALID('invite options are an object')
356
395
  return ctx._invite(opts)
357
396
  }
358
397
 
@@ -360,7 +399,7 @@ export function invite(ctx, opts) {
360
399
  * Kill an invite, for every member.
361
400
  *
362
401
  * @param {Context} ctx
363
- * @param {string} code
402
+ * @param {string} code The code `invite` returned, or the id its `invites` row holds.
364
403
  * @returns {Promise<boolean>} Whether it was live.
365
404
  */
366
405
  export function revoke(ctx, code) {
@@ -368,9 +407,9 @@ export function revoke(ctx, code) {
368
407
  }
369
408
 
370
409
  /**
371
- * Re-key a handle now: a new epoch sealed to its members, so one removed before it reads nothing
372
- * written after. Needs the remove permission. A removal also re-keys on its own shortly after it
373
- * lands; this is the one to await.
410
+ * Rotate a handle's key now: a new epoch sealed to its members, so one removed before it reads
411
+ * nothing written after. Needs the remove permission. A removal by an admin or the owner rotates
412
+ * it as it resolves; this is for any other time.
374
413
  *
375
414
  * @param {Context} ctx
376
415
  * @returns {Promise<{ epoch: number }>}
@@ -431,7 +470,7 @@ export function removed(ctx, id) {
431
470
  }
432
471
 
433
472
  /**
434
- * Quit a handle for good: it leaves your list and closes on this device.
473
+ * Quit a handle for good: its row reads `leaving`, then `left` once the handle holds it, and it closes.
435
474
  *
436
475
  * @param {Context} ctx
437
476
  * @returns {Promise<void>}
@@ -519,7 +558,7 @@ export async function receive(me, payload) {
519
558
  /**
520
559
  * Send a value to an address, signed by this identity. Resolves once the outbox keeps it; it is
521
560
  * delivered in the background, from a mirror too when the owner is offline. `keep: false` erases
522
- * this device's copy once someone read it.
561
+ * this device's copy once a device or a mirror stored it.
523
562
  *
524
563
  * @param {Context} me
525
564
  * @param {string} address As `cero.address(secret)` gives it.
package/src/lib/peek.js CHANGED
@@ -5,36 +5,42 @@ import safetyCatch from 'safety-catch'
5
5
  import { CeroError } from '@cero-base/core/errors'
6
6
 
7
7
  import { Local } from '../local/index.js'
8
- import { current } from './swap.js'
8
+ import { current, lock } from './swap.js'
9
9
 
10
10
  // outside operators.js so storage deps stay off the client's module graph
11
11
 
12
+ const WAITING = { recover: 'recovering', link: 'linking' }
13
+
12
14
  /**
13
- * Quickly check whether the on-disk directory at `dir` already holds an initialised cero
14
- * identity (i.e. a stored device key with its proof).
15
+ * What the directory at `dir` holds, read without opening it: nothing yet, an identity, or a recovery or a link
16
+ * still waiting for a device of its identity, which the next `cero(dir, spec)` goes on with.
15
17
  *
16
18
  * @param {string} dir Cero data directory.
17
19
  * @param {import('./spec.js').Spec} spec Built spec, the value passed to `cero(dir, spec)`.
18
- * @returns {Promise<boolean>} `true` if a device of an identity exists on disk.
20
+ * @param {{ storageKey?: Uint8Array }} [opts] The key `cero()` encrypts the local store with, if any.
21
+ * @returns {Promise<'ready' | 'recovering' | 'linking' | null>} `null` when it holds nothing.
19
22
  */
20
- export async function peek(dir, spec) {
23
+ export async function peek(dir, spec, { storageKey } = {}) {
21
24
  if (typeof dir !== 'string' || !dir) throw CeroError.INVALID('dir must be a non-empty string')
22
25
  if (!spec) throw CeroError.REQUIRED('spec')
23
26
 
27
+ const held = await lock(dir)
24
28
  // construct first, ready inside the try: a corrupt dir must still close everything
25
29
  // a swap killed between its renames: the store a launch will open, never a new empty one
26
30
  const root = new HypercoreStorage(await current(dir))
27
31
  const store = new Corestore(root, { manifestVersion: 2 })
28
- const local = new Local(null, spec, { store })
32
+ const local = new Local(null, spec, { store, storageKey })
29
33
  try {
30
34
  await root.ready()
31
35
  await store.ready()
32
36
  await local.ready()
33
- const { data } = await local.store.get('device')
34
- return !!data
37
+ const setup = (await local.store.get('keypair')).data?.setup
38
+ if (WAITING[setup]) return WAITING[setup]
39
+ return (await local.store.get('device')).data ? 'ready' : null
35
40
  } finally {
36
41
  await local.close().catch(safetyCatch)
37
42
  await store.close().catch(safetyCatch)
38
43
  await root.close().catch(safetyCatch)
44
+ await held.close()
39
45
  }
40
46
  }
@@ -0,0 +1,61 @@
1
+ // what a handle, the local store and the UI's client carry on Bare or Node: no schema ref takes one of these names
2
+ export const reserved = [
3
+ 'addListener',
4
+ 'addOnceListener',
5
+ 'blobs',
6
+ 'call',
7
+ 'children',
8
+ 'close',
9
+ 'closed',
10
+ 'closing',
11
+ 'constructor',
12
+ 'del',
13
+ 'device',
14
+ 'dir',
15
+ 'emit',
16
+ 'eventNames',
17
+ 'extensions',
18
+ 'fileServer',
19
+ 'framed',
20
+ 'get',
21
+ 'getMaxListeners',
22
+ 'hasOwnProperty',
23
+ 'id',
24
+ 'identity',
25
+ 'ipc',
26
+ 'isPrototypeOf',
27
+ 'listenerCount',
28
+ 'listeners',
29
+ 'local',
30
+ 'mailbox',
31
+ 'name',
32
+ 'network',
33
+ 'off',
34
+ 'on',
35
+ 'once',
36
+ 'opened',
37
+ 'opening',
38
+ 'own',
39
+ 'parent',
40
+ 'prependListener',
41
+ 'prependOnceListener',
42
+ 'propertyIsEnumerable',
43
+ 'put',
44
+ 'rawListeners',
45
+ 'ready',
46
+ 'removeAllListeners',
47
+ 'removeListener',
48
+ 'root',
49
+ 'rpc',
50
+ 'schemaOf',
51
+ 'set',
52
+ 'setMaxListeners',
53
+ 'signal',
54
+ 'spec',
55
+ 'store',
56
+ 'toLocaleString',
57
+ 'toString',
58
+ 'type',
59
+ 'valueOf',
60
+ 'watch'
61
+ ]
package/src/lib/spec.js CHANGED
@@ -10,17 +10,23 @@ export { t, schema } from '@cero-base/core/schema'
10
10
  * @property {string} [schema]
11
11
  * @property {string} [type] The handle type a `handle` ref opens.
12
12
  * @property {boolean} [internal] A builtin: members, devices, files and the like.
13
- * @property {boolean} [live] Computed on the device, never stored: status, joins, nearby.
13
+ * @property {boolean} [live] Computed on the device, never stored: status, nearby, topics.
14
14
  * @property {string[]} [fields] The declared fields, in schema order.
15
15
  * @property {Record<string, string>} [required] The required fields and their types.
16
16
  * @property {string[]} [files] The fields holding file ids.
17
17
  * @property {string} [verb]
18
18
  * @property {boolean} [push] Whether a write to this ref pushes a notification.
19
+ * @property {number} [since] The contract that brought it, 0 for one the spec had when its history began.
19
20
  *
20
21
  * @typedef {object} SpecMeta
21
22
  * @property {string} [ns]
22
23
  * @property {string} [type] The handle type, on a handle's spec.
23
24
  * @property {number} [version]
25
+ * @property {number} [rules] What a write means to Cero, raised by a release that changes it.
26
+ * @property {number} [start] The contract the spec's history begins at.
27
+ * @property {number} [target] The contract this build asks databases to use.
28
+ * @property {{ routes: Record<string, number>, types: Record<string, Record<string, number>> }} [since] The contract that brought each route, and each field of each stored type, by full name.
29
+ * @property {Record<string, number>} [encoding] The schema version to encode with as of each contract.
24
30
  * @property {Record<string, RefInfo>} refs
25
31
  * @property {{ refs: Record<string, RefInfo> }} [local]
26
32
  * @property {Record<string, SpecMeta>} [handles]
package/src/lib/swap.js CHANGED
@@ -1,10 +1,15 @@
1
1
  import fs from 'fs'
2
+ import FDLock from 'fd-lock'
3
+
4
+ import { CeroError } from '@cero-base/core/errors'
2
5
 
3
6
  // Another identity comes in beside `main`, in `main.next`, and takes its place only once it has opened: the new store
4
7
  // is flushed to disk, then main moves to `main.old` and `main.next/main` to `main`, each rename atomic. A launch reads
5
- // from what is on disk how far a killed swap got
8
+ // from what is on disk how far a killed swap got. The swap and every open of `dir` take turns on `main.lock`
6
9
  const NEXT = 'main.next'
7
10
  const OLD = 'main.old'
11
+ const LOCK = 'main.lock'
12
+ const RETRY = 20
8
13
 
9
14
  // the dirs a swap is running in, in this process: their `main.next` is in use
10
15
  const running = new Set()
@@ -32,8 +37,7 @@ export async function current(dir) {
32
37
 
33
38
  /**
34
39
  * A swap killed part way, finished or undone before anything opens `dir`: past its first rename the incoming
35
- * identity had opened, so it takes main's place; without it the old one comes back. What a killed swap left
36
- * in `main.next` goes, unless a swap is running there.
40
+ * identity had opened, so it takes main's place; without it the old one comes back.
37
41
  *
38
42
  * @param {string} dir
39
43
  */
@@ -44,6 +48,41 @@ export async function settle(dir) {
44
48
  if (!(await exists(main))) await fs.promises.rename(await current(dir), main)
45
49
  await rm(old)
46
50
  }
51
+ }
52
+
53
+ /**
54
+ * The lock on `dir`, a file beside the stores, held from before a store closes or opens until the one in `main` is
55
+ * open: a store's own lock goes with its close and moves with its directory. Another holder is waited for, a try
56
+ * every few ms; a kill frees it.
57
+ *
58
+ * @param {string} dir
59
+ * @param {number} [timeout] The longest wait in ms, 0 for no limit.
60
+ * @returns {Promise<{ close: () => Promise<void> }>} Held until closed.
61
+ */
62
+ export async function lock(dir, timeout = 0) {
63
+ await fs.promises.mkdir(dir, { recursive: true })
64
+ const deadline = timeout ? Date.now() + timeout : Infinity
65
+ while (true) {
66
+ const held = new FDLock(await open(`${dir}/${LOCK}`))
67
+ try {
68
+ await held.ready()
69
+ return held
70
+ } catch (err) {
71
+ // a file that cannot be locked at all carries the system's code, one that is held does not
72
+ if (err.code) throw err
73
+ if (Date.now() >= deadline) throw CeroError.TIMEOUT(`The lock on ${dir}`)
74
+ await new Promise((resolve) => setTimeout(resolve, RETRY))
75
+ }
76
+ }
77
+ }
78
+
79
+ /**
80
+ * What a killed swap left in `main.next` goes, unless a swap is running there. Only once `main` is open: a swap in
81
+ * another process keeps main open while the incoming identity opens.
82
+ *
83
+ * @param {string} dir
84
+ */
85
+ export async function sweep(dir) {
47
86
  if (!running.has(dir)) await rm(nextOf(dir))
48
87
  }
49
88
 
@@ -69,13 +108,22 @@ export async function staging(dir, fn) {
69
108
  }
70
109
 
71
110
  /**
72
- * The identity opened and closed in `main.next` takes main's place. Both must be closed.
111
+ * The identity opened and closed in `main.next`, all of it on disk: a rename that follows never points at data
112
+ * still in a cache.
113
+ *
114
+ * @param {string} dir
115
+ */
116
+ export async function flush(dir) {
117
+ await durable(`${nextOf(dir)}/main`)
118
+ }
119
+
120
+ /**
121
+ * The identity opened, closed and flushed in `main.next` takes main's place. Both must be closed.
73
122
  *
74
123
  * @param {string} dir
75
124
  */
76
125
  export async function commit(dir) {
77
126
  const incoming = `${nextOf(dir)}/main`
78
- await durable(incoming)
79
127
  await fs.promises.rename(`${dir}/main`, `${dir}/${OLD}`)
80
128
  await fs.promises.rename(incoming, `${dir}/main`)
81
129
  await sync(dir, true)
@@ -83,7 +131,6 @@ export async function commit(dir) {
83
131
  await rm(nextOf(dir))
84
132
  }
85
133
 
86
- // every file and directory under `path` on disk, so a rename that follows never points at data still in a cache
87
134
  async function durable(path) {
88
135
  for (const entry of await fs.promises.readdir(path, { withFileTypes: true })) {
89
136
  const at = `${path}/${entry.name}`
@@ -109,6 +156,12 @@ async function sync(path, dir) {
109
156
  }
110
157
  }
111
158
 
159
+ function open(path) {
160
+ return new Promise((resolve, reject) => {
161
+ fs.open(path, 'a', (err, fd) => (err ? reject(err) : resolve(fd)))
162
+ })
163
+ }
164
+
112
165
  function exists(path) {
113
166
  return fs.promises.stat(path).then(
114
167
  () => true,