credibil_dwn/
lib.rs

1//! # Decentralized Web Node (DWN)
2//!
3//! A [Decentralized Web Node (DWN)] is a data storage and message relay
4//! mechanism entities can use to locate public or private permissioned data
5//! related to a given Decentralized Identifier (DID). Decentralized Web Nodes
6//! are designed to be deployed in mesh-like datastore construct that enables
7//! an entity to operate multiple nodes that replicate state across all nodes.
8//!
9//! A DWN allows the owning entity to secure, manage, and transact data with
10//! others without reliance on location or provider-specific infrastructure,
11//! interfaces, or routing mechanisms.
12//!
13//! [Decentralized Web Node (DWN)]: https://identity.foundation/working-groups/didcomm-messaging/spec/#decentralized-web-node-dwn
14
15#![cfg_attr(docsrs, feature(doc_cfg))]
16
17pub mod authorization;
18mod error;
19pub mod event;
20mod grants;
21pub mod hd_key;
22pub mod interfaces;
23mod utils;
24
25#[cfg(feature = "client")]
26pub mod client;
27
28cfg_if::cfg_if! {
29    if #[cfg(feature = "server")] {
30        pub mod endpoint;
31        mod handlers;
32        pub mod provider;
33        mod schema;
34        pub mod store;
35        mod tasks;
36
37        // re-exports
38        pub use http::StatusCode;
39
40        pub use crate::endpoint::Message;
41        pub use crate::provider::Provider;
42        pub use crate::utils::cid;
43    }
44}
45
46// Re-exports
47use ::serde::{Deserialize, Serialize};
48pub use credibil_infosec::{Receiver, Signer};
49use derive_more::Display;
50
51pub use crate::error::Error;
52
53/// Result type for `DWN` handlers.
54pub type Result<T, E = Error> = std::result::Result<T, E>;
55
56/// `BlockStore` is used by implementers to provide data storage
57/// capability.
58pub trait BlockStore: Send + Sync {
59    /// Store a data block in the underlying block store.
60    fn put(
61        &self, owner: &str, partition: &str, cid: &str, data: &[u8],
62    ) -> impl Future<Output = anyhow::Result<()>> + Send;
63
64    /// Fetches a single block by CID from the underlying store, returning
65    /// `None` if no match was found.
66    fn get(
67        &self, owner: &str, partition: &str, cid: &str,
68    ) -> impl Future<Output = anyhow::Result<Option<Vec<u8>>>> + Send;
69
70    /// Delete the data block associated with the specified CID.
71    fn delete(
72        &self, owner: &str, partition: &str, cid: &str,
73    ) -> impl Future<Output = anyhow::Result<()>> + Send;
74
75    /// Purge all blocks from the store.
76    fn purge(
77        &self, owner: &str, partition: &str,
78    ) -> impl Future<Output = anyhow::Result<()>> + Send;
79}
80
81/// Web node interfaces.
82#[derive(Clone, Debug, Default, Display, Deserialize, Serialize, PartialEq, Eq)]
83pub enum Interface {
84    /// Records interface.
85    #[default]
86    Records,
87
88    /// Protocols interface.
89    Protocols,
90
91    /// Messages interface.
92    Messages,
93}
94
95/// Interface methods.
96#[derive(Clone, Debug, Default, Display, Deserialize, Serialize, PartialEq, Eq)]
97pub enum Method {
98    /// Read method.
99    #[default]
100    Read,
101    /// Write method.
102    Write,
103    /// Query method.
104    Query,
105    /// Configure method.
106    Configure,
107    /// Subscribe method.
108    Subscribe,
109    /// Delete method.
110    Delete,
111}
112
113/// Interface protocols.
114#[derive(Clone, Debug, Default, Deserialize, Serialize)]
115pub enum Protocol {
116    /// HTTP protocol.
117    #[default]
118    Http,
119}
120
121/// `OneOrMany` allows serde to serialize/deserialize a single object or a set of
122/// objects.
123#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
124#[serde(untagged)]
125pub enum OneOrMany<T> {
126    /// A single object.
127    One(T),
128    /// A set of objects.
129    Many(Vec<T>),
130}
131
132impl<T: Default> Default for OneOrMany<T> {
133    fn default() -> Self {
134        Self::One(T::default())
135    }
136}
137
138impl<T: Clone> OneOrMany<T> {
139    /// Convert the quota to a vector.
140    pub fn to_vec(&self) -> Vec<T> {
141        match self {
142            Self::One(value) => vec![value.clone()],
143            Self::Many(values) => values.clone(),
144        }
145    }
146}
147
148impl<T> From<T> for OneOrMany<T> {
149    fn from(value: T) -> Self {
150        Self::One(value)
151    }
152}
153
154impl<T> From<Vec<T>> for OneOrMany<T> {
155    fn from(value: Vec<T>) -> Self {
156        Self::Many(value)
157    }
158}
159
160// Custom serialization functions.
161mod serde {
162    use chrono::SecondsFormat::Micros;
163    use chrono::{DateTime, Utc};
164    use serde::Serializer;
165
166    /// Force serializing to an RFC 3339 string with microsecond precision.
167    pub fn rfc3339_micros<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
168    where
169        S: Serializer,
170    {
171        let s = date.to_rfc3339_opts(Micros, true);
172        serializer.serialize_str(&s)
173    }
174
175    /// Force serializing to an RFC 3339 string with microsecond precision.
176    #[allow(clippy::ref_option)]
177    pub fn rfc3339_micros_opt<S>(
178        date: &Option<DateTime<Utc>>, serializer: S,
179    ) -> Result<S::Ok, S::Error>
180    where
181        S: Serializer,
182    {
183        let Some(date) = date else {
184            return serializer.serialize_none();
185        };
186        rfc3339_micros(date, serializer)
187    }
188}