context_id/
callback.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5#[uniffi::export(callback_interface)]
6pub trait ContextIdCallback: Sync + Send {
7    fn persist(&self, context_id: String, creation_date: i64);
8    fn rotated(&self, old_context_id: String);
9}
10
11pub struct DefaultContextIdCallback;
12impl ContextIdCallback for DefaultContextIdCallback {
13    fn persist(&self, _context_id: String, _creation_date: i64) {}
14    fn rotated(&self, _old_context_id: String) {}
15}
16
17#[cfg(test)]
18pub mod utils {
19    use super::ContextIdCallback;
20    use std::sync::{Arc, Mutex};
21    /// A spy callback for tests that counts persist/rotate calls,
22    /// captures the last rotated ID, and records the last creation timestamp.
23    pub struct SpyCallback {
24        pub callback: Box<dyn ContextIdCallback + Send + Sync>,
25        pub persist_called: Arc<Mutex<u32>>,
26        pub rotated_called: Arc<Mutex<u32>>,
27        pub last_rotated_id: Arc<Mutex<Option<String>>>,
28        pub last_persist_ts: Arc<Mutex<Option<i64>>>,
29    }
30
31    impl SpyCallback {
32        pub fn new() -> Self {
33            let persist_called = Arc::new(Mutex::new(0));
34            let rotated_called = Arc::new(Mutex::new(0));
35            let last_rotated_id = Arc::new(Mutex::new(None));
36            let last_persist_ts = Arc::new(Mutex::new(None));
37
38            let inner = SpyCallbackInner {
39                persist_called: Arc::clone(&persist_called),
40                rotated_called: Arc::clone(&rotated_called),
41                last_rotated_id: Arc::clone(&last_rotated_id),
42                last_persist_ts: Arc::clone(&last_persist_ts),
43            };
44
45            SpyCallback {
46                callback: Box::new(inner),
47                persist_called,
48                rotated_called,
49                last_rotated_id,
50                last_persist_ts,
51            }
52        }
53    }
54
55    struct SpyCallbackInner {
56        persist_called: Arc<Mutex<u32>>,
57        rotated_called: Arc<Mutex<u32>>,
58        last_rotated_id: Arc<Mutex<Option<String>>>,
59        last_persist_ts: Arc<Mutex<Option<i64>>>,
60    }
61
62    impl ContextIdCallback for SpyCallbackInner {
63        fn persist(&self, _ctx: String, ts: i64) {
64            *self.persist_called.lock().unwrap() += 1;
65            *self.last_persist_ts.lock().unwrap() = Some(ts);
66        }
67        fn rotated(&self, old_ctx: String) {
68            *self.rotated_called.lock().unwrap() += 1;
69            *self.last_rotated_id.lock().unwrap() = Some(old_ctx);
70        }
71    }
72}