@johnhenry/browsermesh-apps 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +232 -1
- package/package.json +7 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +859 -0
- package/src/compat.mjs +98 -0
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +34 -2
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1131 -12
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +33 -2
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/serverless-executor-andbox.mjs +136 -0
- package/src/serverless-fetch.mjs +70 -0
- package/src/serverless-functions.mjs +67 -0
- package/src/serverless-peer-select.mjs +69 -0
- package/src/serverless-proxy.mjs +127 -0
- package/src/serverless-router.mjs +115 -0
- package/src/serverless-sites.mjs +116 -0
- package/src/serverless-static.mjs +202 -0
- package/src/serverless-wire.mjs +87 -0
- package/src/peer-session.mjs +0 -937
|
@@ -0,0 +1,859 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* cloud-storage.mjs -- Phase H of the mesh-native-services plan
|
|
3
|
+
* ("CloudStorage: S3-like object storage"): the actual developer-facing
|
|
4
|
+
* class from the plan's Context section --
|
|
5
|
+
*
|
|
6
|
+
* import { CloudStorage as s3 } from '@johnhenry/browsermesh-apps'
|
|
7
|
+
* const store = new s3({ bucket: 'my-bucket', node: peerNode, network })
|
|
8
|
+
* await store.put('key', data)
|
|
9
|
+
*
|
|
10
|
+
* This file composes Phases B/D/E/F/G into one ergonomic entry point so a
|
|
11
|
+
* caller never needs to know `GrantLog`, `key-distribution.mjs`,
|
|
12
|
+
* `manifest-sync.mjs`, or `chunk-replication.mjs` exist:
|
|
13
|
+
*
|
|
14
|
+
* - `CloudStorageBackend` (Phase B) -- the local, durable, encrypted-at-
|
|
15
|
+
* rest single-peer object store this class talks to over its own
|
|
16
|
+
* private JSON-command socket (`fs-service-backend.mjs`'s convention,
|
|
17
|
+
* see that file's module doc comment).
|
|
18
|
+
* - `createKeyDistributionService()` (Phase E) + `createGrantLogService()`
|
|
19
|
+
* (Phase D), attached in that exact order with `onGrantChange`/`onReady`
|
|
20
|
+
* wired between them -- this is `grant-log.mjs`'s own documented
|
|
21
|
+
* composition order (see that file's "Composition with
|
|
22
|
+
* createGrantLogService()" section), reused verbatim here rather than
|
|
23
|
+
* re-derived.
|
|
24
|
+
* - `createManifestSyncService()` (Phase F) -- cross-peer manifest CRDT
|
|
25
|
+
* sync, ACL-gated against the GrantLog's replayed state.
|
|
26
|
+
* - `createChunkReplicationService()` (Phase G) -- eager push-to-replica
|
|
27
|
+
* and lazy pull/read-repair for the actual ciphertext chunk bytes.
|
|
28
|
+
*
|
|
29
|
+
* All four are attached via `attachService()` (`mesh-service.mjs`, Phase C)
|
|
30
|
+
* with NO `network` required -- none of D/E/F/G declare `createBackend`, so
|
|
31
|
+
* `attachService()` never needs one for them (see `mesh-service.mjs`'s own
|
|
32
|
+
* doc comment: `createBackend` is optional per-descriptor, and
|
|
33
|
+
* `attachService()` only throws for a descriptor that both declares it AND
|
|
34
|
+
* is attached with no network).
|
|
35
|
+
*
|
|
36
|
+
* ---------------------------------------------------------------------------
|
|
37
|
+
* DESIGN DECISIONS / GAPS THE PLAN LEFT OPEN, RESOLVED HERE (read before
|
|
38
|
+
* changing this file's behavior):
|
|
39
|
+
*
|
|
40
|
+
* 1. **`network` is OPTIONAL**, and this is a real simplification versus
|
|
41
|
+
* Phase B's original framing, not an oversight. Before this class
|
|
42
|
+
* existed, a caller needed `network.addBackend()` plus a netway
|
|
43
|
+
* `Backend`-shaped socket protocol just to talk to a bucket at all --
|
|
44
|
+
* that machinery is still real and still useful (e.g. another local
|
|
45
|
+
* process, or a debugging tool, connecting via
|
|
46
|
+
* `network.connect('s3-<bucket>://...')` using the raw JSON-command
|
|
47
|
+
* protocol), but `CloudStorage` itself never needs it: it opens its OWN
|
|
48
|
+
* private socket directly against `CloudStorageBackend.connect()`
|
|
49
|
+
* in-process (see `#sendCommand()`) to implement `put`/`get`/`delete`/
|
|
50
|
+
* `list`. `network`, when supplied, is used ONLY to additionally
|
|
51
|
+
* register the backend on it (under `opts.backendScheme`, default
|
|
52
|
+
* `s3-<bucket>`) for that legacy/advanced raw-socket use case -- most
|
|
53
|
+
* callers can omit it entirely.
|
|
54
|
+
*
|
|
55
|
+
* 2. **`get()`'s "not found yet" behavior**: a fully decentralized store has
|
|
56
|
+
* no server to ask "does this key exist" -- a key that was never written
|
|
57
|
+
* ANYWHERE and a key that was written by another peer but whose manifest
|
|
58
|
+
* entry has not yet propagated to THIS peer (Phase F's CRDT sync, an
|
|
59
|
+
* asynchronous background process) are, from this peer's own local
|
|
60
|
+
* vantage point, briefly indistinguishable. Rather than surface a
|
|
61
|
+
* separate "pending" state a caller would have to poll (and rather than
|
|
62
|
+
* hang forever waiting for a sync that might never come, e.g. for a
|
|
63
|
+
* genuinely nonexistent key), `get()` does a bounded wait
|
|
64
|
+
* (`manifestWaitMs`, default `DEFAULT_MANIFEST_WAIT_MS` = 3000ms,
|
|
65
|
+
* overridable per-constructor or per-call) polling the LOCAL manifest
|
|
66
|
+
* snapshot for the key before giving up. If the key never appears in
|
|
67
|
+
* time, `get()` throws `CloudStorageNotFoundError` -- the SAME error
|
|
68
|
+
* class plain absence uses, with `.reason` set to `'not-found'`
|
|
69
|
+
* (never appeared) or `'deleted'` (found, but tombstoned) for callers
|
|
70
|
+
* who want to distinguish further. This mirrors real S3's own external
|
|
71
|
+
* behavior (a 404 either way) while giving ordinary replication lag a
|
|
72
|
+
* real chance to resolve before concluding "not found" -- documented
|
|
73
|
+
* here as a deliberate collapsing of two cases into one bounded wait,
|
|
74
|
+
* not an oversight.
|
|
75
|
+
*
|
|
76
|
+
* 3. **`becomeAdmin()` also self-grants `read`/`write`/`delete`/`list`**,
|
|
77
|
+
* not just the `admin` scope `GrantLog.bootstrapAdmin()` itself grants.
|
|
78
|
+
* This is a real, deliberate gap-fill: `grant-log.mjs` treats "who can
|
|
79
|
+
* grant/revoke" (the `admin` scope, checked by `#assertCanAdminister()`)
|
|
80
|
+
* and "who can actually use this resource" (every other scope) as
|
|
81
|
+
* entirely separate grants by design (see that file's module doc
|
|
82
|
+
* comment) -- bootstrapping admin authority does NOT implicitly grant
|
|
83
|
+
* the bootstrapper read/write access to their own bucket. Since a
|
|
84
|
+
* bucket's creator obviously needs to use the bucket they just created,
|
|
85
|
+
* `becomeAdmin()` performs both steps. Only call this when this instance
|
|
86
|
+
* is genuinely creating a brand-new bucket (see `GrantLog.bootstrapAdmin()`'s
|
|
87
|
+
* own doc comment for what happens if two peers race to create the same
|
|
88
|
+
* bucket id -- the same "earliest write wins" exposure the plan already
|
|
89
|
+
* accepts for `LWWMap` and the GrantLog's own admin-bootstrap record).
|
|
90
|
+
*
|
|
91
|
+
* 4. **`grant()`/`revoke()` also drive manifest visibility and immediate
|
|
92
|
+
* propagation**, not just the GrantLog mutation the plan's brief names
|
|
93
|
+
* literally. Two real family-established facts make this necessary:
|
|
94
|
+
* neither `GrantLog` nor `manifest-sync.mjs`'s `MeshSyncEngine` binding
|
|
95
|
+
* auto-broadcasts on a local mutation (see `grant-log.test.mjs`'s and
|
|
96
|
+
* `manifest-sync.test.mjs`'s own established convention of an explicit
|
|
97
|
+
* `syncWith()`/`watch()` call after every mutation) -- a caller of this
|
|
98
|
+
* ergonomic class should not need to know that. So `grant()`:
|
|
99
|
+
* (a) mutates the local `GrantLog` (`grantLogApi.grant()`),
|
|
100
|
+
* (b) immediately `syncWith(pubKey)`s the FULL current grant log to
|
|
101
|
+
* the newly-granted peer (so they also learn about every
|
|
102
|
+
* PRE-EXISTING grant, including this bucket's admin's own
|
|
103
|
+
* self-grant from step 3 above -- required for the recipient's
|
|
104
|
+
* OWN registry to ever accept the admin's writes/pushes; see
|
|
105
|
+
* `manifest-sync.mjs`'s and `chunk-replication.mjs`'s ACL gates,
|
|
106
|
+
* both of which check the WRITER's grants on the RECEIVING peer's
|
|
107
|
+
* own registry),
|
|
108
|
+
* (c) starts watching the peer for future manifest broadcasts
|
|
109
|
+
* (`manifestSyncApi.watch()`), and
|
|
110
|
+
* (d) immediately syncs the CURRENT manifest snapshot to them too, so
|
|
111
|
+
* pre-existing keys are visible immediately rather than only
|
|
112
|
+
* becoming visible on the NEXT write.
|
|
113
|
+
* `revoke()` mirrors this for the negative case (`unwatch()` after the
|
|
114
|
+
* revoke record propagates) -- though note this is a bandwidth/hygiene
|
|
115
|
+
* cleanup, not itself a security boundary: the actual content-access
|
|
116
|
+
* security boundary is `chunk-replication.mjs`'s own per-request
|
|
117
|
+
* `checkAccess()` gate on `read`/`write`, independent of whether a
|
|
118
|
+
* manifest broadcast is still being sent.
|
|
119
|
+
*
|
|
120
|
+
* 5. **`designateReplica(pubKey)`** is simply `grant(pubKey, 'replica')` --
|
|
121
|
+
* `replica` is not a distinct mechanism in `grant-log.mjs` (see that
|
|
122
|
+
* file's "Replica designation" section: it is implemented as a sixth
|
|
123
|
+
* ordinary action-scope, `s3:<bucket>:replica`, granted/revoked exactly
|
|
124
|
+
* like `read`/`write`/etc.), so this method is a named convenience, not
|
|
125
|
+
* new plumbing.
|
|
126
|
+
*
|
|
127
|
+
* 6. **`replicationFactor` is advisory only, never automatic peer
|
|
128
|
+
* selection.** The plan's own "User decisions... not open for
|
|
129
|
+
* re-litigation" section is explicit: replica peers are admin-designated,
|
|
130
|
+
* never automatically chosen. There is no "pick N replicas from the
|
|
131
|
+
* network" mechanism anywhere in Phases D-G for this class to drive, and
|
|
132
|
+
* inventing one here would contradict that decision. `replicationFactor`
|
|
133
|
+
* is accepted and exposed (`get replicationFactor()`) purely so calling
|
|
134
|
+
* code / tooling can compare it against `replicaPeers.length` itself;
|
|
135
|
+
* this class only logs (via `onLog`) if they don't match, and takes no
|
|
136
|
+
* other action.
|
|
137
|
+
*
|
|
138
|
+
* 7. **What "node" needs to be**: the plan's sketch shows `node: peerNode`,
|
|
139
|
+
* a "booted PeerNode". This class only ever touches `node.podId`,
|
|
140
|
+
* `node.wallet` (duck-typed: `sign()`/`verify()`/`getPublicKeyBytes()`,
|
|
141
|
+
* required transitively by Phases D/E), `node.registry` (`PeerRegistry`,
|
|
142
|
+
* for `checkAccess()`), `node.sendTo()`, and `node.onIncomingData()` --
|
|
143
|
+
* exactly `mesh-service.mjs`'s own `createServiceContext()` needs, and
|
|
144
|
+
* exactly what every Phase C-G unit test's own minimal duck-typed node
|
|
145
|
+
* fixture already provides instead of a full, WebRTC-connected
|
|
146
|
+
* `PeerNode`. A real `PeerNode` (from `createMeshNode()`) satisfies this
|
|
147
|
+
* surface too; this class does not care which.
|
|
148
|
+
*
|
|
149
|
+
* ---------------------------------------------------------------------------
|
|
150
|
+
* KNOWN LIMITATION -- an unauthorized peer's `put()`: because `put()`'s
|
|
151
|
+
* local write can never fail (Phase G's durability contract: the local
|
|
152
|
+
* write is already durable before any replication is attempted), an
|
|
153
|
+
* unauthorized peer's OWN `CloudStorage` instance for the SAME bucket name
|
|
154
|
+
* always resolves `put()` successfully (`{stored: true, durability:
|
|
155
|
+
* 'local-only', replicatedTo: []}`) against its OWN, disconnected local
|
|
156
|
+
* copy -- there is no central arbiter anywhere in this design that could
|
|
157
|
+
* reject it up front. This is architecturally correct, not a bug: that
|
|
158
|
+
* write is never accepted by any OTHER peer's manifest (`manifest-sync.mjs`'s
|
|
159
|
+
* ACL gate rejects it before merge, the same property `manifest-sync.test.mjs`
|
|
160
|
+
* already proves), so it never becomes visible to any authorized reader --
|
|
161
|
+
* "fails cleanly" here means "never corrupts or leaks into the real,
|
|
162
|
+
* shared bucket", not "the promise rejects". `get()`, by contrast, DOES
|
|
163
|
+
* reject cleanly for an unauthorized peer, via the bounded-wait
|
|
164
|
+
* `CloudStorageNotFoundError` above (their local manifest never receives
|
|
165
|
+
* the real writer's entries in the first place, since nobody's
|
|
166
|
+
* `manifest-sync` service ever `watch()`es an unauthorized peer).
|
|
167
|
+
*
|
|
168
|
+
* ---------------------------------------------------------------------------
|
|
169
|
+
* Observability events (`ctx.emit()`/`on()`/`onEvent()`, Phase 1 of the
|
|
170
|
+
* mesh-KV-and-observability plan -- see `mesh-service.mjs`'s module doc
|
|
171
|
+
* comment for the full convention this follows). `CloudStorage` is NOT a
|
|
172
|
+
* `MeshService` descriptor itself -- it calls `attachService()` internally
|
|
173
|
+
* four times (D/E/F/G above) and each of THOSE handles already exposes its
|
|
174
|
+
* own low-level `ctx.emit()` vocabulary (see each service's own module doc
|
|
175
|
+
* comment), but `CloudStorage` has no `ctx` of its OWN to emit through.
|
|
176
|
+
* Rather than leave this class out of the convention, or force a caller to
|
|
177
|
+
* separately subscribe to all four internal handles just to observe "this
|
|
178
|
+
* bucket had a put", this class builds its own bus via `mesh-service.mjs`'s
|
|
179
|
+
* exported `createEventBus()` (the exact same `{emit, on, onEvent, closeAll}`
|
|
180
|
+
* shape `attachService()`'s handle uses) and exposes `on(event, callback)`/
|
|
181
|
+
* `onEvent(callback)` methods matching that same handle shape, so a caller
|
|
182
|
+
* that already knows how to subscribe to one `attachService()` handle knows
|
|
183
|
+
* how to subscribe to a `CloudStorage` instance too. Its own vocabulary is
|
|
184
|
+
* deliberately HIGHER-LEVEL than the internal services' wire-protocol
|
|
185
|
+
* events -- application-meaningful transitions a dashboard actually wants
|
|
186
|
+
* ("this bucket had a write", not "chunk X was pushed to peer Y"):
|
|
187
|
+
*
|
|
188
|
+
* - `cloud-storage:put-completed` `{bucket, key, size, durability}`
|
|
189
|
+
* - `cloud-storage:get-completed` `{bucket, key}`
|
|
190
|
+
* - `cloud-storage:delete-completed` `{bucket, key}`
|
|
191
|
+
* - `cloud-storage:admin-bootstrapped` `{bucket}` -- `becomeAdmin()` finished.
|
|
192
|
+
* - `cloud-storage:grant-issued` `{bucket, pubKey, scopes}` -- `grant()` finished.
|
|
193
|
+
*
|
|
194
|
+
* `close()` calls the bus's own `closeAll()`, stopping further delivery, the
|
|
195
|
+
* same as `attachService()`'s handle does on `teardown()`.
|
|
196
|
+
*
|
|
197
|
+
* No browser-only imports at module level.
|
|
198
|
+
*/
|
|
199
|
+
|
|
200
|
+
import { attachService, createEventBus } from './mesh-service.mjs'
|
|
201
|
+
import { CloudStorageBackend } from './cloud-storage-backend.mjs'
|
|
202
|
+
import { createGrantLogService } from './grant-log.mjs'
|
|
203
|
+
import { createKeyDistributionService } from './key-distribution.mjs'
|
|
204
|
+
import { createManifestSyncService } from './manifest-sync.mjs'
|
|
205
|
+
import { createChunkReplicationService } from './chunk-replication.mjs'
|
|
206
|
+
|
|
207
|
+
/** Default bound (ms) `get()` waits for a key's manifest entry to appear locally before giving up -- see module doc comment, point 2. */
|
|
208
|
+
const DEFAULT_MANIFEST_WAIT_MS = 3000
|
|
209
|
+
|
|
210
|
+
/** How often `get()`'s bounded wait re-polls the local manifest snapshot. */
|
|
211
|
+
const MANIFEST_POLL_INTERVAL_MS = 25
|
|
212
|
+
|
|
213
|
+
/** Bare action-scopes `becomeAdmin()` self-grants beyond the `admin` scope `GrantLog.bootstrapAdmin()` itself grants -- see module doc comment, point 3. */
|
|
214
|
+
const SELF_GRANT_ACTIONS = ['read', 'write', 'delete', 'list']
|
|
215
|
+
|
|
216
|
+
/** @param {string} bucket @returns {string} The scope-grammar resource string GrantLog/PeerRegistry/manifest-sync/chunk-replication all expect. */
|
|
217
|
+
function resourceFor(bucket) {
|
|
218
|
+
return `s3:${bucket}`
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
// Errors
|
|
223
|
+
// ---------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Thrown by `get()` when a key is not found locally after the bounded
|
|
227
|
+
* manifest wait (see module doc comment, point 2). `.reason` is
|
|
228
|
+
* `'not-found'` (the key never appeared) or `'deleted'` (it appeared, but
|
|
229
|
+
* tombstoned).
|
|
230
|
+
*/
|
|
231
|
+
export class CloudStorageNotFoundError extends Error {
|
|
232
|
+
/**
|
|
233
|
+
* @param {string} key
|
|
234
|
+
* @param {object} [opts]
|
|
235
|
+
* @param {'not-found'|'deleted'} [opts.reason='not-found']
|
|
236
|
+
*/
|
|
237
|
+
constructor(key, { reason = 'not-found' } = {}) {
|
|
238
|
+
super(
|
|
239
|
+
reason === 'deleted'
|
|
240
|
+
? `CloudStorage: key '${key}' was deleted`
|
|
241
|
+
: `CloudStorage: key '${key}' not found (it may simply not exist, or its manifest entry has not synced to this peer yet)`,
|
|
242
|
+
)
|
|
243
|
+
this.name = 'CloudStorageNotFoundError'
|
|
244
|
+
this.key = key
|
|
245
|
+
this.reason = reason
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// ---------------------------------------------------------------------------
|
|
250
|
+
// base64 / bytes helpers -- deliberately duplicated rather than shared,
|
|
251
|
+
// matching this family's established per-file convention (see
|
|
252
|
+
// cloud-storage-backend.mjs / key-distribution.mjs / chunk-replication.mjs,
|
|
253
|
+
// all of which independently define the exact same pair).
|
|
254
|
+
// ---------------------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
/** @param {Uint8Array} bytes @returns {string} */
|
|
257
|
+
function toBase64(bytes) {
|
|
258
|
+
if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')
|
|
259
|
+
let bin = ''
|
|
260
|
+
for (const b of bytes) bin += String.fromCharCode(b)
|
|
261
|
+
return btoa(bin)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** @param {string} str @returns {Uint8Array} */
|
|
265
|
+
function fromBase64(str) {
|
|
266
|
+
if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(str, 'base64'))
|
|
267
|
+
const bin = atob(str)
|
|
268
|
+
const bytes = new Uint8Array(bin.length)
|
|
269
|
+
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
|
270
|
+
return bytes
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Normalize `put()`'s `data` argument (a `Uint8Array`, `ArrayBuffer`, or
|
|
275
|
+
* `string`) into bytes.
|
|
276
|
+
* @param {Uint8Array|ArrayBuffer|string} data
|
|
277
|
+
* @returns {Uint8Array}
|
|
278
|
+
*/
|
|
279
|
+
function toUint8Array(data) {
|
|
280
|
+
if (data instanceof Uint8Array) return data
|
|
281
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data)
|
|
282
|
+
if (typeof data === 'string') return new TextEncoder().encode(data)
|
|
283
|
+
throw new TypeError('CloudStorage.put: data must be a Uint8Array, ArrayBuffer, or string')
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// ---------------------------------------------------------------------------
|
|
287
|
+
// CloudStorage
|
|
288
|
+
// ---------------------------------------------------------------------------
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* The ergonomic, S3-like object storage class. See this file's module doc
|
|
292
|
+
* comment for the full design writeup.
|
|
293
|
+
*/
|
|
294
|
+
export class CloudStorage {
|
|
295
|
+
/** @type {string} */
|
|
296
|
+
#bucket
|
|
297
|
+
|
|
298
|
+
/** @type {string} */
|
|
299
|
+
#resource
|
|
300
|
+
|
|
301
|
+
/** @type {object} Duck-typed `{podId, wallet, registry, sendTo, onIncomingData}` -- see module doc comment, point 7. */
|
|
302
|
+
#node
|
|
303
|
+
|
|
304
|
+
/** @type {import('@johnhenry/browsermesh-netway').VirtualNetwork|null} */
|
|
305
|
+
#network
|
|
306
|
+
|
|
307
|
+
/** @type {CloudStorageBackend} */
|
|
308
|
+
#backend
|
|
309
|
+
|
|
310
|
+
/** @type {import('@johnhenry/browsermesh-netway').StreamSocket|null} lazily-opened private local socket to `#backend` */
|
|
311
|
+
#socket = null
|
|
312
|
+
|
|
313
|
+
/** @type {Promise<void>} tail of the local-socket command queue -- see #sendCommand() */
|
|
314
|
+
#socketQueue = Promise.resolve()
|
|
315
|
+
|
|
316
|
+
/** @type {{resource: string, grant: Function, revoke: Function, bootstrapAdmin: Function, syncWith: Function, effective: Function, toJSON: Function}} set synchronously during construction */
|
|
317
|
+
#grantLogApi
|
|
318
|
+
|
|
319
|
+
/** @type {{resource: string, handleGrantChange: Function, localEncryptionPublicKey: Function}} */
|
|
320
|
+
#keyDistApi
|
|
321
|
+
|
|
322
|
+
/** @type {{bucketId: string, docId: string, watch: Function, unwatch: Function, syncWith: Function}} */
|
|
323
|
+
#manifestSyncApi
|
|
324
|
+
|
|
325
|
+
/** @type {{bucketId: string, resource: string, fetchChunk: Function, syncMissingChunks: Function, listReplicaPeers: Function}} */
|
|
326
|
+
#chunkReplicationApi
|
|
327
|
+
|
|
328
|
+
/** @type {Array<{name: string, backendScheme: string|null, api: object|undefined, teardown: () => Promise<void>}>} */
|
|
329
|
+
#handles = []
|
|
330
|
+
|
|
331
|
+
/** @type {string[]} */
|
|
332
|
+
#replicaPeers
|
|
333
|
+
|
|
334
|
+
/** @type {number} */
|
|
335
|
+
#replicationFactor
|
|
336
|
+
|
|
337
|
+
/** @type {number} */
|
|
338
|
+
#manifestWaitMs
|
|
339
|
+
|
|
340
|
+
/** @type {Function} */
|
|
341
|
+
#onLog
|
|
342
|
+
|
|
343
|
+
/** @type {import('./mesh-service.mjs').EventBus} This class's OWN higher-level event bus -- see module doc comment's "Observability events" section. Not the same bus as any of the four internally-attached services' own `ctx.emit()`. */
|
|
344
|
+
#events = createEventBus()
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* @param {object} opts
|
|
348
|
+
* @param {string} opts.bucket - Bucket name. The ACL/sync resource used
|
|
349
|
+
* throughout is `s3:<bucket>`.
|
|
350
|
+
* @param {object} opts.node - A booted `PeerNode` (or any object providing
|
|
351
|
+
* the same minimal surface -- see module doc comment, point 7).
|
|
352
|
+
* @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [opts.network] -
|
|
353
|
+
* Optional -- see module doc comment, point 1. Only used to additionally
|
|
354
|
+
* register the internal `CloudStorageBackend` on it for raw JSON-command
|
|
355
|
+
* socket access.
|
|
356
|
+
* @param {string} [opts.backendScheme] - Scheme `#backend` is registered
|
|
357
|
+
* under on `network`, if supplied. Defaults to `s3-<bucket>`.
|
|
358
|
+
* @param {string[]} [opts.replicaPeers] - PubKeys to designate as replicas
|
|
359
|
+
* immediately when `becomeAdmin()` is called (see module doc comment,
|
|
360
|
+
* point 3). Ignored if `becomeAdmin()` is never called.
|
|
361
|
+
* @param {number} [opts.replicationFactor] - Advisory only -- see module
|
|
362
|
+
* doc comment, point 6.
|
|
363
|
+
* @param {number} [opts.manifestWaitMs] - Default bound for `get()`'s
|
|
364
|
+
* "wait for the manifest to sync" behavior (see module doc comment,
|
|
365
|
+
* point 2). Defaults to `DEFAULT_MANIFEST_WAIT_MS`.
|
|
366
|
+
* @param {Function} [opts.onLog]
|
|
367
|
+
* @param {string} [opts.dbName] - Passed through to `CloudStorageBackend`
|
|
368
|
+
* (its IndexedDB database name prefix). Defaults to `cloud-storage-<bucket>`.
|
|
369
|
+
* @param {import('@johnhenry/browsermesh-sync').IndexedDBChunkStore} [opts.chunkStore]
|
|
370
|
+
* @param {import('@johnhenry/browsermesh-sync').IndexedDBSyncStorage} [opts.manifestStorage]
|
|
371
|
+
* @param {import('@johnhenry/browsermesh-sync').IndexedDBSyncStorage} [opts.keyStorage]
|
|
372
|
+
*/
|
|
373
|
+
constructor({
|
|
374
|
+
bucket,
|
|
375
|
+
node,
|
|
376
|
+
network,
|
|
377
|
+
backendScheme,
|
|
378
|
+
replicaPeers = [],
|
|
379
|
+
replicationFactor,
|
|
380
|
+
manifestWaitMs = DEFAULT_MANIFEST_WAIT_MS,
|
|
381
|
+
onLog,
|
|
382
|
+
dbName,
|
|
383
|
+
chunkStore,
|
|
384
|
+
manifestStorage,
|
|
385
|
+
keyStorage,
|
|
386
|
+
} = {}) {
|
|
387
|
+
if (!bucket || typeof bucket !== 'string') {
|
|
388
|
+
throw new Error('CloudStorage: bucket is required and must be a non-empty string')
|
|
389
|
+
}
|
|
390
|
+
if (!node || typeof node !== 'object') {
|
|
391
|
+
throw new Error('CloudStorage: node is required (a booted PeerNode, or an equivalent duck-typed object)')
|
|
392
|
+
}
|
|
393
|
+
if (!node.podId || typeof node.podId !== 'string') {
|
|
394
|
+
throw new Error('CloudStorage: node.podId is required')
|
|
395
|
+
}
|
|
396
|
+
if (!node.wallet || typeof node.wallet.sign !== 'function') {
|
|
397
|
+
throw new Error('CloudStorage: node.wallet is required (needed by the GrantLog/key-distribution services)')
|
|
398
|
+
}
|
|
399
|
+
if (!node.registry || typeof node.registry.checkAccess !== 'function') {
|
|
400
|
+
throw new Error('CloudStorage: node.registry is required (needed by manifest-sync/chunk-replication for ACL checks)')
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
this.#bucket = bucket
|
|
404
|
+
this.#resource = resourceFor(bucket)
|
|
405
|
+
this.#node = node
|
|
406
|
+
this.#network = network || null
|
|
407
|
+
this.#replicaPeers = Array.isArray(replicaPeers) ? [...replicaPeers] : []
|
|
408
|
+
this.#replicationFactor = typeof replicationFactor === 'number' ? replicationFactor : this.#replicaPeers.length
|
|
409
|
+
this.#manifestWaitMs = manifestWaitMs
|
|
410
|
+
this.#onLog = onLog || (() => {})
|
|
411
|
+
|
|
412
|
+
if (this.#replicationFactor > this.#replicaPeers.length) {
|
|
413
|
+
this.#onLog('cloud-storage:replication-factor-not-met', {
|
|
414
|
+
bucket, replicationFactor: this.#replicationFactor, replicaPeersProvided: this.#replicaPeers.length,
|
|
415
|
+
})
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
this.#backend = new CloudStorageBackend({
|
|
419
|
+
bucket,
|
|
420
|
+
dbName,
|
|
421
|
+
chunkStore,
|
|
422
|
+
manifestStorage,
|
|
423
|
+
keyStorage,
|
|
424
|
+
nodeId: node.podId,
|
|
425
|
+
onLog: this.#onLog,
|
|
426
|
+
})
|
|
427
|
+
|
|
428
|
+
if (this.#network) {
|
|
429
|
+
this.#network.addBackend(backendScheme || `s3-${bucket}`, this.#backend)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// -- Compose D/E/F/G. Order matters for D+E -- see grant-log.mjs's own
|
|
433
|
+
// "Composition with createGrantLogService()" doc-comment section, and
|
|
434
|
+
// key-distribution.test.mjs's `attachBucketServices()` fixture, which
|
|
435
|
+
// this mirrors exactly.
|
|
436
|
+
let grantLogApi
|
|
437
|
+
const keyDistHandle = attachService(node, network, createKeyDistributionService({
|
|
438
|
+
resource: this.#resource,
|
|
439
|
+
getEffective: () => grantLogApi.effective(),
|
|
440
|
+
getLocalKey: () => this.#backend.peekKeyRaw(),
|
|
441
|
+
setReceivedKey: (bytes) => this.#backend.importKeyRaw(bytes),
|
|
442
|
+
onLog: this.#onLog,
|
|
443
|
+
}))
|
|
444
|
+
const grantLogHandle = attachService(node, network, createGrantLogService({
|
|
445
|
+
resource: this.#resource,
|
|
446
|
+
onGrantChange: keyDistHandle.api.handleGrantChange,
|
|
447
|
+
onReady: (api) => { grantLogApi = api },
|
|
448
|
+
onLog: this.#onLog,
|
|
449
|
+
}))
|
|
450
|
+
// `onReady` above runs synchronously inside `attach()` (see
|
|
451
|
+
// grant-log.mjs's own doc comment on why it must), so `grantLogApi` is
|
|
452
|
+
// already assigned by the time `attachService()` returns.
|
|
453
|
+
this.#grantLogApi = grantLogApi
|
|
454
|
+
this.#keyDistApi = keyDistHandle.api
|
|
455
|
+
|
|
456
|
+
const manifestSyncHandle = attachService(node, network, createManifestSyncService({
|
|
457
|
+
bucketId: bucket,
|
|
458
|
+
cloudStorageBackend: this.#backend,
|
|
459
|
+
onLog: this.#onLog,
|
|
460
|
+
}))
|
|
461
|
+
this.#manifestSyncApi = manifestSyncHandle.api
|
|
462
|
+
|
|
463
|
+
const chunkReplicationHandle = attachService(node, network, createChunkReplicationService({
|
|
464
|
+
bucketId: bucket,
|
|
465
|
+
cloudStorageBackend: this.#backend,
|
|
466
|
+
onLog: this.#onLog,
|
|
467
|
+
}))
|
|
468
|
+
this.#chunkReplicationApi = chunkReplicationHandle.api
|
|
469
|
+
|
|
470
|
+
this.#handles = [keyDistHandle, grantLogHandle, manifestSyncHandle, chunkReplicationHandle]
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** The bucket name this instance serves. */
|
|
474
|
+
get bucket() { return this.#bucket }
|
|
475
|
+
|
|
476
|
+
/** The scope-grammar resource string (`s3:<bucket>`) this instance's ACL/sync services check against. */
|
|
477
|
+
get resource() { return this.#resource }
|
|
478
|
+
|
|
479
|
+
/** Advisory only -- see module doc comment, point 6. */
|
|
480
|
+
get replicationFactor() { return this.#replicationFactor }
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Subscribe to exactly one of this instance's own higher-level events
|
|
484
|
+
* (`cloud-storage:*` -- see module doc comment's "Observability events"
|
|
485
|
+
* section). Matches `attachService()`'s returned handle's `on()` shape.
|
|
486
|
+
* @param {string} event
|
|
487
|
+
* @param {(data: object) => void} callback
|
|
488
|
+
* @returns {() => void} Unsubscribe function.
|
|
489
|
+
*/
|
|
490
|
+
on(event, callback) {
|
|
491
|
+
return this.#events.on(event, callback)
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Subscribe to every event this instance emits, regardless of name.
|
|
496
|
+
* Matches `attachService()`'s returned handle's `onEvent()` shape.
|
|
497
|
+
* @param {(event: string, data: object) => void} callback
|
|
498
|
+
* @returns {() => void} Unsubscribe function.
|
|
499
|
+
*/
|
|
500
|
+
onEvent(callback) {
|
|
501
|
+
return this.#events.onEvent(callback)
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// -----------------------------------------------------------------------
|
|
505
|
+
// Local command socket (put/get/delete/list all flow through here)
|
|
506
|
+
// -----------------------------------------------------------------------
|
|
507
|
+
|
|
508
|
+
/** @returns {Promise<import('@johnhenry/browsermesh-netway').StreamSocket>} */
|
|
509
|
+
async #ensureSocket() {
|
|
510
|
+
if (!this.#socket) {
|
|
511
|
+
this.#socket = await this.#backend.connect()
|
|
512
|
+
}
|
|
513
|
+
return this.#socket
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Send one JSON command to `#backend` over its private local socket and
|
|
518
|
+
* return its one JSON response. The wire protocol (`fs-service-backend.mjs`'s
|
|
519
|
+
* convention, reused by `CloudStorageBackend`) has no request-id
|
|
520
|
+
* correlation -- it is strictly one command in flight at a time -- so
|
|
521
|
+
* concurrent callers of this class share one FIFO queue rather than
|
|
522
|
+
* risking interleaved writes/misattributed reads on the same socket.
|
|
523
|
+
* @param {object} cmd
|
|
524
|
+
* @returns {Promise<object>}
|
|
525
|
+
*/
|
|
526
|
+
#sendCommand(cmd) {
|
|
527
|
+
const run = async () => {
|
|
528
|
+
const socket = await this.#ensureSocket()
|
|
529
|
+
const encoder = new TextEncoder()
|
|
530
|
+
const decoder = new TextDecoder()
|
|
531
|
+
await socket.write(encoder.encode(JSON.stringify(cmd)))
|
|
532
|
+
const chunk = await socket.read()
|
|
533
|
+
if (chunk === null) {
|
|
534
|
+
throw new Error('CloudStorage: local backend socket closed unexpectedly')
|
|
535
|
+
}
|
|
536
|
+
return JSON.parse(decoder.decode(chunk))
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const result = this.#socketQueue.then(run, run)
|
|
540
|
+
// Keep the queue itself always-resolved regardless of a given command's
|
|
541
|
+
// outcome -- only `result` (returned below) carries the real
|
|
542
|
+
// success/failure for THIS call.
|
|
543
|
+
this.#socketQueue = result.then(() => {}, () => {})
|
|
544
|
+
return result
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// -----------------------------------------------------------------------
|
|
548
|
+
// Object operations
|
|
549
|
+
// -----------------------------------------------------------------------
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Write `data` under `key`. The local write is always durable by the time
|
|
553
|
+
* this resolves (Phase G's durability contract) -- `durability`/
|
|
554
|
+
* `replicatedTo` report whether it was ALSO pushed to connected,
|
|
555
|
+
* admin-designated replica peers in time, never whether the local write
|
|
556
|
+
* itself succeeded.
|
|
557
|
+
*
|
|
558
|
+
* @param {string} key
|
|
559
|
+
* @param {Uint8Array|ArrayBuffer|string} data
|
|
560
|
+
* @param {object} [opts]
|
|
561
|
+
* @param {string} [opts.contentType]
|
|
562
|
+
* @param {object} [opts.metadata]
|
|
563
|
+
* @returns {Promise<{stored: true, key: string, size: number, durability: 'local-only'|'replicated', replicatedTo: string[]}>}
|
|
564
|
+
*/
|
|
565
|
+
async put(key, data, opts = {}) {
|
|
566
|
+
if (!key || typeof key !== 'string') {
|
|
567
|
+
throw new Error('CloudStorage.put: key is required and must be a non-empty string')
|
|
568
|
+
}
|
|
569
|
+
const bytes = toUint8Array(data)
|
|
570
|
+
const res = await this.#sendCommand({
|
|
571
|
+
op: 'put',
|
|
572
|
+
key,
|
|
573
|
+
data: toBase64(bytes),
|
|
574
|
+
contentType: opts.contentType ?? null,
|
|
575
|
+
metadata: opts.metadata ?? {},
|
|
576
|
+
})
|
|
577
|
+
if (res.error) throw new Error(`CloudStorage.put: ${res.error}`)
|
|
578
|
+
const durability = res.durability === 'replicated' ? 'replicated' : 'local-only'
|
|
579
|
+
this.#events.emit('cloud-storage:put-completed', { bucket: this.#bucket, key: res.key, size: res.size, durability })
|
|
580
|
+
return {
|
|
581
|
+
stored: true,
|
|
582
|
+
key: res.key,
|
|
583
|
+
size: res.size,
|
|
584
|
+
durability,
|
|
585
|
+
replicatedTo: Array.isArray(res.replicatedTo) ? res.replicatedTo : [],
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Wait (up to `waitMs`) for `key`'s manifest entry to be present, per the
|
|
591
|
+
* module doc comment's point 2 ("the manifest entry itself isn't here
|
|
592
|
+
* yet"). Shared by `getObject()` and `stat()` so both honor the same
|
|
593
|
+
* manifest-sync-wait/tombstone contract as each other.
|
|
594
|
+
*
|
|
595
|
+
* @param {string} key
|
|
596
|
+
* @param {number} waitMs
|
|
597
|
+
* @returns {Promise<object>} the manifest registration entry
|
|
598
|
+
* @throws {CloudStorageNotFoundError}
|
|
599
|
+
*/
|
|
600
|
+
async #awaitManifestEntry(key, waitMs) {
|
|
601
|
+
const deadline = Date.now() + waitMs
|
|
602
|
+
|
|
603
|
+
let reg = null
|
|
604
|
+
while (true) {
|
|
605
|
+
const snapshot = await this.#backend.getManifestSnapshot()
|
|
606
|
+
reg = snapshot?.entries?.[key] || null
|
|
607
|
+
if (reg) break
|
|
608
|
+
if (Date.now() >= deadline) break
|
|
609
|
+
await new Promise((r) => setTimeout(r, MANIFEST_POLL_INTERVAL_MS))
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
if (!reg) {
|
|
613
|
+
throw new CloudStorageNotFoundError(key, { reason: 'not-found' })
|
|
614
|
+
}
|
|
615
|
+
if (reg.tombstone) {
|
|
616
|
+
throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
|
|
617
|
+
}
|
|
618
|
+
return reg
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Read `key`'s content plus the `contentType`/`metadata` it was `put()`
|
|
623
|
+
* with. The backend's `get` op already returns these fields
|
|
624
|
+
* (`cloud-storage-backend.mjs`'s `#opGet()`) -- `get()` below is a thin
|
|
625
|
+
* wrapper around this that returns only `data`, for callers that don't
|
|
626
|
+
* need the rest. Falls back to a remote peer request (Phase G's lazy
|
|
627
|
+
* pull/read-repair) for any chunk not already held locally.
|
|
628
|
+
*
|
|
629
|
+
* @param {string} key
|
|
630
|
+
* @param {object} [opts]
|
|
631
|
+
* @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
|
|
632
|
+
* @returns {Promise<{data: Uint8Array, contentType: (string|undefined), metadata: (object|undefined)}>}
|
|
633
|
+
* @throws {CloudStorageNotFoundError}
|
|
634
|
+
*/
|
|
635
|
+
async getObject(key, opts = {}) {
|
|
636
|
+
if (!key || typeof key !== 'string') {
|
|
637
|
+
throw new Error('CloudStorage.getObject: key is required and must be a non-empty string')
|
|
638
|
+
}
|
|
639
|
+
const waitMs = opts.manifestWaitMs ?? this.#manifestWaitMs
|
|
640
|
+
const reg = await this.#awaitManifestEntry(key, waitMs)
|
|
641
|
+
|
|
642
|
+
// Ensure every chunk this entry references is present locally BEFORE
|
|
643
|
+
// asking the backend to decrypt+assemble it -- the backend itself has
|
|
644
|
+
// no notion of "go fetch it from the mesh", only "read what I already
|
|
645
|
+
// have" (see cloud-storage-backend.mjs's #fetchAndDecrypt()).
|
|
646
|
+
for (const { cid } of reg.value?.chunks || []) {
|
|
647
|
+
const has = await this.#backend.hasChunkRaw(cid)
|
|
648
|
+
if (!has) {
|
|
649
|
+
await this.#chunkReplicationApi.fetchChunk(cid) // throws a plain Error if unreachable -- propagated as-is, not wrapped
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
const res = await this.#sendCommand({ op: 'get', key })
|
|
654
|
+
if (res.error) {
|
|
655
|
+
// The manifest could have raced a concurrent delete between the check
|
|
656
|
+
// above and now -- surface it via the same not-found contract rather
|
|
657
|
+
// than a raw backend error string.
|
|
658
|
+
throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
|
|
659
|
+
}
|
|
660
|
+
this.#events.emit('cloud-storage:get-completed', { bucket: this.#bucket, key })
|
|
661
|
+
return { data: fromBase64(res.data), contentType: res.contentType, metadata: res.metadata }
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* Read `key`'s content. See `getObject()` for the `contentType`/`metadata`-
|
|
666
|
+
* preserving variant this delegates to.
|
|
667
|
+
*
|
|
668
|
+
* @param {string} key
|
|
669
|
+
* @param {object} [opts]
|
|
670
|
+
* @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
|
|
671
|
+
* @returns {Promise<Uint8Array>}
|
|
672
|
+
* @throws {CloudStorageNotFoundError}
|
|
673
|
+
*/
|
|
674
|
+
async get(key, opts = {}) {
|
|
675
|
+
const { data } = await this.getObject(key, opts)
|
|
676
|
+
return data
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Return `key`'s metadata (`size`, `contentType`, `metadata`, `updatedAt`,
|
|
681
|
+
* `version`) without reading or decrypting its content. Thin wrapper
|
|
682
|
+
* around the backend's existing `head` op (`cloud-storage-backend.mjs`'s
|
|
683
|
+
* `#opHead()`), which was already implemented but never called from this
|
|
684
|
+
* class.
|
|
685
|
+
*
|
|
686
|
+
* @param {string} key
|
|
687
|
+
* @param {object} [opts]
|
|
688
|
+
* @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
|
|
689
|
+
* @returns {Promise<{size: number, contentType: (string|undefined), metadata: (object|undefined), updatedAt: number, version: number}>}
|
|
690
|
+
* @throws {CloudStorageNotFoundError}
|
|
691
|
+
*/
|
|
692
|
+
async stat(key, opts = {}) {
|
|
693
|
+
if (!key || typeof key !== 'string') {
|
|
694
|
+
throw new Error('CloudStorage.stat: key is required and must be a non-empty string')
|
|
695
|
+
}
|
|
696
|
+
const waitMs = opts.manifestWaitMs ?? this.#manifestWaitMs
|
|
697
|
+
await this.#awaitManifestEntry(key, waitMs)
|
|
698
|
+
|
|
699
|
+
const res = await this.#sendCommand({ op: 'head', key })
|
|
700
|
+
if (res.error) {
|
|
701
|
+
throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
|
|
702
|
+
}
|
|
703
|
+
return { size: res.size, contentType: res.contentType, metadata: res.metadata, updatedAt: res.updatedAt, version: res.version }
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* Delete `key` (a tombstone, per `CloudStorageBackend`'s manifest --
|
|
708
|
+
* never a chunk-store removal; see that file's own doc comment).
|
|
709
|
+
* @param {string} key
|
|
710
|
+
* @returns {Promise<{deleted: true}>}
|
|
711
|
+
*/
|
|
712
|
+
async delete(key) {
|
|
713
|
+
if (!key || typeof key !== 'string') {
|
|
714
|
+
throw new Error('CloudStorage.delete: key is required and must be a non-empty string')
|
|
715
|
+
}
|
|
716
|
+
const res = await this.#sendCommand({ op: 'delete', key })
|
|
717
|
+
if (res.error) throw new Error(`CloudStorage.delete: ${res.error}`)
|
|
718
|
+
this.#events.emit('cloud-storage:delete-completed', { bucket: this.#bucket, key })
|
|
719
|
+
return { deleted: true }
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* List keys, optionally filtered by `prefix`. Reflects this peer's own
|
|
724
|
+
* local manifest state at call time -- eventually consistent with other
|
|
725
|
+
* peers, exactly like real S3 listing, with no special wait (unlike
|
|
726
|
+
* `get()`; see module doc comment, point 2 -- listing has no single key
|
|
727
|
+
* whose absence is ambiguous the way `get()` does).
|
|
728
|
+
* @param {string} [prefix='']
|
|
729
|
+
* @returns {Promise<Array<{key: string, size: number, updatedAt: number}>>}
|
|
730
|
+
*/
|
|
731
|
+
async list(prefix = '') {
|
|
732
|
+
const res = await this.#sendCommand({ op: 'list', prefix })
|
|
733
|
+
if (res.error) throw new Error(`CloudStorage.list: ${res.error}`)
|
|
734
|
+
return res.keys
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
// -----------------------------------------------------------------------
|
|
738
|
+
// Bucket admin
|
|
739
|
+
// -----------------------------------------------------------------------
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* Bootstrap this identity as the bucket's admin, and self-grant
|
|
743
|
+
* `read`/`write`/`delete`/`list` (see module doc comment, point 3). Only
|
|
744
|
+
* call this when THIS instance is genuinely creating a brand-new bucket.
|
|
745
|
+
* If `replicaPeers` was supplied to the constructor, each is designated a
|
|
746
|
+
* replica immediately afterward.
|
|
747
|
+
* @returns {Promise<void>}
|
|
748
|
+
*/
|
|
749
|
+
async becomeAdmin() {
|
|
750
|
+
await this.#grantLogApi.bootstrapAdmin()
|
|
751
|
+
await this.#grantLogApi.grant(this.#node.podId, SELF_GRANT_ACTIONS)
|
|
752
|
+
this.#events.emit('cloud-storage:admin-bootstrapped', { bucket: this.#bucket })
|
|
753
|
+
for (const pubKey of this.#replicaPeers) {
|
|
754
|
+
await this.designateReplica(pubKey)
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* Grant `pubKey` one or more bare capability actions on this bucket
|
|
760
|
+
* (`'read'`, `'write'`, `'delete'`, `'list'`, `'admin'`, `'replica'`).
|
|
761
|
+
* Requires this instance's identity to currently be an authorized admin
|
|
762
|
+
* of this bucket (enforced by `GrantLog.grant()` itself). See module doc
|
|
763
|
+
* comment, point 4, for why this also drives manifest visibility/sync.
|
|
764
|
+
* @param {string} pubKey
|
|
765
|
+
* @param {string|string[]} scopes
|
|
766
|
+
* @returns {Promise<void>}
|
|
767
|
+
*/
|
|
768
|
+
async grant(pubKey, scopes) {
|
|
769
|
+
const list = Array.isArray(scopes) ? scopes : [scopes]
|
|
770
|
+
await this.#grantLogApi.grant(pubKey, list)
|
|
771
|
+
await this.#grantLogApi.syncWith(pubKey)
|
|
772
|
+
this.#manifestSyncApi.watch(pubKey)
|
|
773
|
+
// KNOWN RACE, worked around here rather than ignored: the recipient's
|
|
774
|
+
// GrantLog.mergeRemote() (crypto signature verification, genuinely
|
|
775
|
+
// async) is not awaited by their own grant-log service's dispatch
|
|
776
|
+
// handler (matching `manifest-sync.mjs`'s/`grant-log.mjs`'s own
|
|
777
|
+
// established "handle async work in a .catch()-guarded background
|
|
778
|
+
// promise, never block the dispatch loop" convention) -- so a manifest
|
|
779
|
+
// sync sent immediately after `grantLogApi.syncWith()` can arrive and be
|
|
780
|
+
// ACL-checked on the recipient's side BEFORE their own registry has
|
|
781
|
+
// actually been updated with this grant, and gets silently rejected by
|
|
782
|
+
// manifest-sync.mjs's gate. Without a retry, pre-existing content would
|
|
783
|
+
// then only ever become visible to the recipient on the NEXT write (the
|
|
784
|
+
// first one to be broadcast after the grant has genuinely landed) --
|
|
785
|
+
// fine for future writes, not for content that already existed at grant
|
|
786
|
+
// time. A CRDT manifest merge is idempotent, so resending it a few times
|
|
787
|
+
// at increasing delays is a cheap, safe way to self-heal this race
|
|
788
|
+
// without needing an acknowledgement protocol this phase doesn't have.
|
|
789
|
+
for (const delayMs of [0, 20, 150]) {
|
|
790
|
+
if (delayMs > 0) await new Promise((r) => setTimeout(r, delayMs))
|
|
791
|
+
await this.#manifestSyncApi.syncWith(pubKey)
|
|
792
|
+
}
|
|
793
|
+
this.#events.emit('cloud-storage:grant-issued', { bucket: this.#bucket, pubKey, scopes: list })
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* Revoke `pubKey`'s one or more bare capability actions on this bucket.
|
|
798
|
+
* See `cloud-storage-backend.mjs`'s and `key-distribution.mjs`'s own
|
|
799
|
+
* documented PERMANENT LIMITATION: this stops FUTURE key distribution and
|
|
800
|
+
* chunk replication to `pubKey`, but cannot retroactively erase a bucket
|
|
801
|
+
* key (or plaintext) already delivered to them before the revoke.
|
|
802
|
+
* @param {string} pubKey
|
|
803
|
+
* @param {string|string[]} scopes
|
|
804
|
+
* @returns {Promise<void>}
|
|
805
|
+
*/
|
|
806
|
+
async revoke(pubKey, scopes) {
|
|
807
|
+
const list = Array.isArray(scopes) ? scopes : [scopes]
|
|
808
|
+
await this.#grantLogApi.revoke(pubKey, list)
|
|
809
|
+
await this.#grantLogApi.syncWith(pubKey)
|
|
810
|
+
this.#manifestSyncApi.unwatch(pubKey)
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Convenience for `grant(pubKey, 'replica')` -- see module doc comment,
|
|
815
|
+
* point 5.
|
|
816
|
+
* @param {string} pubKey
|
|
817
|
+
* @returns {Promise<void>}
|
|
818
|
+
*/
|
|
819
|
+
async designateReplica(pubKey) {
|
|
820
|
+
await this.grant(pubKey, 'replica')
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Introspection: this bucket's current admins and per-pubKey effective
|
|
825
|
+
* grants, per the last locally-replayed `GrantLog` state.
|
|
826
|
+
* @returns {{admins: string[], grants: Object<string, string[]>}}
|
|
827
|
+
*/
|
|
828
|
+
effectiveGrants() {
|
|
829
|
+
return this.#grantLogApi.effective()
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// -----------------------------------------------------------------------
|
|
833
|
+
// Teardown
|
|
834
|
+
// -----------------------------------------------------------------------
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* Detach every internally-composed service and close the local backend.
|
|
838
|
+
* Does not (cannot -- see `mesh-service.mjs`'s own documented limitation)
|
|
839
|
+
* remove `#backend` from `network` if it was registered there.
|
|
840
|
+
* @returns {Promise<void>}
|
|
841
|
+
*/
|
|
842
|
+
async close() {
|
|
843
|
+
if (this.#socket) {
|
|
844
|
+
await this.#socket.close().catch(() => {})
|
|
845
|
+
this.#socket = null
|
|
846
|
+
}
|
|
847
|
+
for (const handle of this.#handles) {
|
|
848
|
+
try {
|
|
849
|
+
await handle.teardown()
|
|
850
|
+
} catch (err) {
|
|
851
|
+
this.#onLog('cloud-storage:teardown-error', { bucket: this.#bucket, service: handle.name, error: err?.message || String(err) })
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
await this.#backend.close()
|
|
855
|
+
this.#events.closeAll()
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
export { DEFAULT_MANIFEST_WAIT_MS }
|