syncweb-core 0.1.1-alpha.10

delay-tolerant web surfing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use bytes::Bytes;
use iroh_blobs::Hash;
use iroh_blobs::api::Store as BlobStore;
use iroh_docs::{
    AuthorId, DocTicket, Entry, NamespaceId,
    api::{
        Doc,
        protocol::{AddrInfoOptions, ShareMode},
    },
    engine::LiveEvent,
    protocol::Docs,
    store::Query,
};
use n0_future::StreamExt;

use crate::{
    constants::{CATALOG_METADATA_KEY, MODE_KEY, NETWORK_MEMBERS_KEY},
    error::{Result, SyncwebError},
};

/// The kind of namespace being provisioned. Picks the `sys/` metadata key
/// stamped on a freshly created namespace so folder, catalog, and membership
/// provisioning share one code path.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ProvisionKind {
    Folder,
    Catalog,
    NetworkMembership,
}

impl ProvisionKind {
    const fn metadata_key(self) -> &'static [u8] {
        match self {
            Self::Folder => MODE_KEY,
            Self::Catalog => CATALOG_METADATA_KEY,
            Self::NetworkMembership => NETWORK_MEMBERS_KEY,
        }
    }
}

/// A provisioned namespace and its shareable write ticket.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ProvisionedDoc {
    pub doc: Doc,
    pub ticket: DocTicket,
    pub namespace_id: NamespaceId,
}

#[derive(Clone)]
pub struct DocsEngine {
    docs: Docs,
    blob_store: BlobStore,
    /// The local endpoint's node id, used to stamp the local relay address
    /// onto shared tickets.
    local_id: iroh::PublicKey,
    /// The Syncthing (BEP) relay custom address to advertise in shared tickets,
    /// when relaying is enabled.
    relay_addr: Option<iroh_base::CustomAddr>,
}

impl DocsEngine {
    #[must_use]
    pub fn new(
        docs: &Docs,
        blob_store: &BlobStore,
        local_id: iroh::PublicKey,
        relay_addr: Option<iroh_base::CustomAddr>,
    ) -> Self {
        Self {
            docs: docs.clone(),
            blob_store: blob_store.clone(),
            local_id,
            relay_addr,
        }
    }

    #[must_use]
    pub const fn inner(&self) -> &Docs {
        &self.docs
    }

    /// # Errors
    ///
    /// Returns an error if the namespace cannot be created.
    pub async fn create_namespace(&self) -> Result<Doc> {
        self.docs
            .create()
            .await
            .map_err(|error| SyncwebError::operation("failed to create namespace", error))
    }

    /// Provision a namespace and a shareable ticket for it.
    ///
    /// With `existing == None` a fresh namespace is created; with
    /// `existing == Some(id)` an already-local namespace is opened instead.
    /// In both cases a write ticket is returned so the caller can hand the
    /// namespace to a peer. Folder, catalog, and membership-doc provisioning
    /// all funnel through this single helper.
    ///
    /// # Errors
    ///
    /// Returns an error if the namespace cannot be created, opened, or shared.
    pub async fn create_or_open_namespace(&self, existing: Option<NamespaceId>) -> Result<(Doc, DocTicket)> {
        let doc = match existing {
            Some(namespace_id) => self
                .open(namespace_id)
                .await?
                .ok_or(SyncwebError::NamespaceNotAvailable)?,
            None => self.create_namespace().await?,
        };
        let ticket = self.share_ticket(&doc, true).await?;
        Ok((doc, ticket))
    }

    /// Provision a namespace of the given kind and stamp its `sys/` metadata.
    ///
    /// Unifies folder, catalog, and network-membership namespace creation:
    /// every kind funnels through [`Self::create_or_open_namespace`] and writes
    /// its kind-specific metadata key under `sys/`.
    ///
    /// # Errors
    ///
    /// Returns an error if the namespace cannot be created, opened, shared, or
    /// stamped.
    pub async fn provision(
        &self,
        kind: ProvisionKind,
        existing: Option<NamespaceId>,
        metadata: impl AsRef<[u8]>,
    ) -> Result<ProvisionedDoc> {
        let (doc, ticket) = self.create_or_open_namespace(existing).await?;
        let author = self.author().await?;
        self.set(&doc, author, kind.metadata_key(), metadata).await?;
        self.blob_store
            .sync_db()
            .await
            .map_err(|error| SyncwebError::operation("failed to flush metadata blob", error))?;
        let namespace_id = self.namespace_id(&doc);
        Ok(ProvisionedDoc {
            doc,
            ticket,
            namespace_id,
        })
    }

    /// # Errors
    ///
    /// Returns an error if the ticket cannot be imported.
    pub async fn import_ticket(&self, ticket: DocTicket) -> Result<Doc> {
        self.docs
            .import(ticket)
            .await
            .map_err(|error| SyncwebError::operation("failed to import document ticket", error))
    }

    /// # Errors
    ///
    /// Returns an error if the document cannot be opened.
    pub async fn open(&self, namespace_id: NamespaceId) -> Result<Option<Doc>> {
        self.docs
            .open(namespace_id)
            .await
            .map_err(|error| SyncwebError::operation("failed to open namespace", error))
    }

    /// # Errors
    ///
    /// Returns an error if the namespace cannot be dropped.
    pub async fn drop_namespace(&self, namespace_id: NamespaceId) -> Result<()> {
        self.docs
            .drop_doc(namespace_id)
            .await
            .map_err(|error| SyncwebError::operation("failed to drop namespace", error))?;
        Ok(())
    }

    /// Start live synchronization for a document.
    ///
    /// An empty peer list uses peers already learned by iroh-docs for the
    /// namespace.
    ///
    /// # Errors
    ///
    /// Returns an error if the document cannot be opened for synchronization.
    pub async fn start_sync(&self, doc: &Doc, peers: Vec<iroh::EndpointAddr>) -> Result<()> {
        doc.start_sync(peers)
            .await
            .map_err(|error| SyncwebError::operation("failed to start document synchronization", error))
    }

    /// # Errors
    ///
    /// Returns an error if the document cannot be shared.
    pub async fn share(&self, doc: &Doc, mode: ShareMode) -> Result<DocTicket> {
        self.share_with_options(doc, mode, AddrInfoOptions::RelayAndAddresses)
            .await
    }

    /// Share a document with a specific [`AddrInfoOptions`], so callers can
    /// mint node-id-only tickets that force a peer to resolve addresses via the
    /// DHT topic tracker rather than from the ticket itself.
    ///
    /// # Errors
    ///
    /// Returns an error if the document cannot be shared.
    pub async fn share_with_options(
        &self,
        doc: &Doc,
        mode: ShareMode,
        addr_options: AddrInfoOptions,
    ) -> Result<DocTicket> {
        let mut ticket = doc
            .share(mode, addr_options)
            .await
            .map_err(|error| SyncwebError::operation("failed to share document", error))?;
        if addr_options != AddrInfoOptions::Id
            && let Some(relay_addr) = &self.relay_addr
        {
            for node in &mut ticket.nodes {
                if node.id == self.local_id {
                    node.addrs.insert(iroh::TransportAddr::Custom(relay_addr.clone()));
                }
            }
        }
        Ok(ticket)
    }

    /// Share a read or write ticket for a document.
    ///
    /// # Errors
    ///
    /// Returns an error if the document cannot be shared.
    pub async fn share_ticket(&self, doc: &Doc, writable: bool) -> Result<DocTicket> {
        self.share_ticket_with_options(doc, writable, AddrInfoOptions::RelayAndAddresses)
            .await
    }

    /// Share a read or write ticket for a document with a specific
    /// [`AddrInfoOptions`].
    ///
    /// # Errors
    ///
    /// Returns an error if the document cannot be shared.
    pub async fn share_ticket_with_options(
        &self,
        doc: &Doc,
        writable: bool,
        addr_options: AddrInfoOptions,
    ) -> Result<DocTicket> {
        let mode = if writable { ShareMode::Write } else { ShareMode::Read };
        self.share_with_options(doc, mode, addr_options).await
    }

    /// # Errors
    ///
    /// Returns an error if the default author cannot be retrieved.
    pub async fn author(&self) -> Result<AuthorId> {
        self.docs
            .author_default()
            .await
            .map_err(|error| SyncwebError::operation("failed to retrieve document author", error))
    }

    /// # Errors
    ///
    /// Returns an error if the author cannot be exported.
    pub async fn export_author(&self, author_id: AuthorId) -> Result<Option<iroh_docs::Author>> {
        self.docs
            .author_export(author_id)
            .await
            .map_err(|error| SyncwebError::operation("failed to export document author", error))
    }

    /// # Errors
    ///
    /// Returns an error if the author cannot be imported.
    pub async fn import_author(&self, author: iroh_docs::Author) -> Result<AuthorId> {
        self.docs
            .author_import(author.clone())
            .await
            .map_err(|error| SyncwebError::operation("failed to import document author", error))?;
        Ok(author.id())
    }

    /// # Errors
    ///
    /// Returns an error if setting the document entry fails.
    pub async fn set(
        &self,
        doc: &Doc,
        author: AuthorId,
        key: impl AsRef<[u8]>,
        value: impl AsRef<[u8]>,
    ) -> Result<Hash> {
        doc.set_bytes(
            author,
            Bytes::copy_from_slice(key.as_ref()),
            Bytes::copy_from_slice(value.as_ref()),
        )
        .await
        .map_err(|error| SyncwebError::operation("failed to set document entry", error))
    }

    /// # Errors
    ///
    /// Returns an error if setting the document blob fails.
    pub async fn set_blob(
        &self,
        doc: &Doc,
        author: AuthorId,
        key: impl AsRef<[u8]>,
        hash: Hash,
        size: u64,
    ) -> Result<()> {
        doc.set_hash(author, Bytes::copy_from_slice(key.as_ref()), hash, size)
            .await
            .map_err(|error| SyncwebError::operation("failed to set document blob", error))?;
        Ok(())
    }

    /// # Errors
    ///
    /// Returns an error if getting the document entry fails.
    pub async fn get(&self, doc: &Doc, author: AuthorId, key: impl AsRef<[u8]>) -> Result<Option<Entry>> {
        doc.get_exact(author, key, false)
            .await
            .map_err(|error| SyncwebError::operation("failed to get document entry", error))
    }

    /// Read the latest entry for a key regardless of which author wrote it.
    ///
    /// # Errors
    ///
    /// Returns an error if the document query fails.
    pub async fn get_any(&self, doc: &Doc, key: impl AsRef<[u8]>) -> Result<Option<Entry>> {
        let entries = doc
            .get_many(Query::single_latest_per_key().key_exact(key))
            .await
            .map_err(|error| SyncwebError::operation("failed to query document entries", error))?;
        tokio::pin!(entries);
        n0_future::StreamExt::next(&mut entries)
            .await
            .transpose()
            .map_err(|error| SyncwebError::operation("failed to read document query result", error))
    }

    /// Read the latest non-empty entry for every document key.
    ///
    /// # Errors
    ///
    /// Returns an error if the document query fails.
    pub async fn list_latest(&self, doc: &Doc) -> Result<Vec<Entry>> {
        let entries = doc
            .get_many(Query::single_latest_per_key().build())
            .await
            .map_err(|error| SyncwebError::operation("failed to query document entries", error))?;
        tokio::pin!(entries);
        let mut output = Vec::new();
        while let Some(entry_result) = n0_future::StreamExt::next(&mut entries).await {
            let entry =
                entry_result.map_err(|error| SyncwebError::operation("failed to read document entry", error))?;
            output.push(entry);
        }
        Ok(output)
    }

    /// Read every non-empty entry for one document key, including variants
    /// written by different authors (the CRDT does not lose them; the collapsed
    /// [`Self::list_latest`] view hides them).
    ///
    /// Used by conflict resolution so every author's version of a divergent path
    /// remains materializable.
    ///
    /// # Errors
    ///
    /// Returns an error if the document query fails.
    pub async fn list_all_entries(&self, doc: &Doc) -> Result<Vec<Entry>> {
        let entries = doc
            .get_many(Query::all().build())
            .await
            .map_err(|error| SyncwebError::operation("failed to query document entries", error))?;
        tokio::pin!(entries);
        let mut output = Vec::new();
        while let Some(entry_result) = n0_future::StreamExt::next(&mut entries).await {
            let entry =
                entry_result.map_err(|error| SyncwebError::operation("failed to read document entry", error))?;
            output.push(entry);
        }
        Ok(output)
    }

    /// Delete the current value for a document key.
    ///
    /// # Errors
    ///
    /// Returns an error if the document entry cannot be deleted.
    pub async fn delete(&self, doc: &Doc, author: AuthorId, key: impl AsRef<[u8]>) -> Result<()> {
        doc.del(author, key.as_ref().to_vec())
            .await
            .map_err(|error| SyncwebError::operation("failed to delete document entry", error))?;
        Ok(())
    }

    /// # Errors
    ///
    /// Returns an error if watching the document fails.
    pub async fn watch(
        &self,
        doc: &Doc,
    ) -> Result<impl n0_future::Stream<Item = Result<LiveEvent>> + Send + Unpin + 'static> {
        let stream = doc
            .subscribe()
            .await
            .map_err(|error| SyncwebError::operation("failed to subscribe to document", error))?;
        Ok(stream.map(|event| event.map_err(|error| SyncwebError::operation("document event failed", error))))
    }

    /// Subscribe to a document's live events and start live synchronization.
    ///
    /// This is the shared prologue for every background doc consumer: catalog
    /// subscribers, indexing watchers, and sync intents all pair
    /// [`Self::watch`] with [`Self::start_sync`] before spawning a consumer
    /// task over the returned stream.
    ///
    /// # Errors
    ///
    /// Returns an error if the document cannot be watched or synchronized.
    pub async fn watch_and_sync(
        &self,
        doc: &Doc,
    ) -> Result<impl n0_future::Stream<Item = Result<LiveEvent>> + Send + Unpin + 'static> {
        let live_events = self.watch(doc).await?;
        self.start_sync(doc, Vec::new()).await?;
        Ok(live_events)
    }

    #[must_use]
    pub fn namespace_id(&self, doc: &Doc) -> NamespaceId {
        doc.id()
    }
}