cinnamon 2.0.0-alpha.1

A type-safe, async Nightscout client for Rust: API v3 with v1/v2 fallback, JWT auth, incremental sync and realtime streams.
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
//! The `entries` collection: sensor glucose (`sgv`), meter glucose (`mbg`) and sensor
//! calibrations (`cal`).

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;

use super::{CollectionName, Direction, Extra, Glucose, Meta, Timestamp, de, impl_document};

/// A sensor glucose value (`type: "sgv"`) from a CGM.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Sgv {
    /// Bookkeeping fields.
    #[serde(flatten)]
    pub meta: Meta,
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    kind: Option<String>,
    /// The glucose value (mg/dL).
    pub sgv: Glucose,
    /// When the reading was taken.
    pub date: Timestamp,
    /// The uploader's ISO rendering of `date` (API v3 uploads usually omit it).
    #[serde(
        rename = "dateString",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::text"
    )]
    pub date_string: Option<String>,
    /// Server-normalized ISO time (API v1 uploads only).
    #[serde(
        rename = "sysTime",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::text"
    )]
    pub sys_time: Option<String>,
    /// Trend arrow.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "opt_direction"
    )]
    pub direction: Option<Direction>,
    /// Sensor noise level (1 = clean … 4 = heavy).
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::int32")]
    pub noise: Option<i32>,
    /// Filtered raw sensor signal.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub filtered: Option<f64>,
    /// Unfiltered raw sensor signal.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub unfiltered: Option<f64>,
    /// Signal strength.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub rssi: Option<f64>,
    /// Change from the previous reading, as computed by the uploader.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub delta: Option<f64>,
    /// The uploading device or app (e.g. `xDrip-DexcomG6`, `loop://iPhone`).
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub device: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

impl Sgv {
    /// A new reading at `at`. The device defaults to the client's app name on upload.
    #[must_use]
    pub fn new(sgv: impl Into<Glucose>, at: impl Into<Timestamp>) -> Self {
        let date = at.into();
        Self {
            meta: Meta::default(),
            kind: Some("sgv".into()),
            sgv: sgv.into(),
            date,
            date_string: None,
            sys_time: None,
            direction: None,
            noise: None,
            filtered: None,
            unfiltered: None,
            rssi: None,
            delta: None,
            device: None,
            extra: Extra::new(),
        }
    }

    /// Sets the trend arrow.
    #[must_use]
    pub fn with_direction(mut self, direction: Direction) -> Self {
        self.direction = Some(direction);
        self
    }

    /// Sets the device name.
    #[must_use]
    pub fn with_device(mut self, device: impl Into<String>) -> Self {
        self.device = Some(device.into());
        self
    }

    /// Sets the noise level.
    #[must_use]
    pub const fn with_noise(mut self, noise: i32) -> Self {
        self.noise = Some(noise);
        self
    }

    fn fill_defaults(&mut self, app: &str) {
        self.kind.get_or_insert_with(|| "sgv".into());
        self.device.get_or_insert_with(|| app.to_owned());
        self.date_string.get_or_insert_with(|| self.date.to_iso());
    }
}

impl_document!(
    Sgv,
    CollectionName::Entries,
    timestamp = |s| Some(s.date),
    device = |s| s.device.as_deref()
);

/// A meter (fingerstick) glucose value (`type: "mbg"`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Mbg {
    /// Bookkeeping fields.
    #[serde(flatten)]
    pub meta: Meta,
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    kind: Option<String>,
    /// The glucose value (mg/dL).
    pub mbg: Glucose,
    /// When the measurement was taken.
    pub date: Timestamp,
    /// The uploader's ISO rendering of `date`.
    #[serde(
        rename = "dateString",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::text"
    )]
    pub date_string: Option<String>,
    /// Server-normalized ISO time (API v1 uploads only).
    #[serde(
        rename = "sysTime",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::text"
    )]
    pub sys_time: Option<String>,
    /// The meter or uploading app.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub device: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

impl Mbg {
    /// A new meter reading at `at`.
    #[must_use]
    pub fn new(mbg: impl Into<Glucose>, at: impl Into<Timestamp>) -> Self {
        Self {
            meta: Meta::default(),
            kind: Some("mbg".into()),
            mbg: mbg.into(),
            date: at.into(),
            date_string: None,
            sys_time: None,
            device: None,
            extra: Extra::new(),
        }
    }

    /// Sets the device name.
    #[must_use]
    pub fn with_device(mut self, device: impl Into<String>) -> Self {
        self.device = Some(device.into());
        self
    }

    fn fill_defaults(&mut self, app: &str) {
        self.kind.get_or_insert_with(|| "mbg".into());
        self.device.get_or_insert_with(|| app.to_owned());
        self.date_string.get_or_insert_with(|| self.date.to_iso());
    }
}

impl_document!(
    Mbg,
    CollectionName::Entries,
    timestamp = |s| Some(s.date),
    device = |s| s.device.as_deref()
);

/// A sensor calibration (`type: "cal"`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Cal {
    /// Bookkeeping fields.
    #[serde(flatten)]
    pub meta: Meta,
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    kind: Option<String>,
    /// When the calibration was applied.
    pub date: Timestamp,
    /// The uploader's ISO rendering of `date`.
    #[serde(
        rename = "dateString",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::text"
    )]
    pub date_string: Option<String>,
    /// Calibration slope.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub slope: Option<f64>,
    /// Calibration intercept.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub intercept: Option<f64>,
    /// Calibration scale.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub scale: Option<f64>,
    /// The uploading device.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub device: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

impl Cal {
    /// A new calibration record at `at`.
    #[must_use]
    pub fn new(at: impl Into<Timestamp>, slope: f64, intercept: f64, scale: f64) -> Self {
        Self {
            meta: Meta::default(),
            kind: Some("cal".into()),
            date: at.into(),
            date_string: None,
            slope: Some(slope),
            intercept: Some(intercept),
            scale: Some(scale),
            device: None,
            extra: Extra::new(),
        }
    }

    fn fill_defaults(&mut self, app: &str) {
        self.kind.get_or_insert_with(|| "cal".into());
        self.device.get_or_insert_with(|| app.to_owned());
        self.date_string.get_or_insert_with(|| self.date.to_iso());
    }
}

impl_document!(
    Cal,
    CollectionName::Entries,
    timestamp = |s| Some(s.date),
    device = |s| s.device.as_deref()
);

/// Any document of the `entries` collection, dispatched on its `type`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Entry {
    /// A sensor glucose value.
    Sgv(Sgv),
    /// A meter glucose value.
    Mbg(Mbg),
    /// A calibration.
    Cal(Cal),
    /// Any other entry type, kept as raw JSON.
    Other(RawEntry),
}

/// An entry of a type cinnamon does not model.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RawEntry {
    /// Bookkeeping fields.
    #[serde(flatten)]
    pub meta: Meta,
    /// The entry fields, including `type` and `date`.
    #[serde(flatten)]
    pub extra: Extra,
}

impl Entry {
    /// The entry time, when known.
    #[must_use]
    pub fn date(&self) -> Option<Timestamp> {
        match self {
            Self::Sgv(e) => Some(e.date),
            Self::Mbg(e) => Some(e.date),
            Self::Cal(e) => Some(e.date),
            Self::Other(raw) => raw.extra.get("date").and_then(Timestamp::from_value),
        }
    }

    /// The entry `type` (`sgv`, `mbg`, `cal`, …).
    #[must_use]
    pub fn kind(&self) -> Option<&str> {
        match self {
            Self::Sgv(_) => Some("sgv"),
            Self::Mbg(_) => Some("mbg"),
            Self::Cal(_) => Some("cal"),
            Self::Other(raw) => raw.extra.get("type").and_then(Value::as_str),
        }
    }
}

impl Serialize for Entry {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Sgv(e) => e.serialize(s),
            Self::Mbg(e) => e.serialize(s),
            Self::Cal(e) => e.serialize(s),
            Self::Other(raw) => raw.serialize(s),
        }
    }
}

impl<'de> Deserialize<'de> for Entry {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(d)?;
        let kind = value.get("type").and_then(Value::as_str).map(str::to_owned);
        let parse = |v: Value| -> Result<Self, D::Error> {
            let res = match kind.as_deref() {
                Some("sgv") => serde_json::from_value(v).map(Self::Sgv),
                Some("mbg") => serde_json::from_value(v).map(Self::Mbg),
                Some("cal") => serde_json::from_value(v).map(Self::Cal),
                _ => serde_json::from_value(v).map(Self::Other),
            };
            res.map_err(serde::de::Error::custom)
        };
        parse(value)
    }
}

impl super::sealed::Sealed for Entry {}

impl super::Document for Entry {
    const COLLECTION: CollectionName = CollectionName::Entries;

    fn meta(&self) -> &Meta {
        match self {
            Self::Sgv(e) => &e.meta,
            Self::Mbg(e) => &e.meta,
            Self::Cal(e) => &e.meta,
            Self::Other(e) => &e.meta,
        }
    }

    fn meta_mut(&mut self) -> &mut Meta {
        match self {
            Self::Sgv(e) => &mut e.meta,
            Self::Mbg(e) => &mut e.meta,
            Self::Cal(e) => &mut e.meta,
            Self::Other(e) => &mut e.meta,
        }
    }

    fn timestamp(&self) -> Option<Timestamp> {
        self.date()
    }

    fn device(&self) -> Option<&str> {
        match self {
            Self::Sgv(e) => e.device.as_deref(),
            Self::Mbg(e) => e.device.as_deref(),
            Self::Cal(e) => e.device.as_deref(),
            Self::Other(e) => e.extra.get("device").and_then(Value::as_str),
        }
    }

    fn prepare_for_upload(&mut self, app: &str) {
        match self {
            Self::Sgv(e) => super::Document::prepare_for_upload(e, app),
            Self::Mbg(e) => super::Document::prepare_for_upload(e, app),
            Self::Cal(e) => super::Document::prepare_for_upload(e, app),
            Self::Other(_) => super::prepare_meta(self, app),
        }
    }
}

/// Directions arrive as strings, but some uploaders send `null`, numbers or nothing.
fn opt_direction<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Direction>, D::Error> {
    Ok(match Option::<Value>::deserialize(d)? {
        Some(Value::String(s)) if !s.is_empty() => Some(Direction::parse(&s)),
        _ => None,
    })
}

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

    #[test]
    fn xdrip_sgv_round_trips_losslessly() {
        let raw = serde_json::json!({
            "_id": "65f1c2a8e4b0a1b2c3d4e5f6",
            "device": "xDrip-DexcomG6",
            "date": 1714564800000_i64,
            "dateString": "2024-05-01T14:00:00.000+0200",
            "sgv": 123,
            "delta": -2.5,
            "direction": "FortyFiveDown",
            "type": "sgv",
            "filtered": 131_000,
            "unfiltered": 131_000,
            "rssi": 100,
            "noise": 1,
            "sysTime": "2024-05-01T14:00:00.000+0200",
            "utcOffset": 120,
            "custom_field": {"kept": true}
        });
        let sgv: Sgv = serde_json::from_value(raw.clone()).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(sgv.direction, Some(Direction::FortyFiveDown));
        assert_eq!(sgv.meta.utc_offset, Some(120));
        assert_eq!(serde_json::to_value(&sgv).ok(), Some(raw));
    }

    #[test]
    fn lenient_on_broken_uploads() {
        let sgv: Sgv = serde_json::from_value(serde_json::json!({
            "sgv": "171", "date": "1714564800000", "direction": null, "noise": "", "type": "sgv"
        }))
        .unwrap_or_else(|e| panic!("{e}"));
        assert!((sgv.sgv.as_mgdl() - 171.0).abs() < f64::EPSILON);
        assert_eq!(sgv.direction, None);
        assert_eq!(sgv.noise, None);
    }

    #[test]
    fn entry_dispatches_on_type() {
        let entries: Vec<Entry> = serde_json::from_value(serde_json::json!([
            {"type": "sgv", "sgv": 100, "date": 1},
            {"type": "mbg", "mbg": 104, "date": 2},
            {"type": "cal", "slope": 900, "intercept": 30000, "scale": 1, "date": 3},
            {"type": "sensor", "date": 4}
        ]))
        .unwrap_or_default();
        assert!(matches!(entries[0], Entry::Sgv(_)));
        assert!(matches!(entries[1], Entry::Mbg(_)));
        assert!(matches!(entries[2], Entry::Cal(_)));
        assert_eq!(entries[3].kind(), Some("sensor"));
    }
}