Skip to main content

kernable/
data.rs

1//! Files and cache values: bytes stored by the kernel under a key of a domain, outside the
2//! signed event log. Each request is signed with this process's key and needs a grant for the
3//! domain: `data_read` to read files, `data_write` to put and delete them, `cache` for the cache.
4//! Each request carries a signed request context (the client's default, see
5//! [`crate::Options::context`], or one set with [`Files::context`] or [`Cache::context`]), and
6//! the kernel runs the domain's middlewares before it (types `<domain>.PutData`, `.GetData`,
7//! `.DeleteData`, `.ListData`, `.SetCache`, `.GetCache`, `.DeleteCache`).
8
9use std::time::Duration;
10
11use kernable_core::{
12    PROTOCOL,
13    proto::{
14        CacheRequest, DataRequest, cache_service_client::CacheServiceClient,
15        data_service_client::DataServiceClient,
16    },
17    signing,
18};
19
20use crate::{Client, Error, RequestContext, issued_now};
21
22/// Room for the largest file a kernel takes (`--max-data-bytes`, at most 128 MiB) and the rest
23/// of the message.
24const MAX_MESSAGE_BYTES: usize = 129 << 20;
25
26/// A file as stored by the kernel, returned by [`Files::get`].
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct Data {
29    /// The file's bytes.
30    pub data: Vec<u8>,
31    /// The media type given when the file was put, e.g. `image/png`.
32    pub content_type: String,
33    /// The SHA-256 of `data`, hex, as the kernel computed it.
34    pub sha256: String,
35}
36
37/// A file as [`Files::list`] names it.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct Listed {
40    pub key: String,
41    pub content_type: String,
42    /// The file's length in bytes.
43    pub size: u64,
44}
45
46/// One page of [`Files::list`]: up to 1,000 files, and `next` (to pass as `after`) if there
47/// may be more.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct Listing {
50    pub files: Vec<Listed>,
51    pub next: Option<String>,
52}
53
54/// Files of up to 16 MiB (the kernel's `--max-data-bytes`) under keys of 1 to 512 bytes, per tenant and domain; see
55/// [`crate::Kernable::data`]. Files are not part of the signed event log, and erasing a vault
56/// subject does not delete them, so keep personal data in vault fields instead. A refused or
57/// invalid request is [`Error::Status`]; a middleware that refuses it (checking `PutData`,
58/// `GetData`, `DeleteData` or `ListData` of the domain) makes it `PERMISSION_DENIED` with
59/// `"<code>: <message>"`. Example:
60/// `kernable.data().put("shop", "invoices/c1.pdf", pdf, "application/pdf").await?`, then
61/// `kernable.data().get("shop", "invoices/c1.pdf").await?` returns `Some(Data { .. })`.
62#[derive(Clone)]
63pub struct Files {
64    client: Client,
65    tenant: String,
66    context: RequestContext,
67}
68
69impl Files {
70    pub(crate) fn new(client: Client, tenant: String, context: RequestContext) -> Files {
71        Files {
72            client,
73            tenant,
74            context,
75        }
76    }
77
78    /// The tenant to keep files under. Default: the connection's ([`crate::Options::tenant`]).
79    #[must_use]
80    pub fn tenant(mut self, tenant: impl Into<String>) -> Files {
81        self.tenant = tenant.into();
82        self
83    }
84
85    /// Replaces the client's default context for the requests of this handle (signed with
86    /// each; middlewares decide on it); inside a listener, pass `ctx.follow()`. Example:
87    /// `kernable.data().context(alice).get("shop", "k").await?`.
88    #[must_use]
89    pub fn context(mut self, context: RequestContext) -> Files {
90        self.context = context;
91        self
92    }
93
94    /// Stores `data` as `key` of `domain` (granted `data_write`), replacing any file there.
95    /// Returns the SHA-256 of `data` (hex) as the kernel computed it: for an event to name.
96    pub async fn put(
97        &self,
98        domain: &str,
99        key: &str,
100        data: impl Into<Vec<u8>>,
101        content_type: &str,
102    ) -> Result<String, Error> {
103        let request = self.request("put", domain, key, data.into(), content_type, "");
104        let res = self
105            .client
106            .routed(&request.tenant_id.clone(), |client| {
107                let request = request.clone();
108                async move {
109                    client
110                        .call(None, request, |channel, r| {
111                            let mut service = Self::service(channel);
112                            async move { service.put_data(r).await }
113                        })
114                        .await
115                }
116            })
117            .await?;
118        Ok(hex::encode(res.sha256))
119    }
120
121    /// The file `key` of `domain` (granted `data_read`); `None` if there is none.
122    pub async fn get(&self, domain: &str, key: &str) -> Result<Option<Data>, Error> {
123        let request = self.request("get", domain, key, Vec::new(), "", "");
124        let res = self
125            .client
126            .routed(&request.tenant_id.clone(), |client| {
127                let request = request.clone();
128                async move {
129                    client
130                        .call_with(None, request, true, |channel, r| {
131                            let mut service = Self::service(channel);
132                            async move { service.get_data(r).await }
133                        })
134                        .await
135                }
136            })
137            .await?;
138        Ok(res.found.then_some(Data {
139            data: res.data,
140            content_type: res.content_type,
141            sha256: hex::encode(res.sha256),
142        }))
143    }
144
145    /// The files of `domain` whose keys start with `prefix` (granted `data_read`), in the order
146    /// of their keys' bytes, up to 1,000 after the key `after` (`""` for the first page). To
147    /// find files no event names, or what a tenant stores. Example: `let mut after =
148    /// String::new(); loop { let page = files.list("shop", "invoices/", &after).await?; …;
149    /// match page.next { Some(n) => after = n, None => break } }`.
150    pub async fn list(&self, domain: &str, prefix: &str, after: &str) -> Result<Listing, Error> {
151        let request = self.request("list", domain, prefix, Vec::new(), "", after);
152        let res = self
153            .client
154            .routed(&request.tenant_id.clone(), |client| {
155                let request = request.clone();
156                async move {
157                    client
158                        .call_with(None, request, true, |channel, r| {
159                            let mut service = Self::service(channel);
160                            async move { service.list_data(r).await }
161                        })
162                        .await
163                }
164            })
165            .await?;
166        Ok(Listing {
167            files: res
168                .files
169                .into_iter()
170                .map(|f| Listed {
171                    key: f.key,
172                    content_type: f.content_type,
173                    size: f.size,
174                })
175                .collect(),
176            next: (!res.next.is_empty()).then_some(res.next),
177        })
178    }
179
180    /// Deletes the file `key` of `domain` (granted `data_write`); whether there was one.
181    pub async fn delete(&self, domain: &str, key: &str) -> Result<bool, Error> {
182        let request = self.request("delete", domain, key, Vec::new(), "", "");
183        let res = self
184            .client
185            .routed(&request.tenant_id.clone(), |client| {
186                let request = request.clone();
187                async move {
188                    client
189                        .call(None, request, |channel, r| {
190                            let mut service = Self::service(channel);
191                            async move { service.delete_data(r).await }
192                        })
193                        .await
194                }
195            })
196            .await?;
197        Ok(res.found)
198    }
199
200    fn service(channel: tonic::transport::Channel) -> DataServiceClient<tonic::transport::Channel> {
201        DataServiceClient::new(channel)
202            .max_encoding_message_size(MAX_MESSAGE_BYTES)
203            .max_decoding_message_size(MAX_MESSAGE_BYTES)
204    }
205
206    fn request(
207        &self,
208        op: &str,
209        domain: &str,
210        key: &str,
211        data: Vec<u8>,
212        content_type: &str,
213        after: &str,
214    ) -> DataRequest {
215        let mut r = DataRequest {
216            tenant_id: self.tenant.clone(),
217            domain: domain.to_owned(),
218            key: key.to_owned(),
219            data,
220            content_type: content_type.to_owned(),
221            issued_at: issued_now(),
222            client_sig: None,
223            protocol: PROTOCOL,
224            context: Some(self.context.to_wire()),
225            after: after.to_owned(),
226        };
227        r.client_sig = Some(self.client.sign(&signing::data_message(op, &r)));
228        r
229    }
230}
231
232/// Values of up to 1 MiB under keys of 1 to 512 bytes, per tenant and domain, held in the
233/// kernel's memory (granted `cache`); see [`crate::Kernable::cache`]. A restart of the kernel
234/// empties the cache; values are not part of the signed event log, and erasing a vault subject
235/// does not delete them. For rate limits, short-lived tokens and computed values. A refused
236/// or invalid request is [`Error::Status`]; a middleware that refuses it (checking `SetCache`,
237/// `GetCache` or `DeleteCache` of the domain) makes it `PERMISSION_DENIED` with
238/// `"<code>: <message>"`. Example:
239/// `kernable.cache().set("shop", "rate:c1", "3", Some(Duration::from_secs(60))).await?`, then
240/// `kernable.cache().get("shop", "rate:c1").await?` returns `Some(b"3".to_vec())`.
241#[derive(Clone)]
242pub struct Cache {
243    client: Client,
244    tenant: String,
245    context: RequestContext,
246}
247
248impl Cache {
249    pub(crate) fn new(client: Client, tenant: String, context: RequestContext) -> Cache {
250        Cache {
251            client,
252            tenant,
253            context,
254        }
255    }
256
257    /// The tenant to keep values under. Default: the connection's ([`crate::Options::tenant`]).
258    #[must_use]
259    pub fn tenant(mut self, tenant: impl Into<String>) -> Cache {
260        self.tenant = tenant.into();
261        self
262    }
263
264    /// Replaces the client's default context for the requests of this handle (signed with
265    /// each; middlewares decide on it); inside a listener, pass `ctx.follow()`. Example:
266    /// `kernable.cache().context(alice).get("shop", "k").await?`.
267    #[must_use]
268    pub fn context(mut self, context: RequestContext) -> Cache {
269        self.context = context;
270        self
271    }
272
273    /// Stores `value` as `key` of `domain` (granted `cache`), replacing any value there. With a
274    /// `ttl`, the value expires after it; without, it stays until deleted or the kernel
275    /// restarts. A `&str` or `String` is stored as UTF-8.
276    pub async fn set(
277        &self,
278        domain: &str,
279        key: &str,
280        value: impl Into<Vec<u8>>,
281        ttl: Option<Duration>,
282    ) -> Result<(), Error> {
283        // A TTL under a millisecond would mean none on the wire.
284        let ttl_ms = ttl.map_or(0, |t| (t.as_millis() as u64).max(1));
285        let request = self.request("set", domain, key, value.into(), ttl_ms);
286        self.client
287            .routed(&request.tenant_id.clone(), |client| {
288                let request = request.clone();
289                async move {
290                    client
291                        .call(None, request, |channel, r| {
292                            let mut service = Self::service(channel);
293                            async move { service.set_cache(r).await }
294                        })
295                        .await
296                }
297            })
298            .await?;
299        Ok(())
300    }
301
302    /// The value `key` of `domain`; `None` if there is none or it expired.
303    pub async fn get(&self, domain: &str, key: &str) -> Result<Option<Vec<u8>>, Error> {
304        let request = self.request("get", domain, key, Vec::new(), 0);
305        let res = self
306            .client
307            .routed(&request.tenant_id.clone(), |client| {
308                let request = request.clone();
309                async move {
310                    client
311                        .call_with(None, request, true, |channel, r| {
312                            let mut service = Self::service(channel);
313                            async move { service.get_cache(r).await }
314                        })
315                        .await
316                }
317            })
318            .await?;
319        Ok(res.found.then_some(res.value))
320    }
321
322    /// Deletes the value `key` of `domain`; whether there was one.
323    pub async fn delete(&self, domain: &str, key: &str) -> Result<bool, Error> {
324        let request = self.request("delete", domain, key, Vec::new(), 0);
325        let res = self
326            .client
327            .routed(&request.tenant_id.clone(), |client| {
328                let request = request.clone();
329                async move {
330                    client
331                        .call(None, request, |channel, r| {
332                            let mut service = Self::service(channel);
333                            async move { service.delete_cache(r).await }
334                        })
335                        .await
336                }
337            })
338            .await?;
339        Ok(res.found)
340    }
341
342    fn service(
343        channel: tonic::transport::Channel,
344    ) -> CacheServiceClient<tonic::transport::Channel> {
345        CacheServiceClient::new(channel)
346    }
347
348    fn request(
349        &self,
350        op: &str,
351        domain: &str,
352        key: &str,
353        value: Vec<u8>,
354        ttl_ms: u64,
355    ) -> CacheRequest {
356        let mut r = CacheRequest {
357            tenant_id: self.tenant.clone(),
358            domain: domain.to_owned(),
359            key: key.to_owned(),
360            value,
361            ttl_ms,
362            issued_at: issued_now(),
363            client_sig: None,
364            protocol: PROTOCOL,
365            context: Some(self.context.to_wire()),
366        };
367        r.client_sig = Some(self.client.sign(&signing::cache_message(op, &r)));
368        r
369    }
370}