dregs 1.0.0

The official Rust client for Dregs, which scores the users of your application for fraud and abuse.
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! Typed views over the Dregs API's responses.
//!
//! Every model keeps the response it was built from in `raw`, so a field Dregs adds after this
//! release is still reachable without waiting for an SDK upgrade. Parsing is deliberately
//! lenient: a missing or unexpected field becomes `None` rather than an error, because an SDK
//! that refuses to parse a response it half-understands is worse than one that hands back what it
//! got.

use std::fmt;
use std::ops::Deref;

use chrono::{DateTime, NaiveDateTime, Utc};
use serde_json::{Map, Value};

/// The four categories Dregs scores an identity in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Category {
    /// How likely it is that a person, rather than a script, is behind the account.
    Humanity,
    /// How genuine the details on the account look.
    Authenticity,
    /// How distinct the account is from others in the same tenant.
    Uniqueness,
    /// How ordinary the account's activity looks.
    Behavior,
}

impl Category {
    /// The name the API uses for the category, such as `"HUMANITY"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Category::Humanity => "HUMANITY",
            Category::Authenticity => "AUTHENTICITY",
            Category::Uniqueness => "UNIQUENESS",
            Category::Behavior => "BEHAVIOR",
        }
    }

    /// Parses the API's name for a category, ignoring case. A category this release predates
    /// gives `None`, so it cannot break an otherwise good response.
    pub fn parse(value: &str) -> Option<Category> {
        [
            Category::Humanity,
            Category::Authenticity,
            Category::Uniqueness,
            Category::Behavior,
        ]
        .into_iter()
        .find(|category| category.as_str().eq_ignore_ascii_case(value))
    }
}

impl fmt::Display for Category {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The outcome of a [`Client::track`](crate::Client::track) call.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TrackResult {
    /// The status Dregs reported, normally `"success"`.
    pub status: Option<String>,
    /// The event's identifier, either the one you supplied or one Dregs generated. It is `None`
    /// when the event was not recorded.
    pub id: Option<String>,
    /// The device fingerprint Dregs resolved, for events that carried a device signature.
    /// Server-side events do not, so this is normally `None`.
    pub fingerprint: Option<String>,
    /// The response body as received.
    pub raw: Value,
}

impl TrackResult {
    /// Whether Dregs recorded the event.
    ///
    /// This is `false` in the uncommon case where Dregs accepts the request without recording an
    /// event. A server-side integration holding a valid secret key should not normally see it,
    /// so it is worth a log line if you do. Ingestion failures that are the caller's to act on (a
    /// bad request, an unknown key, an exhausted quota, a rate limit) are returned as errors
    /// instead of landing here.
    pub fn accepted(&self) -> bool {
        self.id.is_some()
    }

    pub(crate) fn from_value(raw: Value) -> Self {
        TrackResult {
            status: string(&raw, "status"),
            id: string(&raw, "id"),
            fingerprint: string(&raw, "fingerprint"),
            raw,
        }
    }
}

/// A label Dregs applied to an identity, from an analyzer or a badge rule.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Badge {
    /// The badge's identifier, such as `"behavior.account-takeover-signal"`.
    pub slug: Option<String>,
    /// A human-readable name for the badge.
    pub name: Option<String>,
    /// The kind of badge.
    pub badge_type: Option<String>,
    /// Why the badge was applied.
    pub explanation: Option<String>,
    /// The details behind the badge.
    pub metadata: Map<String, Value>,
    /// The badge as received.
    pub raw: Value,
}

impl Badge {
    fn from_value(raw: &Value) -> Self {
        Badge {
            slug: string(raw, "slug"),
            name: string(raw, "name"),
            badge_type: string(raw, "type"),
            explanation: string(raw, "explanation"),
            metadata: object(raw, "metadata"),
            raw: raw.clone(),
        }
    }
}

/// One analyzer's finding, and the reasoning behind a slice of a score.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Observation {
    /// The category the observation contributes to.
    pub category: Option<Category>,
    /// The analyzer's identifier, such as `"humanity.user-agent"`.
    pub id: Option<String>,
    /// A human-readable name for the analyzer.
    pub label: Option<String>,
    /// A sentence describing what the analyzer found.
    pub explanation: Option<String>,
    /// 0.0 for entirely suspicious, 1.0 for entirely legitimate.
    pub value: Option<f64>,
    /// How sure the analyzer is, from 0.0 to 1.0.
    pub confidence: Option<f64>,
    /// How heavily this observation counts toward the category score.
    pub weight: Option<f64>,
    /// The counts and details behind the finding.
    pub metadata: Map<String, Value>,
    /// The observation as received.
    pub raw: Value,
}

impl Observation {
    fn from_value(raw: &Value) -> Self {
        Observation {
            category: category(raw),
            id: string(raw, "id"),
            label: string(raw, "label"),
            explanation: string(raw, "explanation"),
            value: float(raw, "value"),
            confidence: float(raw, "confidence"),
            weight: float(raw, "weight"),
            metadata: object(raw, "metadata"),
            raw: raw.clone(),
        }
    }
}

/// One category's score.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Score {
    /// The category scored. `None` for a category this release of the SDK predates; the API's
    /// name for it is still in `raw`.
    pub category: Option<Category>,
    /// An integer from 0 (worst) to 100 (best).
    pub value: Option<i64>,
    /// The observations behind the score. This is empty on the result of
    /// [`Identities::scores`](crate::Identities::scores), which reports the scores alone; the
    /// observations come from [`Identities::analysis`](crate::Identities::analysis).
    pub observations: Vec<Observation>,
    /// The score as received.
    pub raw: Value,
}

impl Score {
    fn from_value(raw: &Value) -> Self {
        Score {
            category: category(raw),
            value: integer(raw, "value"),
            observations: objects(raw, "observations")
                .map(Observation::from_value)
                .collect(),
            raw: raw.clone(),
        }
    }

    fn bare(category: Category, value: i64) -> Self {
        Score {
            category: Some(category),
            value: Some(value),
            observations: Vec::new(),
            raw: Value::Null,
        }
    }
}

/// An identity's four category scores.
///
/// Dereferences to a slice of [`Score`], and also offers the four categories by name:
///
/// ```
/// # async fn run(client: dregs::Client) -> dregs::Result<()> {
/// let scores = client.identities().scores("user_12345").await?;
///
/// if scores.humanity().is_some_and(|humanity| humanity < 30) {
///     // hold for review
/// }
///
/// for score in &scores {
///     println!("{:?}: {:?}", score.category, score.value);
/// }
/// # Ok(())
/// # }
/// ```
///
/// A category Dregs has not scored yet is absent from the slice, and its named accessor returns
/// `None`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Scores(Vec<Score>);

impl Scores {
    /// The score for `category`, or `None` when it has not been scored.
    pub fn get(&self, category: Category) -> Option<&Score> {
        self.0.iter().find(|score| score.category == Some(category))
    }

    fn value(&self, category: Category) -> Option<i64> {
        self.get(category).and_then(|score| score.value)
    }

    /// How likely it is that a person, rather than a script, is behind the account.
    pub fn humanity(&self) -> Option<i64> {
        self.value(Category::Humanity)
    }

    /// How genuine the details on the account look.
    pub fn authenticity(&self) -> Option<i64> {
        self.value(Category::Authenticity)
    }

    /// How distinct the account is from others in the same tenant.
    pub fn uniqueness(&self) -> Option<i64> {
        self.value(Category::Uniqueness)
    }

    /// How ordinary the account's activity looks.
    pub fn behavior(&self) -> Option<i64> {
        self.value(Category::Behavior)
    }

    /// The scores as a vector.
    pub fn into_vec(self) -> Vec<Score> {
        self.0
    }

    pub(crate) fn from_value(raw: &Value) -> Self {
        let items = match raw {
            Value::Array(items) => items
                .iter()
                .filter(|item| item.is_object())
                .map(Score::from_value)
                .collect(),
            _ => Vec::new(),
        };

        Scores(items)
    }
}

impl Deref for Scores {
    type Target = [Score];

    fn deref(&self) -> &[Score] {
        &self.0
    }
}

impl IntoIterator for Scores {
    type Item = Score;
    type IntoIter = std::vec::IntoIter<Score>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a Scores {
    type Item = &'a Score;
    type IntoIter = std::slice::Iter<'a, Score>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

/// A user Dregs is tracking, and their current scores.
///
/// `id` is your own identifier for the user, the one you pass to
/// [`Event::new`](crate::Event::new) and to `dregs.identify()` in the browser tracker, not an
/// internal Dregs id.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Identity {
    /// Your own id for the user.
    pub id: Option<String>,
    /// The name Dregs displays for the user, from the attributes you have sent.
    pub display_name: Option<String>,
    /// The email Dregs displays for the user.
    pub display_email: Option<String>,
    /// The username Dregs displays for the user.
    pub display_username: Option<String>,
    /// The humanity score, from 0 to 100.
    pub humanity_score: Option<i64>,
    /// The authenticity score, from 0 to 100.
    pub authenticity_score: Option<i64>,
    /// The uniqueness score, from 0 to 100.
    pub uniqueness_score: Option<i64>,
    /// The behavior score, from 0 to 100.
    pub behavior_score: Option<i64>,
    /// When Dregs first saw the identity.
    pub created_at: Option<DateTime<Utc>>,
    /// When the identity last changed.
    pub updated_at: Option<DateTime<Utc>>,
    /// When an event was last tracked against the identity.
    pub last_tracked_at: Option<DateTime<Utc>>,
    /// When the identity was last scored.
    pub last_scored_at: Option<DateTime<Utc>>,
    /// Whether the identity has been disregarded, and so is left out of scoring and alerting.
    pub disregarded: bool,
    /// The badges applied to the identity.
    pub badges: Vec<Badge>,
    /// Every attribute you have sent for the identity.
    pub data: Map<String, Value>,
    /// The identity as received.
    pub raw: Value,
}

impl Identity {
    /// The identity's scores, as a [`Scores`] for parity with
    /// [`Identities::scores`](crate::Identities::scores).
    pub fn scores(&self) -> Scores {
        let pairs = [
            (Category::Humanity, self.humanity_score),
            (Category::Authenticity, self.authenticity_score),
            (Category::Uniqueness, self.uniqueness_score),
            (Category::Behavior, self.behavior_score),
        ];

        Scores(
            pairs
                .into_iter()
                .filter_map(|(category, value)| value.map(|value| Score::bare(category, value)))
                .collect(),
        )
    }

    pub(crate) fn from_value(raw: Value) -> Self {
        Identity {
            id: string(&raw, "id"),
            display_name: string(&raw, "displayName"),
            display_email: string(&raw, "displayEmail"),
            display_username: string(&raw, "displayUsername"),
            humanity_score: integer(&raw, "humanityScore"),
            authenticity_score: integer(&raw, "authenticityScore"),
            uniqueness_score: integer(&raw, "uniquenessScore"),
            behavior_score: integer(&raw, "behaviorScore"),
            created_at: datetime(&raw, "createdAt"),
            updated_at: datetime(&raw, "updatedAt"),
            last_tracked_at: datetime(&raw, "lastTrackedAt"),
            last_scored_at: datetime(&raw, "lastScoredAt"),
            disregarded: boolean_or(&raw, "disregarded", false),
            badges: objects(&raw, "badges").map(Badge::from_value).collect(),
            data: object(&raw, "data"),
            raw,
        }
    }
}

/// One analysis cycle: the scores an identity was given, and why.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Analysis {
    /// The cycle's identifier.
    pub id: Option<i64>,
    /// The identity that was analyzed.
    pub identity_id: Option<String>,
    /// The four category scores, each carrying its observations.
    pub scores: Scores,
    /// How many events the cycle considered.
    pub event_count: Option<i64>,
    /// How many devices the cycle considered.
    pub device_count: Option<i64>,
    /// How long the cycle took.
    pub duration_millis: Option<i64>,
    /// When the cycle started.
    pub started_at: Option<DateTime<Utc>>,
    /// When the cycle finished.
    pub finished_at: Option<DateTime<Utc>>,
    /// The analysis as received.
    pub raw: Value,
}

impl Analysis {
    /// Every observation from the cycle, across all four categories.
    pub fn observations(&self) -> impl Iterator<Item = &Observation> {
        self.scores
            .iter()
            .flat_map(|score| score.observations.iter())
    }

    pub(crate) fn from_value(raw: Value) -> Self {
        Analysis {
            id: integer(&raw, "id"),
            identity_id: string(&raw, "identityId"),
            scores: raw
                .get("scores")
                .map(Scores::from_value)
                .unwrap_or_default(),
            event_count: integer(&raw, "eventCount"),
            device_count: integer(&raw, "deviceCount"),
            duration_millis: integer(&raw, "durationMillis"),
            started_at: datetime(&raw, "startedAt"),
            finished_at: datetime(&raw, "finishedAt"),
            raw,
        }
    }
}

/// Where an escalation stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EscalationStatus {
    /// Opened by a rule, and not yet looked at.
    Open,
    /// Someone is looking at it.
    Acknowledged,
    /// Dealt with.
    Closed,
}

impl EscalationStatus {
    /// The name the API uses for the status, such as `"OPEN"`.
    pub fn as_str(self) -> &'static str {
        match self {
            EscalationStatus::Open => "OPEN",
            EscalationStatus::Acknowledged => "ACKNOWLEDGED",
            EscalationStatus::Closed => "CLOSED",
        }
    }

    /// Parses the API's name for a status, ignoring case. A status this release predates gives
    /// `None`.
    pub fn parse(value: &str) -> Option<EscalationStatus> {
        [
            EscalationStatus::Open,
            EscalationStatus::Acknowledged,
            EscalationStatus::Closed,
        ]
        .into_iter()
        .find(|status| status.as_str().eq_ignore_ascii_case(value))
    }
}

impl fmt::Display for EscalationStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// How serious an escalation is, as its rule set it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EscalationSeverity {
    /// Worth knowing about.
    Info,
    /// Worth a look.
    Warning,
    /// Worth acting on now.
    Critical,
}

impl EscalationSeverity {
    /// The name the API uses for the severity, such as `"CRITICAL"`.
    pub fn as_str(self) -> &'static str {
        match self {
            EscalationSeverity::Info => "INFO",
            EscalationSeverity::Warning => "WARNING",
            EscalationSeverity::Critical => "CRITICAL",
        }
    }

    /// Parses the API's name for a severity, ignoring case. A severity this release predates
    /// gives `None`.
    pub fn parse(value: &str) -> Option<EscalationSeverity> {
        [
            EscalationSeverity::Info,
            EscalationSeverity::Warning,
            EscalationSeverity::Critical,
        ]
        .into_iter()
        .find(|severity| severity.as_str().eq_ignore_ascii_case(value))
    }
}

impl fmt::Display for EscalationSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A pointer to another resource: its id, a label for display, and its API path.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Reference {
    /// The resource's id.
    pub id: Option<String>,
    /// A label for display, such as an identity's name.
    pub label: Option<String>,
    /// The resource's API path, such as `"/api/identities/user_12345"`.
    pub path: Option<String>,
    /// The reference as received.
    pub raw: Value,
}

impl Reference {
    fn from_value(raw: &Value) -> Self {
        Reference {
            id: id(raw, "id"),
            label: string(raw, "label"),
            path: string(raw, "path"),
            raw: raw.clone(),
        }
    }
}

/// A pointer to a group, as it appears on a [`TrackedEvent`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct GroupReference {
    /// The kind of group, such as `"organization"` or `"team"`.
    pub group_type: Option<String>,
    /// Your own id for the group.
    pub id: Option<String>,
    /// A label for display, such as the group's name.
    pub label: Option<String>,
    /// The group's API path.
    pub path: Option<String>,
    /// The reference as received.
    pub raw: Value,
}

impl GroupReference {
    fn from_value(raw: &Value) -> Self {
        GroupReference {
            group_type: string(raw, "type"),
            id: id(raw, "id"),
            label: string(raw, "label"),
            path: string(raw, "path"),
            raw: raw.clone(),
        }
    }
}

/// An organization, team, workspace, or whatever your application groups users into, as Dregs
/// has recorded it.
///
/// A group is identified by its type and id together, both your own. Dregs normalizes the type to
/// lower_snake_case. To send a group with an event, or to create one, use the
/// [`Group`](crate::Group) builder.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TrackedGroup {
    /// The kind of group, such as `"organization"` or `"team"`.
    pub group_type: Option<String>,
    /// Your own id for the group.
    pub id: Option<String>,
    /// A name for display, taken from the group's attributes.
    pub display_name: Option<String>,
    /// How many identities are members.
    pub identity_count: Option<i64>,
    /// When Dregs first saw the group.
    pub created_at: Option<DateTime<Utc>>,
    /// When the group last changed.
    pub updated_at: Option<DateTime<Utc>>,
    /// When an event was last sent with the group.
    pub last_tracked_at: Option<DateTime<Utc>>,
    /// The group's attributes. Empty on the groups of a list call, which leaves them out.
    pub data: Map<String, Value>,
    /// The group as received.
    pub raw: Value,
}

impl TrackedGroup {
    pub(crate) fn from_value(raw: Value) -> Self {
        TrackedGroup {
            group_type: string(&raw, "type"),
            id: id(&raw, "id"),
            display_name: string(&raw, "displayName"),
            identity_count: integer(&raw, "identityCount"),
            created_at: datetime(&raw, "createdAt"),
            updated_at: datetime(&raw, "updatedAt"),
            last_tracked_at: datetime(&raw, "lastTrackedAt"),
            data: object(&raw, "data"),
            raw,
        }
    }
}

/// An event Dregs recorded. To record one, use [`Client::track`](crate::Client::track).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TrackedEvent {
    /// The event's id, either the one you sent or one Dregs generated.
    pub id: Option<String>,
    /// When the event happened.
    pub timestamp: Option<DateTime<Utc>>,
    /// The identity the event belongs to, if any.
    pub identity: Option<Reference>,
    /// The groups the event was sent with.
    pub groups: Vec<GroupReference>,
    /// The device fingerprint, for events that carried a device signature.
    pub fingerprint: Option<String>,
    /// The browser session, for events from the tracker.
    pub session: Option<String>,
    /// The address the event came from.
    pub ip: Option<String>,
    /// The page URL, for events from the tracker.
    pub url: Option<String>,
    /// Where the event came from, such as `"rust-sdk"`.
    pub source: Option<String>,
    /// Your name for the event, such as `"user.signup"`.
    pub name: Option<String>,
    /// The Dregs event type your name is mapped to, if it is mapped.
    pub canonical_type: Option<String>,
    /// The event's attributes, with sensitive values redacted.
    pub data: Map<String, Value>,
    /// The event as received.
    pub raw: Value,
}

impl TrackedEvent {
    pub(crate) fn from_value(raw: Value) -> Self {
        TrackedEvent {
            id: id(&raw, "id"),
            timestamp: datetime(&raw, "timestamp"),
            identity: nested(&raw, "identity", Reference::from_value),
            groups: objects(&raw, "groups")
                .map(GroupReference::from_value)
                .collect(),
            fingerprint: string(&raw, "fingerprint"),
            session: string(&raw, "session"),
            ip: string(&raw, "ip"),
            url: string(&raw, "url"),
            source: string(&raw, "eventSource"),
            name: string(&raw, "eventName"),
            canonical_type: string(&raw, "canonicalType"),
            data: object(&raw, "eventData"),
            raw,
        }
    }
}

/// A browser or device Dregs has seen, identified by its fingerprint.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Device {
    /// The device's fingerprint.
    pub fingerprint: Option<String>,
    /// The address the device was last seen at.
    pub ip: Option<String>,
    /// The autonomous system the address belongs to.
    pub asn: Option<String>,
    /// The name of that autonomous system, such as a hosting provider or ISP.
    pub asn_label: Option<String>,
    /// The browser's user agent.
    pub user_agent: Option<String>,
    /// The city the address is in.
    pub city: Option<String>,
    /// The region the address is in.
    pub region: Option<String>,
    /// The country the address is in.
    pub country: Option<String>,
    /// The country's ISO 3166 code, such as `"US"`.
    pub country_code: Option<String>,
    /// The browser's time zone.
    pub timezone: Option<String>,
    /// The address's approximate latitude.
    pub latitude: Option<f64>,
    /// The address's approximate longitude.
    pub longitude: Option<f64>,
    /// Whether the device has been disregarded, and so no longer links the identities seen on it.
    pub disregarded: bool,
    /// When Dregs first saw the device.
    pub first_seen_at: Option<DateTime<Utc>>,
    /// When Dregs last saw the device.
    pub last_seen_at: Option<DateTime<Utc>>,
    /// The device as received.
    pub raw: Value,
}

impl Device {
    pub(crate) fn from_value(raw: Value) -> Self {
        Device {
            fingerprint: string(&raw, "fingerprint"),
            ip: string(&raw, "ip"),
            asn: string(&raw, "asn"),
            asn_label: string(&raw, "asnLabel"),
            user_agent: string(&raw, "userAgent"),
            city: string(&raw, "city"),
            region: string(&raw, "region"),
            country: string(&raw, "country"),
            country_code: string(&raw, "countryCode"),
            timezone: string(&raw, "timezone"),
            latitude: float(&raw, "latitude"),
            longitude: float(&raw, "longitude"),
            disregarded: boolean_or(&raw, "disregarded", false),
            first_seen_at: datetime(&raw, "firstSeenAt"),
            last_seen_at: datetime(&raw, "lastSeenAt"),
            raw,
        }
    }
}

/// Another identity Dregs believes is connected to this one, such as by a shared device.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct LinkedIdentity {
    /// The linked identity's id.
    pub identity_id: Option<String>,
    /// The linked identity's display name.
    pub display_name: Option<String>,
    /// How they are linked, such as `"SAME_DEVICE"` or `"SHARED_IP"`.
    pub link_type: Option<String>,
    /// How strongly they are linked, from 0.0 to 1.0.
    pub value: Option<f64>,
    /// How sure Dregs is of the link, from 0.0 to 1.0.
    pub confidence: Option<f64>,
    /// A sentence describing the link.
    pub explanation: Option<String>,
    /// The details behind the link.
    pub metadata: Map<String, Value>,
    /// When Dregs found the link.
    pub created_at: Option<DateTime<Utc>>,
    /// The link as received.
    pub raw: Value,
}

impl LinkedIdentity {
    pub(crate) fn from_value(raw: Value) -> Self {
        LinkedIdentity {
            identity_id: string(&raw, "targetIdentityId"),
            display_name: string(&raw, "targetDisplayName"),
            link_type: string(&raw, "type"),
            value: float(&raw, "value"),
            confidence: float(&raw, "confidence"),
            explanation: string(&raw, "explanation"),
            metadata: object(&raw, "metadata"),
            created_at: datetime(&raw, "createdAt"),
            raw,
        }
    }
}

/// The scores one past analysis cycle produced.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ScoreHistoryEntry {
    /// The cycle's id, which
    /// [`Identities::analysis_cycle`](crate::Identities::analysis_cycle) accepts to fetch that
    /// cycle's observations.
    pub cycle_id: Option<i64>,
    /// The humanity score the cycle gave, from 0 to 100.
    pub humanity: Option<i64>,
    /// The authenticity score the cycle gave, from 0 to 100.
    pub authenticity: Option<i64>,
    /// The uniqueness score the cycle gave, from 0 to 100.
    pub uniqueness: Option<i64>,
    /// The behavior score the cycle gave, from 0 to 100.
    pub behavior: Option<i64>,
    /// How many events the cycle considered.
    pub event_count: Option<i64>,
    /// How many devices the cycle considered.
    pub device_count: Option<i64>,
    /// When the cycle finished.
    pub finished_at: Option<DateTime<Utc>>,
    /// The entry as received.
    pub raw: Value,
}

impl ScoreHistoryEntry {
    pub(crate) fn from_value(raw: Value) -> Self {
        ScoreHistoryEntry {
            cycle_id: integer(&raw, "id"),
            humanity: integer(&raw, "humanityScore"),
            authenticity: integer(&raw, "authenticityScore"),
            uniqueness: integer(&raw, "uniquenessScore"),
            behavior: integer(&raw, "behaviorScore"),
            event_count: integer(&raw, "eventCount"),
            device_count: integer(&raw, "deviceCount"),
            finished_at: datetime(&raw, "finishedAt"),
            raw,
        }
    }
}

/// A review of an identity's analysis, written by Dregs's AI reviewer.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct IdentityReview {
    /// The review's id.
    pub id: Option<i64>,
    /// The identity reviewed.
    pub identity_id: Option<String>,
    /// `"PENDING"` until the review has run, then `"FINISHED"` or `"FAILED"`.
    pub status: Option<String>,
    /// The note you sent with the request, if any.
    pub feedback: Option<String>,
    /// The reviewer's findings, once it has run.
    pub summary: Option<String>,
    /// Why the review failed, when it did.
    pub error_message: Option<String>,
    /// When the review was requested.
    pub created_at: Option<DateTime<Utc>>,
    /// When the review finished.
    pub completed_at: Option<DateTime<Utc>>,
    /// The review as received.
    pub raw: Value,
}

impl IdentityReview {
    pub(crate) fn from_value(raw: Value) -> Self {
        IdentityReview {
            id: integer(&raw, "id"),
            identity_id: string(&raw, "identityId"),
            status: string(&raw, "status"),
            feedback: string(&raw, "userFeedback"),
            summary: string(&raw, "summary"),
            error_message: string(&raw, "errorMessage"),
            created_at: datetime(&raw, "createdAt"),
            completed_at: datetime(&raw, "completedAt"),
            raw,
        }
    }
}

/// An escalation an escalation rule opened against an identity.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Escalation {
    /// The escalation's id.
    pub id: Option<i64>,
    /// Where the escalation stands. `None` for a status this release predates; the API's name
    /// for it is still in `raw`.
    pub status: Option<EscalationStatus>,
    /// How serious the escalation is. `None` for a severity this release predates.
    pub severity: Option<EscalationSeverity>,
    /// The identity the escalation is about.
    pub identity: Option<Reference>,
    /// The escalation rule that opened it.
    pub rule: Option<Reference>,
    /// The identity's scores when the escalation opened, by category name.
    pub scores: Map<String, Value>,
    /// When the escalation opened.
    pub opened_at: Option<DateTime<Utc>>,
    /// When the escalation was acknowledged.
    pub acknowledged_at: Option<DateTime<Utc>>,
    /// When the escalation was closed.
    pub closed_at: Option<DateTime<Utc>>,
    /// When the escalation was created.
    pub created_at: Option<DateTime<Utc>>,
    /// The escalation as received.
    pub raw: Value,
}

impl Escalation {
    pub(crate) fn from_value(raw: Value) -> Self {
        Escalation {
            id: integer(&raw, "id"),
            status: raw
                .get("status")
                .and_then(Value::as_str)
                .and_then(EscalationStatus::parse),
            severity: raw
                .get("severity")
                .and_then(Value::as_str)
                .and_then(EscalationSeverity::parse),
            identity: nested(&raw, "identity", Reference::from_value),
            rule: nested(&raw, "escalationRule", Reference::from_value),
            scores: object(&raw, "scoreSnapshot"),
            opened_at: datetime(&raw, "openedAt"),
            acknowledged_at: datetime(&raw, "acknowledgedAt"),
            closed_at: datetime(&raw, "closedAt"),
            created_at: datetime(&raw, "createdAt"),
            raw,
        }
    }
}

/// How many escalations are in each status.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct EscalationSummary {
    /// How many are open.
    pub open: u64,
    /// How many are acknowledged.
    pub acknowledged: u64,
    /// How many are closed.
    pub closed: u64,
    /// The summary as received.
    pub raw: Value,
}

impl EscalationSummary {
    pub(crate) fn from_value(raw: Value) -> Self {
        let count = |key| {
            integer(&raw, key)
                .and_then(|value| u64::try_from(value).ok())
                .unwrap_or(0)
        };

        EscalationSummary {
            open: count("open"),
            acknowledged: count("acknowledged"),
            closed: count("closed"),
            raw,
        }
    }
}

/// Reads an id the API spells as a string, accepting a number too.
fn id(raw: &Value, key: &str) -> Option<String> {
    match raw.get(key)? {
        Value::String(value) => Some(value.clone()),
        Value::Number(value) => Some(value.to_string()),
        _ => None,
    }
}

fn string(raw: &Value, key: &str) -> Option<String> {
    raw.get(key).and_then(Value::as_str).map(str::to_owned)
}

fn float(raw: &Value, key: &str) -> Option<f64> {
    raw.get(key).and_then(Value::as_f64)
}

/// Reads an integer, accepting a float with no fractional part, since JSON does not distinguish
/// the two and a serializer that writes `85.0` should not cost the caller their score.
pub(crate) fn integer(raw: &Value, key: &str) -> Option<i64> {
    let value = raw.get(key)?;

    value.as_i64().or_else(|| {
        value
            .as_f64()
            .filter(|f| f.fract() == 0.0 && f.is_finite())
            .map(|f| f as i64)
    })
}

/// Reads a boolean, falling back to `default` when it is missing or not a boolean.
pub(crate) fn boolean_or(raw: &Value, key: &str, default: bool) -> bool {
    raw.get(key).and_then(Value::as_bool).unwrap_or(default)
}

/// Reads a nested object as a model, or `None` when it is missing or not an object.
fn nested<T>(raw: &Value, key: &str, parse: fn(&Value) -> T) -> Option<T> {
    raw.get(key).filter(|value| value.is_object()).map(parse)
}

fn object(raw: &Value, key: &str) -> Map<String, Value> {
    raw.get(key)
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default()
}

fn objects<'a>(raw: &'a Value, key: &str) -> impl Iterator<Item = &'a Value> {
    raw.get(key)
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter(|item| item.is_object())
}

fn category(raw: &Value) -> Option<Category> {
    raw.get("category")
        .and_then(Value::as_str)
        .and_then(Category::parse)
}

/// Parses an ISO-8601 timestamp, reading one with no offset as UTC and returning `None` for
/// anything unparseable.
pub(crate) fn parse_datetime(value: &str) -> Option<DateTime<Utc>> {
    if let Ok(parsed) = DateTime::parse_from_rfc3339(value) {
        return Some(parsed.with_timezone(&Utc));
    }

    NaiveDateTime::parse_from_str(value, "%Y-%m-%dT%H:%M:%S%.f")
        .ok()
        .map(|naive| naive.and_utc())
}

fn datetime(raw: &Value, key: &str) -> Option<DateTime<Utc>> {
    raw.get(key)
        .and_then(Value::as_str)
        .and_then(parse_datetime)
}