Skip to main content

saola_kit/envelope/
share.rs

1use std::collections::BTreeMap;
2use std::sync::{Arc, RwLock};
3
4use laravel::http::Request;
5use serde_json::Value;
6
7#[derive(Debug, thiserror::Error, PartialEq, Eq)]
8#[error("Invalid Saola::share key: {key}")]
9pub struct InvalidShareKeyError {
10    pub key: String,
11}
12
13type ShareResolver = Arc<dyn Fn(&Request) -> laravel::Result<Option<Value>> + Send + Sync>;
14
15/// Request-evaluated shared data resolvers (`Saola::share` -> `APP_CONFIGS.shared`).
16/// Returning `None` omits the key; returning `Err` logs and skips the key without breaking the page.
17#[derive(Clone, Default)]
18pub struct ClientShare {
19    resolvers: Arc<RwLock<BTreeMap<String, ShareResolver>>>,
20}
21
22impl std::fmt::Debug for ClientShare {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        let count = self.resolvers.read().map(|r| r.len()).unwrap_or(0);
25        f.debug_struct("ClientShare")
26            .field("resolver_count", &count)
27            .finish()
28    }
29}
30
31impl ClientShare {
32    pub fn new() -> Self {
33        Self::default()
34    }
35
36    pub fn share<F>(&self, key: impl Into<String>, resolver: F) -> Result<(), InvalidShareKeyError>
37    where
38        F: Fn(&Request) -> laravel::Result<Option<Value>> + Send + Sync + 'static,
39    {
40        let key = key.into();
41        if !is_valid_share_key(&key) {
42            return Err(InvalidShareKeyError { key });
43        }
44        if let Ok(mut map) = self.resolvers.write() {
45            map.insert(key, Arc::new(resolver));
46        }
47        Ok(())
48    }
49
50    pub fn export(&self, request: &Request) -> BTreeMap<String, Value> {
51        let snapshot: Vec<(String, ShareResolver)> = self
52            .resolvers
53            .read()
54            .map(|map| map.iter().map(|(k, v)| (k.clone(), Arc::clone(v))).collect())
55            .unwrap_or_default();
56
57        let mut shared = BTreeMap::new();
58        for (key, resolver) in snapshot {
59            match resolver(request) {
60                Ok(Some(value)) => {
61                    shared.insert(key, value);
62                }
63                Ok(None) => {}
64                Err(error) => {
65                    tracing::error!(key = %key, error = %error, "Saola shared data resolver failed");
66                }
67            }
68        }
69        shared
70    }
71}
72
73pub fn is_valid_share_key(key: &str) -> bool {
74    let mut chars = key.chars();
75    let Some(first) = chars.next() else {
76        return false;
77    };
78    if !first.is_ascii_alphabetic() {
79        return false;
80    }
81    chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
82}