Skip to main content

lean_ctx/core/context_os/
observation.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Private, durable observations owned by the ContextBus.
3
4use crate::core::events::LeanCtxEvent;
5use crate::core::ocla_bus::OclaEvent;
6use std::fmt;
7use std::sync::{Mutex, MutexGuard, OnceLock, TryLockError};
8use std::time::{Duration, Instant};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum LocalObservationSource {
12    Ocla,
13    Legacy,
14}
15
16impl LocalObservationSource {
17    pub fn as_str(self) -> &'static str {
18        match self {
19            Self::Ocla => "ocla",
20            Self::Legacy => "legacy",
21        }
22    }
23
24    pub fn parse(value: &str) -> Result<Self, ObservationPersistenceError> {
25        match value {
26            "ocla" => Ok(Self::Ocla),
27            "legacy" => Ok(Self::Legacy),
28            other => Err(ObservationPersistenceError::InvalidRow(format!(
29                "unknown local observation source {other:?}"
30            ))),
31        }
32    }
33}
34
35#[derive(Debug)]
36pub enum ObservationPersistenceError {
37    Io(std::io::Error),
38    LockPoisoned,
39    LockTimeout,
40    IdentityConflict,
41    Serialization(String),
42    Sqlite(String),
43    InvalidRow(String),
44}
45
46#[derive(Debug, Clone, PartialEq)]
47pub enum LocalObservationPayload {
48    Ocla(OclaEvent),
49    Legacy(LeanCtxEvent),
50}
51
52#[derive(Debug, Clone, PartialEq)]
53pub struct LocalObservationV1 {
54    /// SQLite's local cursor; this is not the producer's identity.
55    pub cursor_id: i64,
56    /// A producer instance distinguishes IDs reused after a process restart.
57    pub producer_instance: String,
58    /// The original producer ID, retained as u64 independently of SQLite.
59    pub source_id: u64,
60    /// OCLA IDs use decimal milliseconds; legacy timestamps remain verbatim.
61    pub source_timestamp: String,
62    pub source: LocalObservationSource,
63    pub payload: LocalObservationPayload,
64}
65
66impl fmt::Display for ObservationPersistenceError {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Self::Io(error) => write!(f, "context bus storage unavailable: {error}"),
70            Self::LockPoisoned => f.write_str("context bus observation lock poisoned"),
71            Self::LockTimeout => f.write_str("context bus observation lock timed out"),
72            Self::IdentityConflict => {
73                f.write_str("observation identity reused with different data")
74            }
75            Self::Serialization(error) => write!(f, "observation serialization failed: {error}"),
76            Self::Sqlite(error) => write!(f, "observation sqlite operation failed: {error}"),
77            Self::InvalidRow(error) => write!(f, "invalid local observation row: {error}"),
78        }
79    }
80}
81
82impl std::error::Error for ObservationPersistenceError {}
83
84impl From<serde_json::Error> for ObservationPersistenceError {
85    fn from(error: serde_json::Error) -> Self {
86        Self::Serialization(error.to_string())
87    }
88}
89
90impl From<rusqlite::Error> for ObservationPersistenceError {
91    fn from(error: rusqlite::Error) -> Self {
92        Self::Sqlite(error.to_string())
93    }
94}
95
96impl From<std::io::Error> for ObservationPersistenceError {
97    fn from(error: std::io::Error) -> Self {
98        Self::Io(error)
99    }
100}
101
102pub(crate) fn validate_identity(
103    producer_instance: &str,
104    source_id: u64,
105) -> Result<(), ObservationPersistenceError> {
106    if source_id == 0
107        || !uuid::Uuid::parse_str(producer_instance)
108            .is_ok_and(|id| id.to_string() == producer_instance && !id.is_nil())
109    {
110        return Err(ObservationPersistenceError::InvalidRow(
111            "invalid producer instance or source ID".into(),
112        ));
113    }
114    Ok(())
115}
116
117/// Validate persisted metadata before either reader projects a payload.
118pub(crate) fn decode_row(
119    row: &rusqlite::Row<'_>,
120) -> Result<LocalObservationV1, ObservationPersistenceError> {
121    if row.get::<_, i64>(6)? != 1 {
122        return Err(ObservationPersistenceError::InvalidRow(
123            "unsupported local observation schema".into(),
124        ));
125    }
126    let cursor_id: i64 = row.get(0)?;
127    let source = LocalObservationSource::parse(row.get::<_, String>(1)?.as_str())?;
128    let source_id_raw: String = row.get(2)?;
129    let source_id = source_id_raw.parse::<u64>().map_err(|_| {
130        ObservationPersistenceError::InvalidRow("invalid source ID encoding".into())
131    })?;
132    let producer_instance: String = row.get(5)?;
133    validate_identity(&producer_instance, source_id)?;
134    if cursor_id <= 0 || source_id.to_string() != source_id_raw {
135        return Err(ObservationPersistenceError::InvalidRow(
136            "noncanonical observation identity".into(),
137        ));
138    }
139    let source_timestamp: String = row.get(3)?;
140    let payload_json: String = row.get(4)?;
141    let payload = match source {
142        LocalObservationSource::Ocla => {
143            if !source_timestamp
144                .parse::<u64>()
145                .is_ok_and(|value| value.to_string() == source_timestamp)
146            {
147                return Err(ObservationPersistenceError::InvalidRow(
148                    "invalid OCLA timestamp encoding".into(),
149                ));
150            }
151            LocalObservationPayload::Ocla(serde_json::from_str(&payload_json)?)
152        }
153        LocalObservationSource::Legacy => {
154            let event: LeanCtxEvent = serde_json::from_str(&payload_json)?;
155            if event.id != source_id || event.timestamp != source_timestamp {
156                return Err(ObservationPersistenceError::InvalidRow(
157                    "legacy payload contradicts observation identity or timestamp".into(),
158                ));
159            }
160            LocalObservationPayload::Legacy(event)
161        }
162    };
163    Ok(LocalObservationV1 {
164        cursor_id,
165        producer_instance,
166        source_id,
167        source_timestamp,
168        source,
169        payload,
170    })
171}
172
173pub(crate) fn producer_instance() -> &'static str {
174    static INSTANCE: OnceLock<String> = OnceLock::new();
175    INSTANCE.get_or_init(|| uuid::Uuid::new_v4().to_string())
176}
177
178/// Bound contention and reject poisoned state; callers never recover a guard.
179pub(crate) fn lock_observation<T>(
180    mutex: &Mutex<T>,
181) -> Result<MutexGuard<'_, T>, ObservationPersistenceError> {
182    let started = Instant::now();
183    loop {
184        match mutex.try_lock() {
185            Ok(guard) => return Ok(guard),
186            Err(TryLockError::Poisoned(_)) => {
187                return Err(ObservationPersistenceError::LockPoisoned);
188            }
189            Err(TryLockError::WouldBlock) => {
190                if started.elapsed() >= Duration::from_secs(5) {
191                    return Err(ObservationPersistenceError::LockTimeout);
192                }
193                std::thread::sleep(Duration::from_millis(1));
194            }
195        }
196    }
197}