Debian Codegraph @

third_party/rust/context_id/src/lib.rs

raw
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 mod error;
6
7 pub use error::{ApiError, ApiResult, Error, Result};
8
9 use chrono::{DateTime, Duration, Utc};
10 use error_support::{error, handle_error};
11 use parking_lot::{Mutex, RwLock};
12 use uuid::Uuid;
13
14 uniffi::setup_scaffolding!("context_id");
15
16 mod callback;
17 pub use callback::{ContextIdCallback, DefaultContextIdCallback};
18
19 mod mars;
20 use mars::{MARSClient, SimpleMARSClient};
21
22 /// Top-level API for the context_id component
23 #[derive(uniffi::Object)]
24 pub struct ContextIDComponent {
25 inner: Mutex<ContextIDComponentInner>,
26 }
27
28 #[uniffi::export]
29 impl ContextIDComponent {
30 /// Construct a new [ContextIDComponent].
31 ///
32 /// If no creation timestamp is provided, the current time will be used.
33 #[uniffi::constructor]
34 #[handle_error(Error)]
35 pub fn new(
36 init_context_id: &str,
37 creation_timestamp_s: i64,
38 running_in_test_automation: bool,
39 callback: Box<dyn ContextIdCallback>,
40 ) -> ApiResult<Self> {
41 Ok(Self {
42 inner: Mutex::new(ContextIDComponentInner::new(
43 init_context_id,
44 creation_timestamp_s,
45 running_in_test_automation,
46 callback,
47 Utc::now(),
48 Box::new(SimpleMARSClient::new()),
49 )?),
50 })
51 }
52
53 /// Return the current context ID string.
54 #[handle_error(Error)]
55 pub fn request(&self, rotation_days_in_s: u8) -> ApiResult<String> {
56 let mut inner = self.inner.lock();
57 inner.request(rotation_days_in_s, Utc::now())
58 }
59
60 /// Regenerate the context ID.
61 #[handle_error(Error)]
62 pub fn force_rotation(&self) -> ApiResult<()> {
63 let mut inner = self.inner.lock();
64 inner.force_rotation(Utc::now());
65 Ok(())
66 }
67
68 /// Unset the callbacks set during construction, and use a default
69 /// no-op ContextIdCallback instead.
70 #[handle_error(Error)]
71 pub fn unset_callback(&self) -> ApiResult<()> {
72 let mut inner = self.inner.lock();
73 inner.unset_callback();
74 Ok(())
75 }
76 }
77
78 struct ContextIDComponentInner {
79 context_id: String,
80 creation_timestamp: DateTime<Utc>,
81 callback_handle: RwLock<Box<dyn ContextIdCallback>>,
82 mars_client: Box<dyn MARSClient>,
83 running_in_test_automation: bool,
84 }
85
86 impl ContextIDComponentInner {
87 pub fn new(
88 init_context_id: &str,
89 creation_timestamp_s: i64,
90 running_in_test_automation: bool,
91 callback: Box<dyn ContextIdCallback>,
92 now: DateTime<Utc>,
93 mars_client: Box<dyn MARSClient>,
94 ) -> Result<Self> {
95 // Some historical context IDs are stored within opening and closing
96 // braces, and our endpoints have tolerated this, but ideally we'd
97 // send without the braces, so we strip any off here.
98 let (context_id, generated_context_id) = match init_context_id
99 .trim()
100 .trim_start_matches('{')
101 .trim_end_matches('}')
102 {
103 "" => (Uuid::new_v4().to_string(), true),
104 // If the passed in string isn't empty, but still not a valid UUID,
105 // just go ahead and generate a new UUID.
106 s => match Uuid::parse_str(s) {
107 Ok(_) => (s.to_string(), false),
108 Err(_) => (Uuid::new_v4().to_string(), true),
109 },
110 };
111
112 let (creation_timestamp, generated_creation_timestamp) = if generated_context_id {
113 // If we had to generate a UUID, also force a new timestamp.
114 (now, true)
115 } else {
116 match creation_timestamp_s {
117 secs if secs > 0 => (
118 DateTime::<Utc>::from_timestamp(secs, 0)
119 .ok_or(Error::InvalidTimestamp { timestamp: secs })?,
120 false,
121 ),
122 _ => (now, true),
123 }
124 };
125
126 let instance = Self {
127 context_id,
128 creation_timestamp,
129 callback_handle: RwLock::new(callback),
130 mars_client,
131 running_in_test_automation,
132 };
133
134 // We only need to persist these if we just generated one.
135 if generated_context_id || generated_creation_timestamp {
136 instance.persist();
137 }
138
139 Ok(instance)
140 }
141
142 pub fn request(&mut self, rotation_days: u8, now: DateTime<Utc>) -> Result<String> {
143 if rotation_days == 0 {
144 return Ok(self.context_id.clone());
145 }
146
147 let age = now - self.creation_timestamp;
148 if age >= Duration::days(rotation_days.into()) {
149 self.rotate_context_id(now);
150 }
151
152 Ok(self.context_id.clone())
153 }
154
155 pub fn rotate_context_id(&mut self, now: DateTime<Utc>) {
156 let original_context_id = self.context_id.clone();
157
158 self.context_id = Uuid::new_v4().to_string();
159 self.creation_timestamp = now;
160 self.persist();
161
162 // If we're running in test automation in the embedder, we don't want
163 // to be sending actual network requests to MARS.
164 if !self.running_in_test_automation {
165 let _ = self
166 .mars_client
167 .delete(original_context_id.clone())
168 .inspect_err(|e| error!("Failed to contact MARS: {}", e));
169 }
170
171 // In a perfect world, we'd call Glean ourselves here - however,
172 // our uniffi / Rust infrastructure doesn't yet support doing that,
173 // so we'll delegate to our embedder to send the Glean ping by
174 // calling a `rotated` callback method.
175 self.callback_handle
176 .read()
177 .rotated(original_context_id.clone());
178 }
179
180 pub fn force_rotation(&mut self, now: DateTime<Utc>) {
181 self.rotate_context_id(now);
182 }
183
184 pub fn persist(&self) {
185 self.callback_handle
186 .read()
187 .persist(self.context_id.clone(), self.creation_timestamp.timestamp());
188 }
189
190 pub fn unset_callback(&mut self) {
191 self.callback_handle = RwLock::new(Box::new(DefaultContextIdCallback));
192 }
193 }
194
195 #[cfg(test)]
196 mod tests {
197 use super::*;
198 use chrono::Utc;
199 use lazy_static::lazy_static;
200
201 use std::sync::{Arc, Mutex};
202
203 // 1745859061 ~= the timestamp for when this test was written (Apr 28, 2025)
204 const FAKE_NOW_TS: i64 = 1745859061;
205 const TEST_CONTEXT_ID: &str = "decafbad-0cd1-0cd2-0cd3-decafbad1000";
206 // 1706763600 ~= Jan 1st, 2024, which is long ago compared to FAKE_NOW.
207 const FAKE_LONG_AGO_TS: i64 = 1706763600;
208
209 lazy_static! {
210 static ref FAKE_NOW: DateTime<Utc> = DateTime::from_timestamp(FAKE_NOW_TS, 0).unwrap();
211 static ref FAKE_LONG_AGO: DateTime<Utc> =
212 DateTime::from_timestamp(FAKE_LONG_AGO_TS, 0).unwrap();
213 }
214
215 pub struct TestMARSClient {
216 delete_called: Arc<Mutex<bool>>,
217 }
218
219 impl TestMARSClient {
220 pub fn new(delete_called: Arc<Mutex<bool>>) -> Self {
221 Self { delete_called }
222 }
223 }
224
225 impl MARSClient for TestMARSClient {
226 fn delete(&self, _context_id: String) -> crate::Result<()> {
227 *self.delete_called.lock().unwrap() = true;
228 Ok(())
229 }
230 }
231
232 fn with_test_mars<F: FnOnce(Box<dyn MARSClient + Send + Sync>, Arc<Mutex<bool>>)>(test: F) {
233 let delete_called = Arc::new(Mutex::new(false));
234 let mars = Box::new(TestMARSClient::new(Arc::clone(&delete_called)));
235 test(mars, delete_called);
236 }
237
238 #[test]
239 fn test_creation_timestamp_with_some_value() {
240 with_test_mars(|mars, delete_called| {
241 let creation_timestamp = FAKE_NOW_TS;
242 let component = ContextIDComponentInner::new(
243 TEST_CONTEXT_ID,
244 creation_timestamp,
245 false,
246 Box::new(DefaultContextIdCallback),
247 *FAKE_NOW,
248 mars,
249 )
250 .unwrap();
251
252 // We should have left the context_id and creation_timestamp
253 // untouched if a creation_timestamp was passed.
254 assert_eq!(component.context_id, TEST_CONTEXT_ID);
255 assert_eq!(component.creation_timestamp.timestamp(), creation_timestamp);
256 assert!(!*delete_called.lock().unwrap());
257 });
258 }
259
260 #[test]
261 fn test_creation_timestamp_with_zero_value() {
262 with_test_mars(|mars, delete_called| {
263 let component = ContextIDComponentInner::new(
264 TEST_CONTEXT_ID,
265 0,
266 false,
267 Box::new(DefaultContextIdCallback),
268 *FAKE_NOW,
269 mars,
270 )
271 .unwrap();
272
273 // If 0 was passed as the creation_timestamp, we'll interpret that
274 // as there having been no stored creation_timestamp. In that case,
275 // we'll use "now" as the creation_timestamp.
276 assert_eq!(component.context_id, TEST_CONTEXT_ID);
277 assert_eq!(component.creation_timestamp, FAKE_NOW.clone());
278 assert!(!*delete_called.lock().unwrap());
279 });
280 }
281
282 #[test]
283 fn test_empty_initial_context_id() {
284 with_test_mars(|mars, delete_called| {
285 let component = ContextIDComponentInner::new(
286 "",
287 0,
288 false,
289 Box::new(DefaultContextIdCallback),
290 *FAKE_NOW,
291 mars,
292 )
293 .unwrap();
294
295 // We expect a new UUID to have been generated for context_id.
296 assert!(Uuid::parse_str(&component.context_id).is_ok());
297 assert_eq!(component.creation_timestamp, FAKE_NOW.clone());
298 assert!(!*delete_called.lock().unwrap());
299 });
300 }
301
302 #[test]
303 fn test_empty_initial_context_id_with_creation_date() {
304 with_test_mars(|mars, delete_called| {
305 let component = ContextIDComponentInner::new(
306 "",
307 0,
308 false,
309 Box::new(DefaultContextIdCallback),
310 *FAKE_NOW,
311 mars,
312 )
313 .unwrap();
314
315 // We expect a new UUID to have been generated for context_id.
316 assert!(Uuid::parse_str(&component.context_id).is_ok());
317 assert_eq!(component.creation_timestamp, FAKE_NOW.clone());
318 assert!(!*delete_called.lock().unwrap());
319 });
320 }
321
322 #[test]
323 fn test_invalid_context_id_with_no_creation_date() {
324 with_test_mars(|mars, delete_called| {
325 let component = ContextIDComponentInner::new(
326 "something-invalid",
327 0,
328 false,
329 Box::new(DefaultContextIdCallback),
330 *FAKE_NOW,
331 mars,
332 )
333 .unwrap();
334
335 // We expect a new UUID to have been generated for context_id.
336 assert!(Uuid::parse_str(&component.context_id).is_ok());
337 assert_eq!(component.creation_timestamp, FAKE_NOW.clone());
338 assert!(!*delete_called.lock().unwrap());
339 });
340 }
341
342 #[test]
343 fn test_invalid_context_id_with_creation_date() {
344 with_test_mars(|mars, delete_called| {
345 let component = ContextIDComponentInner::new(
346 "something-invalid",
347 FAKE_LONG_AGO_TS,
348 false,
349 Box::new(DefaultContextIdCallback),
350 *FAKE_NOW,
351 mars,
352 )
353 .unwrap();
354
355 // We expect a new UUID to have been generated for context_id.
356 assert!(Uuid::parse_str(&component.context_id).is_ok());
357 assert_eq!(component.creation_timestamp, FAKE_NOW.clone());
358 assert!(!*delete_called.lock().unwrap());
359 });
360 }
361
362 #[test]
363 fn test_request_no_rotation() {
364 with_test_mars(|mars, delete_called| {
365 // Let's create a context_id with a creation date far in the past.
366 let mut component = ContextIDComponentInner::new(
367 TEST_CONTEXT_ID,
368 FAKE_LONG_AGO_TS,
369 false,
370 Box::new(DefaultContextIdCallback),
371 *FAKE_NOW,
372 mars,
373 )
374 .unwrap();
375
376 // We expect neither the UUID nor creation_timestamp to have been changed.
377 assert_eq!(component.context_id, TEST_CONTEXT_ID);
378 assert_eq!(component.creation_timestamp, FAKE_LONG_AGO.clone());
379
380 // Now request the context_id, passing 0 for the rotation_days. We
381 // interpret this to mean "do not rotate".
382 assert_eq!(
383 component.request(0, *FAKE_NOW).unwrap(),
384 component.context_id
385 );
386 assert_eq!(component.creation_timestamp, FAKE_LONG_AGO.clone());
387 assert!(!*delete_called.lock().unwrap());
388 });
389 }
390
391 #[test]
392 fn test_request_with_rotation() {
393 with_test_mars(|mars, delete_called| {
394 struct FakeContextIdCallback {
395 rotated_called: Arc<Mutex<bool>>,
396 original_context_id: Arc<Mutex<Option<String>>>,
397 }
398
399 impl ContextIdCallback for FakeContextIdCallback {
400 fn persist(&self, _context_id: String, _creation_date: i64) {}
401
402 fn rotated(&self, original_context_id: String) {
403 *self.rotated_called.lock().unwrap() = true;
404 *self.original_context_id.lock().unwrap() = Some(original_context_id);
405 }
406 }
407
408 let rotated_called_flag = Arc::new(Mutex::new(false));
409 let original_context_id = Arc::new(Mutex::new(None));
410
411 let callback = FakeContextIdCallback {
412 rotated_called: Arc::clone(&rotated_called_flag),
413 original_context_id: Arc::clone(&original_context_id),
414 };
415
416 // Let's create a context_id with a creation date far in the past.
417 let mut component = ContextIDComponentInner::new(
418 TEST_CONTEXT_ID,
419 FAKE_LONG_AGO_TS,
420 false,
421 Box::new(callback),
422 *FAKE_NOW,
423 mars,
424 )
425 .unwrap();
426
427 // We expect neither the UUID nor creation_timestamp to have been changed.
428 assert_eq!(component.context_id, TEST_CONTEXT_ID);
429 assert_eq!(component.creation_timestamp, FAKE_LONG_AGO.clone());
430
431 // Now request the context_id, passing 2 for the rotation_days. Since
432 // the number of days since FAKE_LONG_AGO is greater than 2 days, we
433 // expect a new context_id to be generated, and the creation_timestamp
434 // to update to now.
435 assert!(Uuid::parse_str(&component.request(2, *FAKE_NOW).unwrap()).is_ok());
436 assert_ne!(component.context_id, TEST_CONTEXT_ID);
437 assert_eq!(component.creation_timestamp, FAKE_NOW.clone());
438 assert!(*delete_called.lock().unwrap());
439
440 assert!(
441 *rotated_called_flag.lock().unwrap(),
442 "rotated() should have been called"
443 );
444 assert_eq!(
445 original_context_id.lock().unwrap().as_deref().unwrap(),
446 TEST_CONTEXT_ID
447 );
448 });
449 }
450
451 #[test]
452 fn test_force_rotation() {
453 with_test_mars(|mars, delete_called| {
454 struct FakeContextIdCallback {
455 rotated_called: Arc<Mutex<bool>>,
456 original_context_id: Arc<Mutex<Option<String>>>,
457 }
458
459 impl ContextIdCallback for FakeContextIdCallback {
460 fn persist(&self, _context_id: String, _creation_date: i64) {}
461
462 fn rotated(&self, original_context_id: String) {
463 *self.rotated_called.lock().unwrap() = true;
464 *self.original_context_id.lock().unwrap() = Some(original_context_id);
465 }
466 }
467
468 let rotated_called_flag = Arc::new(Mutex::new(false));
469 let original_context_id = Arc::new(Mutex::new(None));
470
471 let callback = FakeContextIdCallback {
472 rotated_called: Arc::clone(&rotated_called_flag),
473 original_context_id: Arc::clone(&original_context_id),
474 };
475
476 let mut component = ContextIDComponentInner::new(
477 TEST_CONTEXT_ID,
478 FAKE_LONG_AGO_TS,
479 false,
480 Box::new(callback),
481 *FAKE_NOW,
482 mars,
483 )
484 .unwrap();
485
486 component.force_rotation(*FAKE_NOW);
487 assert!(Uuid::parse_str(&component.request(2, *FAKE_NOW).unwrap()).is_ok());
488 assert_ne!(component.context_id, TEST_CONTEXT_ID);
489 assert_eq!(component.creation_timestamp, FAKE_NOW.clone());
490 assert!(*delete_called.lock().unwrap());
491 assert!(
492 *rotated_called_flag.lock().unwrap(),
493 "rotated() should have been called"
494 );
495 assert_eq!(
496 original_context_id.lock().unwrap().as_deref().unwrap(),
497 TEST_CONTEXT_ID
498 );
499 });
500 }
501
502 #[test]
503 fn test_accept_braces() {
504 with_test_mars(|mars, delete_called| {
505 // Some callers may store pre-existing context IDs with opening
506 // and closing curly braces. Our component should accept them, but
507 // return (and persist) UUIDs without such braces.
508 let wrapped_context_id = ["{", TEST_CONTEXT_ID, "}"].concat();
509 let mut component = ContextIDComponentInner::new(
510 &wrapped_context_id,
511 0,
512 false,
513 Box::new(DefaultContextIdCallback),
514 *FAKE_NOW,
515 mars,
516 )
517 .unwrap();
518
519 // We expect to be storing TEST_CONTEXT_ID, and to return
520 // TEST_CONTEXT_ID without the braces.
521 assert_eq!(component.context_id, TEST_CONTEXT_ID);
522 assert!(Uuid::parse_str(&component.request(0, *FAKE_NOW).unwrap()).is_ok());
523 assert!(!*delete_called.lock().unwrap());
524 });
525 }
526
527 #[test]
528 fn test_persist_callback() {
529 with_test_mars(|mars, delete_called| {
530 struct FakeContextIdCallback {
531 persist_called: Arc<Mutex<bool>>,
532 context_id: Arc<Mutex<Option<String>>>,
533 creation_timestamp: Arc<Mutex<Option<i64>>>,
534 }
535
536 impl ContextIdCallback for FakeContextIdCallback {
537 fn persist(&self, context_id: String, creation_date: i64) {
538 *self.persist_called.lock().unwrap() = true;
539 *self.context_id.lock().unwrap() = Some(context_id);
540 *self.creation_timestamp.lock().unwrap() = Some(creation_date);
541 }
542
543 fn rotated(&self, _original_context_id: String) {}
544 }
545
546 let persist_called_flag = Arc::new(Mutex::new(false));
547 let context_id = Arc::new(Mutex::new(None));
548 let creation_timestamp = Arc::new(Mutex::new(None));
549
550 let callback = FakeContextIdCallback {
551 persist_called: Arc::clone(&persist_called_flag),
552 context_id: Arc::clone(&context_id),
553 creation_timestamp: Arc::clone(&creation_timestamp),
554 };
555
556 let mut component = ContextIDComponentInner::new(
557 TEST_CONTEXT_ID,
558 FAKE_LONG_AGO_TS,
559 false,
560 Box::new(callback),
561 *FAKE_NOW,
562 mars,
563 )
564 .unwrap();
565
566 component.force_rotation(*FAKE_NOW);
567
568 assert!(
569 *persist_called_flag.lock().unwrap(),
570 "persist() should have been called"
571 );
572
573 assert!(
574 Uuid::parse_str(context_id.lock().unwrap().as_deref().unwrap()).is_ok(),
575 "persist() should have received a valid context_id string"
576 );
577
578 assert_eq!(
579 *creation_timestamp.lock().unwrap(),
580 Some(FAKE_NOW_TS),
581 "persist() should have received the expected creation date"
582 );
583 assert!(*delete_called.lock().unwrap());
584 });
585 }
586 }