antimatter 2.0.13

antimatter.io Rust library for data control
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
use crate::session::session::SessionError;
use crate::session::RUNTIME;
use antimatter_api::apis::configuration;
use antimatter_api::apis::internal_api::{self as api};
use antimatter_api::models::*;
use lru::LruCache;
use std::cmp::max;
use std::mem;
use std::num::NonZeroUsize;
use std::sync::{Arc, Mutex};
use tokio::task::JoinHandle;

type InvokeFunc = Arc<
    dyn Fn(
            configuration::Configuration,
            String,
            String,
            String,
            CapsuleSealRequest,
        ) -> Result<(), SessionError>
        + Send
        + Sync,
>;

// invoke_request is a wrapper for the domain seal capsule. By returning a
// boxed future, we can store a reference to it that can be checked later for
// completion.
fn invoke_request(
    configuration: configuration::Configuration,
    domain_id: String,
    id: String,
    create_token: String,
    seal_request: CapsuleSealRequest,
) -> Result<(), SessionError> {
    let c = configuration.clone();
    RUNTIME
        .block_on(api::domain_seal_capsule(
            &c,
            &domain_id,
            &id,
            &create_token,
            seal_request,
        ))
        .map_err(|e| SessionError::APIError(format!("invoke seal error: {:?}", e)))
}

#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct SealKey {
    domain_id: String,
    id: String,
    create_token: String,
}

pub struct SealCache {
    cache: LruCache<SealKey, BufferedSealInternal>,
    seal_invoker: InvokeFunc,
    enabled: bool,
    size: usize,
}

impl SealCache {
    pub fn new(size: usize, is_async: bool) -> Self {
        let cache_size = NonZeroUsize::new(size).unwrap_or_else(|| NonZeroUsize::new(100).unwrap());
        Self {
            cache: LruCache::new(cache_size),
            seal_invoker: Arc::new(invoke_request),
            enabled: is_async,
            size,
        }
    }

    pub fn seal(
        &mut self,
        configuration: &configuration::Configuration,
        domain_id: String,
        id: String,
        create_token: String,
        request: &mut CapsuleSealRequest,
        async_seal: bool,
    ) -> Result<(), SessionError> {
        let key = SealKey {
            domain_id: domain_id.to_string(),
            id: id.to_string(),
            create_token: create_token.to_string(),
        };

        let buff = match self.cache.get_mut(&key) {
            None => {
                let new_buff = BufferedSealInternal::new(
                    configuration.clone(),
                    domain_id.clone(),
                    id.clone(),
                    create_token.clone(),
                    self.seal_invoker.clone(),
                );
                self.cache.push(key.clone(), new_buff);
                self.cache.get_mut(&key).unwrap()
            }
            Some(v) => v,
        };

        if !self.enabled || !async_seal {
            buff.seal(
                &mut request.span_tags.unique_tags,
                &mut request.span_tags.elided_tags,
                &mut request.capsule_tags,
                request.size,
                request.rows,
            )
        } else {
            buff.seal_async(
                &mut request.span_tags.unique_tags,
                &mut request.span_tags.elided_tags,
                &mut request.capsule_tags,
                request.size,
                request.rows,
            )
        }
    }

    pub fn update_tags_for_seal(
        &mut self,
        configuration: &configuration::Configuration,
        domain_id: String,
        id: String,
        create_token: String,
        request: &mut CapsuleSealRequest,
    ) -> Result<(), SessionError> {
        let key = SealKey {
            domain_id: domain_id.to_string(),
            id: id.to_string(),
            create_token: create_token.to_string(),
        };

        let buff = match self.cache.get_mut(&key) {
            None => {
                let new_buff = BufferedSealInternal::new(
                    configuration.clone(),
                    domain_id.clone(),
                    id.clone(),
                    create_token.clone(),
                    self.seal_invoker.clone(),
                );
                self.cache.push(key.clone(), new_buff);
                self.cache.get_mut(&key).unwrap()
            }
            Some(v) => v,
        };
        buff.update_tags_for_seal(
            &mut request.span_tags.unique_tags,
            &mut request.span_tags.elided_tags,
            &mut request.capsule_tags,
            request.size,
            request.rows,
        );
        Ok(())
    }

    pub fn size(&self) -> usize {
        self.size
    }

    pub fn enabled(&self) -> bool {
        self.enabled
    }
}

struct BufferedSealInternal {
    configuration: configuration::Configuration,
    domain_id: String,
    id: String,
    create_token: String,
    active_request: Option<JoinHandle<Result<(), SessionError>>>,
    pub seal_invoker: InvokeFunc,
    request: Arc<Mutex<Option<CapsuleSealRequest>>>,
    first: bool,
}

impl Drop for BufferedSealInternal {
    fn drop(&mut self) {
        match self.complete() {
            Ok(_) => {}
            // TODO: this happens during the cleanup phase, i dont know how to propagate the error out
            Err(e) => {
                println!("error handling tail seal event: {:}", e)
            }
        }
    }
}

impl BufferedSealInternal {
    pub fn new(
        configuration: configuration::Configuration,
        domain_id: String,
        id: String,
        create_token: String,
        seal_invoker: InvokeFunc,
    ) -> Self {
        Self {
            configuration,
            domain_id,
            id,
            create_token,
            active_request: None,
            seal_invoker,
            request: Arc::new(Mutex::new(None)),
            first: true,
        }
    }

    fn request_in_flight(&mut self) -> Result<bool, SessionError> {
        if self.active_request.is_some() {
            if self.active_request.as_ref().unwrap().is_finished() {
                RUNTIME.block_on(async {
                    match self.active_request.as_mut().unwrap().await {
                        Ok(Ok(())) => {
                            self.active_request = None;
                            Ok(false)
                        }
                        Ok(Err(e)) => Err(e),
                        Err(e) => Err(SessionError::Error(format!(
                            "error joining active request task: {}",
                            e
                        ))),
                    }
                })
            } else {
                Ok(true)
            }
        } else {
            Ok(false)
        }
    }

    // Update adds the supplied tags to the current capsule request body.
    pub fn update_tags_for_seal(
        &mut self,
        unique: &mut Vec<TagSummaryUniqueTagsInner>,
        elided: &mut Vec<TagSummaryElidedTagsInner>,
        capsule_tags: &mut Vec<Tag>,
        size: i64,
        rows: i64,
    ) {
        let mut request = self.request.lock().unwrap();

        if request.is_none() {
            *request = Some(CapsuleSealRequest {
                capsule_tags: mem::take(&mut *capsule_tags),
                span_tags: Box::new(TagSummary {
                    unique_tags: mem::take(&mut *unique),
                    elided_tags: mem::take(&mut *elided),
                }),
                size,
                rows,
            })
        } else {
            let req = request.as_mut().unwrap();
            merge_unique_tags(&mut req.span_tags.unique_tags, unique);
            merge_elided_tags(&mut req.span_tags.elided_tags, elided);
            req.capsule_tags.append(capsule_tags);
            req.size += size;
            req.rows += rows;
        }
    }

    // Invoke seal for the current request as a blocking event
    pub fn seal(
        &mut self,
        unique: &mut Vec<TagSummaryUniqueTagsInner>,
        elided: &mut Vec<TagSummaryElidedTagsInner>,
        capsule_tags: &mut Vec<Tag>,
        size: i64,
        rows: i64,
    ) -> Result<(), SessionError> {
        self.update_tags_for_seal(unique, elided, capsule_tags, size, rows);
        let request = self.request.lock().unwrap().take().unwrap();
        (self.seal_invoker)(
            self.configuration.clone(),
            self.domain_id.clone(),
            self.id.clone(),
            self.create_token.clone(),
            request,
        )
    }

    // seal_async will issue a seal request for the provided tags if no request is in flight.
    // If a request is in flight, these tags are added to the next request to be sent.
    pub fn seal_async(
        &mut self,
        unique: &mut Vec<TagSummaryUniqueTagsInner>,
        elided: &mut Vec<TagSummaryElidedTagsInner>,
        capsule_tags: &mut Vec<Tag>,
        size: i64,
        rows: i64,
    ) -> Result<(), SessionError> {
        self.update_tags_for_seal(unique, elided, capsule_tags, size, rows);

        if !self.request_in_flight()? {
            let request = self.request.lock().unwrap().take().unwrap();

            if self.first {
                // first seal is sync
                (self.seal_invoker)(
                    self.configuration.clone(),
                    self.domain_id.clone(),
                    self.id.clone(),
                    self.create_token.clone(),
                    request,
                )?;
            } else {
                // subsequent seals are async
                let config = self.configuration.clone();
                let domain_id = self.domain_id.clone();
                let id = self.id.clone();
                let create_token = self.create_token.clone();
                let invoker = self.seal_invoker.clone();
                let request_clone = self.request.clone();

                self.active_request = Some(tokio::spawn(async move {
                    // send the current request
                    (invoker)(
                        config.clone(),
                        domain_id.clone(),
                        id.clone(),
                        create_token.clone(),
                        request,
                    )?;
                    // if a new request is ready, send that too
                    if let Some(next_request) = request_clone.lock().unwrap().take() {
                        (invoker)(config, domain_id, id, create_token, next_request)?;
                    }
                    Ok(())
                }));
            }
        }
        Ok(())
    }

    pub fn complete(&mut self) -> Result<(), SessionError> {
        if self.active_request.is_some() {
            RUNTIME.block_on(async { self.active_request.as_mut().unwrap().await.unwrap() })?;
        }
        self.active_request = None;
        let request = self.request.lock().unwrap().take();
        if request.is_some() {
            (self.seal_invoker)(
                self.configuration.clone(),
                self.domain_id.clone(),
                self.id.clone(),
                self.create_token.clone(),
                request.unwrap(),
            )?;
        }
        Ok(())
    }
}

// merge_unique_tags merges b into a
fn merge_unique_tags(a: &mut Vec<TagSummaryUniqueTagsInner>, b: &Vec<TagSummaryUniqueTagsInner>) {
    for bi in b {
        if let Some(ai) = a.iter_mut().find(|ai| ai.tag == bi.tag) {
            ai.occurrences += bi.occurrences;
        } else {
            a.push(bi.clone());
        }
    }
}

// merge_elided_tags merges b into a
fn merge_elided_tags(a: &mut Vec<TagSummaryElidedTagsInner>, b: &Vec<TagSummaryElidedTagsInner>) {
    for bi in b {
        if let Some(ai) = a.iter_mut().find(|ai| ai.tag_name == bi.tag_name) {
            // This is wrong but we no longer have information on the unique tags.
            // The best we can do is report the largest set.
            ai.num_unique_tags = max(ai.num_unique_tags, bi.num_unique_tags);
            ai.total_occurrences += bi.total_occurrences;
        } else {
            a.push(bi.clone());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Mock implementation of `invoke_request` function for testing.
    fn mock_invoke_request(
        _configuration: configuration::Configuration,
        _domain_id: String,
        _id: String,
        _create_token: String,
        _seal_request: CapsuleSealRequest,
    ) -> Result<(), SessionError> {
        Ok(())
    }

    fn dummy_tag() -> TagSummaryUniqueTagsInner {
        TagSummaryUniqueTagsInner {
            tag: Box::new(Tag {
                name: "dummy_tag".to_string(),
                value: "value".to_string(),
                r#type: Default::default(),
                source: "source".to_string(),
                hook_version: Some("1.0.0".to_string()),
            }),
            occurrences: 10,
        }
    }

    fn seal_request() -> CapsuleSealRequest {
        CapsuleSealRequest {
            capsule_tags: vec![],
            span_tags: Box::new(TagSummary {
                unique_tags: vec![],
                elided_tags: vec![],
            }),
            size: 0,
            rows: 0,
        }
    }

    #[test]
    fn test_buffered_seal() {
        let configuration = configuration::Configuration::default();
        let domain_id = "test_domain".to_string();
        let id = "test_id".to_string();
        let create_token = "test_token".to_string();

        let mut buffered_seal = BufferedSealInternal::new(
            configuration,
            domain_id,
            id,
            create_token,
            Arc::new(mock_invoke_request),
        );

        // Simulate adding data to be sealed
        let mut unique_tags = vec![dummy_tag()];
        let mut elided_tags = vec![];
        let mut capsule_tags: Vec<Tag> = vec![];
        let size = 100;
        let rows = 10;

        buffered_seal
            .seal_async(
                &mut unique_tags,
                &mut elided_tags,
                &mut capsule_tags,
                size,
                rows,
            )
            .unwrap();

        let complete = buffered_seal.complete();
        assert!(complete.is_ok());
        assert!(buffered_seal.active_request.is_none());
    }

    #[test]
    fn test_caching_enabled() {
        let configuration = configuration::Configuration::default();
        let domain_id = "domain1".to_string();
        let id = "id1".to_string();
        let create_token = "token1".to_string();
        let mut request = seal_request();
        let mut seal_cache = SealCache::new(10, true);
        seal_cache.seal_invoker = Arc::new(mock_invoke_request);

        assert!(seal_cache
            .seal(
                &configuration,
                domain_id.clone(),
                id.clone(),
                create_token.clone(),
                &mut request,
                true
            )
            .is_ok());
        assert!(seal_cache
            .seal(
                &configuration,
                domain_id,
                id,
                create_token,
                &mut request,
                true
            )
            .is_ok());
        assert_eq!(seal_cache.cache.len(), 1);
    }

    #[test]
    fn test_caching_disabled() {
        let configuration = configuration::Configuration::default();
        let domain_id = "domain2".to_string();
        let id = "id2".to_string();
        let create_token = "token2".to_string();
        let mut request = seal_request();

        let mut seal_cache = SealCache::new(0, false);
        seal_cache.seal_invoker = Arc::new(mock_invoke_request);

        assert!(seal_cache
            .seal(
                &configuration,
                domain_id,
                id,
                create_token,
                &mut request,
                true
            )
            .is_ok());
        assert_eq!(seal_cache.enabled, false);
    }

    #[test]
    fn merge_into_empty() {
        let mut a: Vec<TagSummaryUniqueTagsInner> = vec![];
        let mut b = vec![TagSummaryUniqueTagsInner {
            tag: Box::new(Tag {
                name: "tag1".to_string(),
                value: "value1".to_string(),
                r#type: Default::default(),
                source: "source1".to_string(),
                hook_version: Some("1.0.0".to_string()),
            }),
            occurrences: 2,
        }];

        merge_unique_tags(&mut a, &mut b);

        assert_eq!(a.len(), 1);
        assert_eq!(a[0].occurrences, 2);
        assert_eq!(a[0].tag.name, "tag1");
    }

    #[test]
    fn merge_with_no_overlap() {
        let mut a = vec![TagSummaryUniqueTagsInner {
            tag: Box::new(Tag {
                name: "tag1".to_string(),
                value: "value1".to_string(),
                r#type: Default::default(),
                source: "source1".to_string(),
                hook_version: Some("1.0.0".to_string()),
            }),
            occurrences: 2,
        }];

        let mut b = vec![
            TagSummaryUniqueTagsInner {
                // tag has same name but different source so should be treated as a separate tag
                tag: Box::new(Tag {
                    name: "tag1".to_string(),
                    value: "value1".to_string(),
                    r#type: Default::default(),
                    source: "source2".to_string(),
                    hook_version: Some("1.0.0".to_string()),
                }),
                occurrences: 3,
            },
            TagSummaryUniqueTagsInner {
                tag: Box::new(Tag {
                    name: "tag2".to_string(),
                    value: "value2".to_string(),
                    r#type: Default::default(),
                    source: "source2".to_string(),
                    hook_version: Some("1.0.0".to_string()),
                }),
                occurrences: 3,
            },
        ];

        merge_unique_tags(&mut a, &mut b);

        assert_eq!(a.len(), 3);
        assert_eq!(a[1].occurrences, 3);
        assert_eq!(a[1].tag.name, "tag1");
    }

    #[test]
    fn merge_with_overlap() {
        let mut a = vec![TagSummaryUniqueTagsInner {
            tag: Box::new(Tag {
                name: "tag1".to_string(),
                value: "value1".to_string(),
                r#type: Default::default(),
                source: "source1".to_string(),
                hook_version: Some("1.0.0".to_string()),
            }),
            occurrences: 2,
        }];

        let mut b = vec![
            TagSummaryUniqueTagsInner {
                tag: Box::new(Tag {
                    name: "tag1".to_string(),
                    value: "value1_different".to_string(),
                    r#type: Default::default(),
                    source: "source1_different".to_string(),
                    hook_version: Some("1.0.1".to_string()),
                }),
                occurrences: 3,
            },
            TagSummaryUniqueTagsInner {
                tag: Box::new(Tag {
                    name: "tag1".to_string(),
                    value: "value1".to_string(),
                    r#type: Default::default(),
                    source: "source1".to_string(),
                    hook_version: Some("1.0.0".to_string()),
                }),
                occurrences: 5,
            },
        ];

        merge_unique_tags(&mut a, &mut b);

        assert_eq!(a.len(), 2, "One tag should be merged, the other appended");
        assert_eq!(a[0].occurrences, 7, "Occurrences should be summed");
    }

    #[test]
    fn merge_elided_into_empty() {
        let mut a: Vec<TagSummaryElidedTagsInner> = vec![];
        let mut b = vec![TagSummaryElidedTagsInner {
            tag_name: "tag1".to_string(),
            num_unique_tags: 2,
            total_occurrences: 5,
        }];

        merge_elided_tags(&mut a, &mut b);

        assert_eq!(a.len(), 1);
        assert_eq!(a[0].num_unique_tags, 2);
        assert_eq!(a[0].total_occurrences, 5);
        assert_eq!(a[0].tag_name, "tag1");
    }

    #[test]
    fn merge_elided_with_no_overlap() {
        let mut a = vec![TagSummaryElidedTagsInner {
            tag_name: "tag1".to_string(),
            num_unique_tags: 2,
            total_occurrences: 5,
        }];
        let mut b = vec![TagSummaryElidedTagsInner {
            tag_name: "tag2".to_string(),
            num_unique_tags: 3,
            total_occurrences: 7,
        }];

        merge_elided_tags(&mut a, &mut b);

        assert_eq!(a.len(), 2);
        assert_eq!(a[1].num_unique_tags, 3);
        assert_eq!(a[1].total_occurrences, 7);
        assert_eq!(a[1].tag_name, "tag2");
    }

    #[test]
    fn merge_elided_with_overlap() {
        let mut a = vec![TagSummaryElidedTagsInner {
            tag_name: "tag1".to_string(),
            num_unique_tags: 2,
            total_occurrences: 5,
        }];
        let mut b = vec![TagSummaryElidedTagsInner {
            tag_name: "tag1".to_string(),
            num_unique_tags: 1, // Lower number of unique tags
            total_occurrences: 3,
        }];

        merge_elided_tags(&mut a, &mut b);

        assert_eq!(a.len(), 1, "Tags should be merged, not appended");
        assert_eq!(
            a[0].num_unique_tags, 2,
            "Num unique tags should report the largest set"
        );
        assert_eq!(
            a[0].total_occurrences, 8,
            "Total occurrences should be summed"
        );
    }
}