Skip to main content

adk_site/
live.rs

1//! The live lane: state the edge serves through read-only capabilities and that is never
2//! released (spec 3.5 §7.8.2 "Volatile data", §7.8.3 "Three lanes", A-I26).
3//!
4//! Feeds write stock, availability, scores, queue times and counts here; the edge answers
5//! its read-only capabilities from it with a cache of seconds. Nothing here carries a claim,
6//! and an order checks live state again at order time. Pages show the value the last release
7//! carried with its time, so they work with script off.
8
9use std::collections::BTreeMap;
10
11use async_trait::async_trait;
12use awp_types::ContentId;
13use chrono::{DateTime, Utc};
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16use tokio::sync::RwLock;
17
18use crate::error::Result;
19
20/// One live value.
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct LiveValue {
24    /// The value.
25    pub value: Value,
26    /// When it was set.
27    pub at: DateTime<Utc>,
28    /// The feed that set it, if a feed did.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub feed: Option<String>,
31}
32
33/// Where the edge reads live values from (spec 3.5 §7.8.3). The edge implements it over its
34/// own store; [`InMemoryLiveStore`] keeps values in memory.
35#[async_trait]
36pub trait LiveStore: Send + Sync {
37    /// Sets live values of one item.
38    ///
39    /// # Errors
40    ///
41    /// Returns an error when the store cannot be written.
42    async fn set(&self, id: &ContentId, values: BTreeMap<String, LiveValue>) -> Result<()>;
43
44    /// The live values of one item.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error when the store cannot be read.
49    async fn get(&self, id: &ContentId) -> Result<BTreeMap<String, LiveValue>>;
50}
51
52/// Live values in memory.
53///
54/// # Example
55///
56/// ```rust
57/// use std::collections::BTreeMap;
58/// use adk_site::live::{InMemoryLiveStore, LiveStore, LiveValue};
59///
60/// # #[tokio::main(flavor = "current_thread")]
61/// # async fn main() -> adk_site::Result<()> {
62/// let store = InMemoryLiveStore::default();
63/// let value = LiveValue { value: 4.into(), at: chrono::Utc::now(), feed: Some("pos".into()) };
64/// store.set(&"panel".into(), BTreeMap::from([("stock".to_string(), value)])).await?;
65/// assert_eq!(store.get(&"panel".into()).await?["stock"].value, 4);
66/// assert_eq!(store.writes().await, 1);
67/// # Ok(())
68/// # }
69/// ```
70#[derive(Debug, Default)]
71pub struct InMemoryLiveStore {
72    values: RwLock<Values>,
73}
74
75/// Live values by item and field, and the count of values written.
76#[derive(Debug, Default)]
77struct Values {
78    items: BTreeMap<ContentId, BTreeMap<String, LiveValue>>,
79    writes: u64,
80}
81
82impl InMemoryLiveStore {
83    /// Values written so far, counted per field.
84    pub async fn writes(&self) -> u64 {
85        self.values.read().await.writes
86    }
87}
88
89#[async_trait]
90impl LiveStore for InMemoryLiveStore {
91    async fn set(&self, id: &ContentId, values: BTreeMap<String, LiveValue>) -> Result<()> {
92        let mut guard = self.values.write().await;
93        guard.writes += values.len() as u64;
94        guard.items.entry(id.clone()).or_default().extend(values);
95        Ok(())
96    }
97
98    async fn get(&self, id: &ContentId) -> Result<BTreeMap<String, LiveValue>> {
99        Ok(self.values.read().await.items.get(id).cloned().unwrap_or_default())
100    }
101}