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
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use noosphere_core::{
    authority::Author,
    data::{Did, Link, MemoIpld},
    view::Sphere,
};
use noosphere_storage::{SphereDb, Storage};
use std::{
    ops::{Deref, DerefMut},
    sync::Arc,
};
use tokio::sync::{Mutex, OwnedMutexGuard};

use crate::SphereContextKey;

use super::SphereContext;

#[allow(missing_docs)]
#[cfg(not(target_arch = "wasm32"))]
pub trait HasConditionalSendSync: Send + Sync {}

#[cfg(not(target_arch = "wasm32"))]
impl<S> HasConditionalSendSync for S where S: Send + Sync {}

#[allow(missing_docs)]
#[cfg(target_arch = "wasm32")]
pub trait HasConditionalSendSync {}

#[cfg(target_arch = "wasm32")]
impl<S> HasConditionalSendSync for S {}

/// Any container that can provide non-mutable access to a [SphereContext]
/// should implement [HasSphereContext]. The most common example of something
/// that may implement this trait is an `Arc<SphereContext<_, _>>`. Implementors
/// of this trait will automatically implement other traits that provide
/// convience methods for accessing different parts of the sphere, such as
/// content and petnames.
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait HasSphereContext<S>: Clone + HasConditionalSendSync
where
    S: Storage,
{
    /// The type of the internal read-only [SphereContext]
    type SphereContext: Deref<Target = SphereContext<S>> + HasConditionalSendSync;

    /// Get the [SphereContext] that is made available by this container.
    async fn sphere_context(&self) -> Result<Self::SphereContext>;

    /// Get the DID identity of the sphere that this FS view is reading from and
    /// writing to
    async fn identity(&self) -> Result<Did> {
        let sphere_context = self.sphere_context().await?;

        Ok(sphere_context.identity().clone())
    }

    /// The CID of the most recent local version of this sphere
    async fn version(&self) -> Result<Link<MemoIpld>> {
        self.sphere_context().await?.version().await
    }

    /// Get a data view into the sphere at the current revision
    async fn to_sphere(&self) -> Result<Sphere<SphereDb<S>>> {
        let version = self.version().await?;
        Ok(Sphere::at(&version, self.sphere_context().await?.db()))
    }

    /// Create a new [SphereContext] via [SphereContext::with_author] and wrap it in the same
    /// [HasSphereContext] implementation, returning the result
    async fn with_author(&self, author: &Author<SphereContextKey>) -> Result<Self> {
        Ok(Self::wrap(self.sphere_context().await?.with_author(author).await?).await)
    }

    /// Wrap a given [SphereContext] in this [HasSphereContext]
    async fn wrap(sphere_context: SphereContext<S>) -> Self;
}

/// Any container that can provide mutable access to a [SphereContext] should
/// implement [HasMutableSphereContext]. The most common example of something
/// that may implement this trait is `Arc<Mutex<SphereContext<_, _>>>`.
/// Implementors of this trait will automatically implement other traits that
/// provide convenience methods for modifying the contents, petnames and other
/// aspects of a sphere.
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait HasMutableSphereContext<S>: HasSphereContext<S> + HasConditionalSendSync
where
    S: Storage,
{
    /// The type of the internal mutable [SphereContext]
    type MutableSphereContext: Deref<Target = SphereContext<S>>
        + DerefMut<Target = SphereContext<S>>
        + HasConditionalSendSync;

    /// Get a mutable reference to the [SphereContext] that is wrapped by this
    /// container.
    async fn sphere_context_mut(&mut self) -> Result<Self::MutableSphereContext>;

    /// Returns true if any changes have been made to the underlying
    /// [SphereContext] that have not been committed to the associated sphere
    /// yet (according to local history).
    async fn has_unsaved_changes(&self) -> Result<bool> {
        let context = self.sphere_context().await?;
        Ok(!context.mutation().is_empty())
    }

    /// Commits a series of writes to the sphere and signs the new version. The
    /// new version [Link<MemoIpld>] of the sphere is returned. This method must
    /// be invoked in order to update the local history of the sphere with any
    /// changes that have been made.
    async fn save(
        &mut self,
        additional_headers: Option<Vec<(String, String)>>,
    ) -> Result<Link<MemoIpld>> {
        let sphere = self.to_sphere().await?;
        let mut sphere_context = self.sphere_context_mut().await?;
        let sphere_identity = sphere_context.identity().clone();
        let mut revision = sphere.apply_mutation(sphere_context.mutation()).await?;

        match additional_headers {
            Some(headers) if !headers.is_empty() => revision.memo.replace_headers(headers),
            _ if sphere_context.mutation().is_empty() => return Err(anyhow!("No changes to save")),
            _ => (),
        }

        let new_sphere_version = revision
            .sign(
                &sphere_context.author().key,
                sphere_context.author().authorization.as_ref(),
            )
            .await?;

        sphere_context
            .db_mut()
            .set_version(&sphere_identity, &new_sphere_version)
            .await?;
        sphere_context.db_mut().flush().await?;
        sphere_context.mutation_mut().reset();

        Ok(new_sphere_version)
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl<S> HasSphereContext<S> for Arc<Mutex<SphereContext<S>>>
where
    S: Storage + 'static,
{
    type SphereContext = OwnedMutexGuard<SphereContext<S>>;

    async fn sphere_context(&self) -> Result<Self::SphereContext> {
        Ok(self.clone().lock_owned().await)
    }

    async fn wrap(sphere_context: SphereContext<S>) -> Self {
        Arc::new(Mutex::new(sphere_context))
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl<S, T> HasSphereContext<S> for Box<T>
where
    T: HasSphereContext<S>,
    S: Storage + 'static,
{
    type SphereContext = T::SphereContext;

    async fn sphere_context(&self) -> Result<Self::SphereContext> {
        T::sphere_context(self).await
    }

    async fn wrap(sphere_context: SphereContext<S>) -> Self {
        Box::new(T::wrap(sphere_context).await)
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl<S> HasSphereContext<S> for Arc<SphereContext<S>>
where
    S: Storage,
{
    type SphereContext = Arc<SphereContext<S>>;

    async fn sphere_context(&self) -> Result<Self::SphereContext> {
        Ok(self.clone())
    }

    async fn wrap(sphere_context: SphereContext<S>) -> Self {
        Arc::new(sphere_context)
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl<S> HasMutableSphereContext<S> for Arc<Mutex<SphereContext<S>>>
where
    S: Storage + 'static,
{
    type MutableSphereContext = OwnedMutexGuard<SphereContext<S>>;

    async fn sphere_context_mut(&mut self) -> Result<Self::MutableSphereContext> {
        self.sphere_context().await
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl<S, T> HasMutableSphereContext<S> for Box<T>
where
    T: HasMutableSphereContext<S>,
    S: Storage + 'static,
{
    type MutableSphereContext = T::MutableSphereContext;

    async fn sphere_context_mut(&mut self) -> Result<Self::MutableSphereContext> {
        T::sphere_context_mut(self).await
    }
}