arqen 0.11.3

Backend infrastructure for agent-ready applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Optional read-through caching for any [`ThingdBackend`].

use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use async_trait::async_trait;
use serde_json::Value;

use crate::core::AppError;
use crate::observability::{NoopMetricsSink, SharedMetricsSink};
use crate::thingd::{
    QueryOptions, SearchOptions, SearchResults, ThingdBackend, ThingdEvent, ThingdJob, ThingdLink,
    ThingdObject, ThingdOperation, ThingdOperationResult,
};

/// Limits and expiry settings for [`CachingThingdBackend`].
#[derive(Debug, Clone)]
pub struct CachePolicy {
    pub ttl: Duration,
    pub capacity: usize,
}

impl Default for CachePolicy {
    fn default() -> Self {
        Self {
            ttl: Duration::from_secs(30),
            capacity: 1_024,
        }
    }
}

struct CacheState {
    expires: Mutex<HashMap<String, Instant>>,
    gates: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
}

/// A backend decorator that caches object reads while delegating all other
/// operations to `source`. Writes invalidate the cached object first.
///
/// Prefer [`CachingThingdBackend::new_catalog`] for production configuration.
pub struct CachingThingdBackend {
    source: Arc<dyn ThingdBackend>,
    cache: Arc<dyn ThingdBackend>,
    policy: CachePolicy,
    state: CacheState,
    hits: AtomicU64,
    misses: AtomicU64,
    metrics: SharedMetricsSink,
    allowed_collections: Option<Arc<HashSet<String>>>,
}

impl CachingThingdBackend {
    pub fn new(
        source: Arc<dyn ThingdBackend>,
        cache: Arc<dyn ThingdBackend>,
        policy: CachePolicy,
    ) -> Self {
        Self::new_with_metrics(source, cache, policy, Arc::new(NoopMetricsSink))
    }

    pub fn new_with_metrics(
        source: Arc<dyn ThingdBackend>,
        cache: Arc<dyn ThingdBackend>,
        policy: CachePolicy,
        metrics: SharedMetricsSink,
    ) -> Self {
        Self {
            source,
            cache,
            policy,
            state: CacheState {
                expires: Mutex::new(HashMap::new()),
                gates: Mutex::new(HashMap::new()),
            },
            hits: AtomicU64::new(0),
            misses: AtomicU64::new(0),
            metrics,
            allowed_collections: None,
        }
    }

    /// Construct a cache restricted to an explicit catalog collection allowlist.
    ///
    /// This is the safe variant for HTTP and multi-user deployments. A cache
    /// must never be enabled for user-scoped collections unless the caller has
    /// separately guaranteed that the collection contains no tenant data.
    pub fn new_catalog(
        source: Arc<dyn ThingdBackend>,
        cache: Arc<dyn ThingdBackend>,
        policy: CachePolicy,
        collections: impl IntoIterator<Item = String>,
    ) -> Self {
        let mut backend = Self::new(source, cache, policy);
        backend.allowed_collections = Some(Arc::new(collections.into_iter().collect()));
        backend
    }

    pub fn cache_hits(&self) -> u64 {
        self.hits.load(Ordering::Relaxed)
    }
    pub fn cache_misses(&self) -> u64 {
        self.misses.load(Ordering::Relaxed)
    }

    fn key(collection: &str, id: &str) -> String {
        format!("{collection}\0{id}")
    }

    fn cache_collection(&self, collection: &str) -> bool {
        self.allowed_collections
            .as_ref()
            .is_none_or(|collections| collections.contains(collection))
    }

    async fn gate(&self, key: &str) -> Arc<tokio::sync::Mutex<()>> {
        let mut gates = self.state.gates.lock().expect("cache gate mutex poisoned");
        gates
            .entry(key.to_string())
            .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
            .clone()
    }

    fn fresh(&self, key: &str) -> bool {
        self.state
            .expires
            .lock()
            .expect("cache expiry mutex poisoned")
            .get(key)
            .is_some_and(|expiry| *expiry > Instant::now())
    }

    async fn invalidate(&self, collection: &str, id: &str) -> Result<(), AppError> {
        let key = Self::key(collection, id);
        self.cache.delete_object(collection, id).await?;
        self.state
            .expires
            .lock()
            .expect("cache expiry mutex poisoned")
            .remove(&key);
        Ok(())
    }

    async fn cache_object(&self, object: &ThingdObject) -> Result<(), AppError> {
        if self.policy.capacity == 0 {
            return Ok(());
        }
        let key = Self::key(&object.collection, &object.id);
        self.cache
            .put_object(&object.collection, &object.id, object.data.clone())
            .await?;
        let evicted = {
            let expires = self
                .state
                .expires
                .lock()
                .expect("cache expiry mutex poisoned");
            if expires.len() >= self.policy.capacity && !expires.contains_key(&key) {
                expires
                    .iter()
                    .min_by_key(|(_, expiry)| **expiry)
                    .map(|(k, _)| k.clone())
            } else {
                None
            }
        };
        if let Some(oldest) = &evicted {
            if let Some((collection, id)) = oldest.split_once('\0') {
                let _ = self.cache.delete_object(collection, id).await;
            }
            self.state
                .expires
                .lock()
                .expect("cache expiry mutex poisoned")
                .remove(oldest);
            self.metrics
                .record_cache(crate::observability::CacheMetric {
                    operation: "eviction".to_string(),
                    hit: false,
                    duration_ms: 0,
                });
        }
        self.state
            .expires
            .lock()
            .expect("cache expiry mutex poisoned")
            .insert(key, Instant::now() + self.policy.ttl);
        Ok(())
    }
}

#[async_trait]
impl ThingdBackend for CachingThingdBackend {
    async fn get_object(
        &self,
        collection: &str,
        id: &str,
    ) -> Result<Option<ThingdObject>, AppError> {
        if !self.cache_collection(collection) {
            return self.source.get_object(collection, id).await;
        }
        let started = Instant::now();
        let key = Self::key(collection, id);
        if self.fresh(&key)
            && let Some(object) = self.cache.get_object(collection, id).await?
        {
            self.hits.fetch_add(1, Ordering::Relaxed);
            self.metrics
                .record_cache(crate::observability::CacheMetric {
                    operation: "get".to_string(),
                    hit: true,
                    duration_ms: started.elapsed().as_millis() as u64,
                });
            return Ok(Some(object));
        }
        let gate = self.gate(&key).await;
        let _guard = gate.lock().await;
        if self.fresh(&key)
            && let Some(object) = self.cache.get_object(collection, id).await?
        {
            self.hits.fetch_add(1, Ordering::Relaxed);
            self.metrics
                .record_cache(crate::observability::CacheMetric {
                    operation: "get".to_string(),
                    hit: true,
                    duration_ms: started.elapsed().as_millis() as u64,
                });
            return Ok(Some(object));
        }
        self.misses.fetch_add(1, Ordering::Relaxed);
        self.metrics
            .record_cache(crate::observability::CacheMetric {
                operation: "get".to_string(),
                hit: false,
                duration_ms: started.elapsed().as_millis() as u64,
            });
        let object = self.source.get_object(collection, id).await?;
        if let Some(object) = &object {
            self.cache_object(object).await?;
        }
        Ok(object)
    }

    async fn put_object(
        &self,
        collection: &str,
        id: &str,
        data: Value,
    ) -> Result<ThingdObject, AppError> {
        self.invalidate(collection, id).await?;
        self.source.put_object(collection, id, data).await
    }
    async fn delete_object(&self, collection: &str, id: &str) -> Result<(), AppError> {
        self.invalidate(collection, id).await?;
        self.source.delete_object(collection, id).await
    }
    async fn query_objects(
        &self,
        collection: &str,
        options: QueryOptions,
    ) -> Result<Vec<ThingdObject>, AppError> {
        self.source.query_objects(collection, options).await
    }
    async fn count_objects(&self, collection: &str) -> Result<usize, AppError> {
        self.source.count_objects(collection).await
    }
    async fn batch_write(
        &self,
        operations: Vec<ThingdOperation>,
    ) -> Result<Vec<ThingdOperationResult>, AppError> {
        for operation in &operations {
            match operation {
                ThingdOperation::Put { collection, id, .. }
                | ThingdOperation::Delete { collection, id } => {
                    self.invalidate(collection, id).await?
                }
            }
        }
        self.source.batch_write(operations).await
    }
    async fn append_event(
        &self,
        stream: &str,
        event_type: &str,
        data: Value,
    ) -> Result<ThingdEvent, AppError> {
        self.source.append_event(stream, event_type, data).await
    }
    async fn read_events(
        &self,
        stream: &str,
        from: Option<String>,
        limit: usize,
    ) -> Result<Vec<ThingdEvent>, AppError> {
        self.source.read_events(stream, from, limit).await
    }
    async fn push_job(
        &self,
        queue: &str,
        payload: Value,
        max_retries: u32,
    ) -> Result<ThingdJob, AppError> {
        self.source.push_job(queue, payload, max_retries).await
    }
    async fn claim_job(
        &self,
        queue: &str,
        worker_id: &str,
        lease_seconds: u32,
    ) -> Result<Option<ThingdJob>, AppError> {
        self.source.claim_job(queue, worker_id, lease_seconds).await
    }
    async fn complete_job(&self, queue: &str, job_id: &str) -> Result<(), AppError> {
        self.source.complete_job(queue, job_id).await
    }
    async fn nack_job(&self, queue: &str, job_id: &str) -> Result<(), AppError> {
        self.source.nack_job(queue, job_id).await
    }
    async fn dead_letter_job(&self, queue: &str, job_id: &str) -> Result<(), AppError> {
        self.source.dead_letter_job(queue, job_id).await
    }
    async fn search(&self, query: &str, options: SearchOptions) -> Result<SearchResults, AppError> {
        self.source.search(query, options).await
    }
    async fn create_link(
        &self,
        source_id: &str,
        target_id: &str,
        relation: &str,
    ) -> Result<ThingdLink, AppError> {
        self.source
            .create_link(source_id, target_id, relation)
            .await
    }
    async fn get_links(
        &self,
        source_id: &str,
        relation: Option<&str>,
    ) -> Result<Vec<ThingdLink>, AppError> {
        self.source.get_links(source_id, relation).await
    }
    async fn delete_link(&self, link_id: &str) -> Result<(), AppError> {
        self.source.delete_link(link_id).await
    }
    async fn reset(&self) -> Result<(), AppError> {
        self.source.reset().await
    }
    async fn seed(&self) -> Result<(), AppError> {
        self.source.seed().await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::thingd::{MemoryThingdBackend, ThingdBackend};

    #[tokio::test]
    async fn read_through_cache_hits_and_invalidates_on_write() {
        let source: Arc<dyn ThingdBackend> = Arc::new(MemoryThingdBackend::new());
        let cache: Arc<dyn ThingdBackend> = Arc::new(MemoryThingdBackend::new());
        source
            .put_object("movies", "m-1", serde_json::json!({"title":"Before"}))
            .await
            .unwrap();
        let backend = CachingThingdBackend::new(
            source,
            cache,
            CachePolicy {
                ttl: Duration::from_secs(60),
                capacity: 10,
            },
        );

        assert_eq!(
            backend
                .get_object("movies", "m-1")
                .await
                .unwrap()
                .unwrap()
                .data["title"],
            "Before"
        );
        assert_eq!(
            backend
                .get_object("movies", "m-1")
                .await
                .unwrap()
                .unwrap()
                .data["title"],
            "Before"
        );
        assert_eq!(backend.cache_misses(), 1);
        assert_eq!(backend.cache_hits(), 1);

        backend
            .put_object("movies", "m-1", serde_json::json!({"title":"After"}))
            .await
            .unwrap();
        assert_eq!(
            backend
                .get_object("movies", "m-1")
                .await
                .unwrap()
                .unwrap()
                .data["title"],
            "After"
        );
        assert_eq!(backend.cache_misses(), 2);
    }

    #[tokio::test]
    async fn catalog_cache_bypasses_non_allowlisted_collections() {
        let source: Arc<dyn ThingdBackend> = Arc::new(MemoryThingdBackend::new());
        let cache: Arc<dyn ThingdBackend> = Arc::new(MemoryThingdBackend::new());
        source
            .put_object("catalog", "one", serde_json::json!({"title":"Catalog"}))
            .await
            .unwrap();
        source
            .put_object("users", "one", serde_json::json!({"name":"User"}))
            .await
            .unwrap();
        let backend = CachingThingdBackend::new_catalog(
            source,
            cache,
            CachePolicy::default(),
            ["catalog".to_string()],
        );

        backend.get_object("catalog", "one").await.unwrap();
        backend.get_object("catalog", "one").await.unwrap();
        backend.get_object("users", "one").await.unwrap();
        backend.get_object("users", "one").await.unwrap();

        assert_eq!(backend.cache_hits(), 1);
        assert_eq!(backend.cache_misses(), 1);
    }
}