Skip to main content

telemetry_across_codecs/
main.rs

1//! A log that outlived both its encoding and its schema.
2//!
3//! Every other example in this workspace writes one encoding and one event
4//! shape, which is the arrangement no system that has been deployed twice is
5//! ever in. This one writes JSON readings in whole degrees, upgrades, and then
6//! writes postcard readings in thousandths — into the same log, on the same
7//! file, read afterwards by one fold that branches on neither.
8//!
9//! Run with `cargo run -p telemetry-across-codecs`.
10//!
11//! # The two axes, and why they are different problems
12//!
13//! 1. **The encoding changed.** ADR-0021 puts a codec tag in a framing region
14//!    at the front of `Event::metadata`, which no store parses and no adapter
15//!    has to understand. A payload is decoded with the codec its own tag
16//!    names, resolved against the codecs the *build* carries — so a caller
17//!    holding `Json` folds a postcard event without branching, and without
18//!    knowing that it did. Nothing in this file passes two codecs anywhere.
19//! 2. **The event shape changed.** That the tag cannot help with, because the
20//!    bytes decode perfectly into a type that means something else. It is
21//!    handled the way it has always been handled — a new event *type* beside
22//!    the old one, the old type kept as a wire format, and an upcast in
23//!    `DomainEvent::decode`, which is handed the `EventType` precisely so it
24//!    can branch on it. This is the one example where that parameter is not
25//!    `_event_type`.
26//!
27//! # The hazard this file is built around
28//!
29//! A query is derived from `EVENT_TYPES` crossed with a model's scope. So the
30//! **old event type must stay in `EVENT_TYPES` forever**, even though nothing
31//! writes it any more: delete the name and the derived query stops nominating
32//! the old events, every fold silently loses its history, and nothing in the
33//! compiler, the linter or the conformance suite has an opinion about it. The
34//! name is what keeps the past inside the boundary.
35//!
36//! # What this does not demonstrate
37//!
38//! It does not rewrite the log, and nothing here is a migration in the sense
39//! of a backfill: the old events keep their old bytes and their old type name
40//! for as long as the store holds them. Nor is the postcard payload's size
41//! advantage a benchmark — two payloads are printed because the difference is
42//! the reason anybody does this, and `experiments/` is where this repository
43//! measures things.
44
45#![allow(clippy::print_stdout, reason = "the transcript is the point")]
46
47use std::path::{Path, PathBuf};
48
49use anyhow::{Result, bail};
50use happenstance::bytes::Bytes;
51use happenstance::{
52    Boundary, Codec, CodecError, CommandError, DecisionModel, DomainEvent, EventStore, EventType,
53    InvalidTag, Json, Postcard, Query, ReadOptions, Retry, SequencedEvent, Tag, Tags, collect,
54    commit, commit_with, read_decision_model,
55};
56use happenstance_sqlite::event_store::{SqliteEventStore, SqliteEventStoreError};
57use serde::{Deserialize, Serialize};
58
59/// How many times a command may be attempted before it gives up.
60///
61/// Spelled at every call site for the reason `course-subscriptions` gives: a
62/// loop whose only exit is success is a hang with better manners. This run is
63/// single-writer, so the bound is never spent.
64const ATTEMPTS: u32 = 3;
65
66/// The device this run reports for.
67const DEVICE: &str = "d-1";
68
69/// The coldest reading this application will accept, in thousandths of a degree.
70const MIN_MILLIDEGREES: i32 = -60_000;
71
72/// The hottest reading this application will accept, in thousandths of a degree.
73const MAX_MILLIDEGREES: i32 = 150_000;
74
75/// How many thousandths there are in a degree.
76///
77/// Named rather than spelled `1000` inside the upcast, because it is the whole
78/// content of the schema change and a reader should be able to find it.
79const PER_DEGREE: i32 = 1_000;
80
81#[tokio::main(flavor = "current_thread")]
82async fn main() -> Result<()> {
83    let path = database_path();
84    remove_database(&path);
85
86    println!("== the database this run writes to ==");
87    println!("   {}", path.display());
88
89    // The run is a function so every store and connection it builds is dropped
90    // before the file is removed — on Windows an open handle is what makes the
91    // cleanup silently fail and the next run start on the tail of this one.
92    let outcome = run(&path).await;
93    remove_database(&path);
94    outcome
95}
96
97/// Everything this program does, against one file.
98async fn run(path: &Path) -> Result<()> {
99    let events = SqliteEventStore::open(path)?;
100
101    the_version_that_shipped_first(&events).await?;
102    the_upgrade(&events).await?;
103    one_log_two_encodings(&events).await?;
104    one_fold_reads_both(&events).await?;
105
106    println!("\n== final log ==");
107    print_log(&events).await?;
108
109    Ok(())
110}
111
112// ---------------------------------------------------------------------------
113// The four things this program shows
114// ---------------------------------------------------------------------------
115
116/// Writes the log the old binary would have written.
117///
118/// It uses `commit`, which is `commit_with` with `Json` already chosen, and a
119/// domain type that has since been superseded. Nothing about this section
120/// knows that anything is going to change, which is the point — the events it
121/// writes are the ones a real deployment is stuck with.
122async fn the_version_that_shipped_first(events: &SqliteEventStore) -> Result<()> {
123    println!("\n== the version that shipped first ==");
124
125    register(events, DEVICE, "1.4.0").await?;
126    for celsius in [21, 23, 22] {
127        report_celsius(events, DEVICE, celsius).await?;
128    }
129    println!(
130        "   registered {DEVICE} on firmware 1.4.0 and wrote 3 readings, in whole degrees, as JSON"
131    );
132
133    match report_celsius(events, "d-9", 20).await {
134        Ok(()) => bail!("a reading from an unregistered device should have been refused"),
135        Err(err) => println!("   refused: {err}"),
136    }
137
138    Ok(())
139}
140
141/// Upgrades the firmware and starts writing the new shape, in the new encoding.
142///
143/// Both changes land here at once because that is how they arrive in practice
144/// — a deployment changes what it writes and how it writes it in the same
145/// release — and keeping them together is what makes the next two sections
146/// have anything to separate.
147async fn the_upgrade(events: &SqliteEventStore) -> Result<()> {
148    println!("\n== the upgrade ==");
149
150    upgrade_firmware(events, DEVICE, "2.0.0").await?;
151    for millidegrees in [22_500, 21_250] {
152        report_millidegrees(events, DEVICE, millidegrees).await?;
153    }
154    println!("   firmware 2.0.0, and 2 readings in thousandths of a degree, as postcard");
155
156    match report_millidegrees(events, DEVICE, 900_000).await {
157        Ok(()) => bail!("an implausible reading should have been refused"),
158        Err(err) => println!("   refused: {err}"),
159    }
160
161    Ok(())
162}
163
164/// Prints what each event was written with, and how big its payload is.
165///
166/// The codec tag is read out of the framing region **only to print it**. No
167/// application needs to do this and no adapter may: ADR-0021's whole point is
168/// that the region is opaque to the store, and the decode path below resolves
169/// it without anybody here looking. It is parsed here for the same reason a
170/// debugger exists.
171async fn one_log_two_encodings(events: &SqliteEventStore) -> Result<()> {
172    println!("\n== one log, two encodings ==");
173
174    let log = collect(events.read(&Query::all(), ReadOptions::new())).await?;
175    let mut seen = Vec::new();
176
177    for event in &log {
178        let codec = framed_codec(event).unwrap_or_else(|| "unframed".to_owned());
179        println!(
180            "   {:>3}  {:<22} {:<8} {} bytes",
181            event.position.get(),
182            event.event_type().as_str(),
183            codec,
184            event.event.data().len()
185        );
186        if !seen.contains(&codec) {
187            seen.push(codec);
188        }
189    }
190
191    if seen.len() < 2 {
192        bail!("the log holds only {seen:?}, so there are no two encodings to read across");
193    }
194    println!("   two encodings and two temperature types, in one store, side by side");
195
196    Ok(())
197}
198
199/// Folds the whole device history with one codec in hand.
200///
201/// The section the other three exist for. `Json` is the only codec named at
202/// this call site; the postcard readings arrive decoded anyway, because the
203/// framing region says what they were written with. The v1 readings arrive
204/// *upcast*, because `Telemetry::decode` was handed their event type and knew
205/// what to do with it.
206async fn one_fold_reads_both(events: &SqliteEventStore) -> Result<()> {
207    println!("\n== one fold reads both ==");
208
209    let device = DeviceId::new(DEVICE)?;
210    let mut readings = Readings::new(&device)?;
211
212    let query = readings.query()?;
213    let (found, _) = read_decision_model(events, &query).await?;
214    for event in &found {
215        readings.absorb(event, &Json)?;
216    }
217
218    println!(
219        "   the derived query nominated {} event(s), and one codec was named here: Json",
220        found.len()
221    );
222    println!(
223        "   firmware:   {}",
224        readings.firmware.as_deref().unwrap_or("unknown")
225    );
226    println!("   readings:   {:?}", readings.millidegrees);
227
228    // The upcast is the assertion. 21 degrees was written by a binary that had
229    // never heard of a thousandth, and it is 21000 here without anything in
230    // this function converting it.
231    if !readings.millidegrees.contains(&(21 * PER_DEGREE)) {
232        bail!(
233            "the first JSON reading did not arrive upcast: {:?}",
234            readings.millidegrees
235        );
236    }
237    println!(
238        "   21 whole degrees, written by a binary with no concept of a\n   \
239         thousandth, arrives as {} — the upcast is in `decode`, and the fold\n   \
240         below it has one temperature variant and no idea there were ever two",
241        21 * PER_DEGREE
242    );
243
244    Ok(())
245}
246
247// ---------------------------------------------------------------------------
248// Identity, validated once at the edge
249// ---------------------------------------------------------------------------
250
251/// A device, validated once into the tag its events carry.
252///
253/// The resolution the other examples reach, and for the same reason:
254/// `DomainEvent::tags` is infallible while `Tag::key_value` can refuse, so a
255/// domain type whose tags come from runtime values holds the validated form
256/// instead of rebuilding it on every call.
257#[derive(Debug, Clone, Serialize, Deserialize)]
258#[serde(try_from = "String", into = "String")]
259struct DeviceId {
260    /// The identifier as the application wrote it.
261    id: String,
262    /// The same value, validated into a tag.
263    tag: Tag,
264}
265
266impl DeviceId {
267    /// Validates `id` into the tag every event for this device is written with.
268    fn new(id: &str) -> Result<Self, InvalidTag> {
269        Ok(Self {
270            id: id.to_owned(),
271            tag: Tag::key_value("device", id)?,
272        })
273    }
274
275    /// The identifier as the application wrote it.
276    fn as_str(&self) -> &str {
277        &self.id
278    }
279}
280
281impl TryFrom<String> for DeviceId {
282    type Error = InvalidTag;
283
284    fn try_from(id: String) -> Result<Self, InvalidTag> {
285        Self::new(&id)
286    }
287}
288
289impl From<DeviceId> for String {
290    fn from(device: DeviceId) -> Self {
291        device.id
292    }
293}
294
295// ---------------------------------------------------------------------------
296// The domain, in the shape the old binary had
297// ---------------------------------------------------------------------------
298
299/// The event set the previous version of this application shipped.
300///
301/// **Kept rather than deleted, and it is not dead code.** It is the wire
302/// format of every reading written before the upgrade, and `Telemetry::decode`
303/// still reaches for it — an upcast is "decode with the type that wrote these
304/// bytes, then map forward", and the type that wrote them has to still exist
305/// for that sentence to be executable.
306///
307/// It writes two event types. `Telemetry` declares four, because it must
308/// nominate these two as well as its own.
309#[derive(Debug, Serialize, Deserialize)]
310enum Legacy {
311    /// A device came online. The same shape the new version writes.
312    DeviceRegistered {
313        /// The device now known.
314        device: DeviceId,
315        /// What it was running.
316        firmware: String,
317    },
318    /// A reading, in whole degrees Celsius.
319    TemperatureReported {
320        /// Which device reported.
321        device: DeviceId,
322        /// The reading, in whole degrees.
323        celsius: i32,
324    },
325}
326
327/// The four names this log has ever carried, declared once.
328///
329/// Two of them mean the same *reading* at different schema versions, and that is
330/// the whole point of this example — so they are named rather than indexed.
331/// Indexing the declaration list gave two subscripts that differ by one
332/// character and mean "what is written now" and "what may still be read";
333/// `TEMPERATURE_REPORTED_V2` and `TEMPERATURE_REPORTED` cannot be confused by a
334/// reader, or reordered into a lie by an editor.
335const DEVICE_REGISTERED: EventType = EventType::from_static("DeviceRegistered");
336/// See [`DEVICE_REGISTERED`].
337const FIRMWARE_UPGRADED: EventType = EventType::from_static("FirmwareUpgraded");
338/// The **v1** reading. Read-only: nothing writes this name any more.
339const TEMPERATURE_REPORTED: EventType = EventType::from_static("TemperatureReported");
340/// The **v2** reading, and what a reading written now carries.
341const TEMPERATURE_REPORTED_V2: EventType = EventType::from_static("TemperatureReportedV2");
342
343impl DomainEvent for Legacy {
344    const EVENT_TYPES: &'static [EventType] = &[DEVICE_REGISTERED, TEMPERATURE_REPORTED];
345
346    fn event_type(&self) -> EventType {
347        match self {
348            Self::DeviceRegistered { .. } => DEVICE_REGISTERED,
349            Self::TemperatureReported { .. } => TEMPERATURE_REPORTED,
350        }
351    }
352
353    fn tags(&self) -> Tags {
354        match self {
355            Self::DeviceRegistered { device, .. } | Self::TemperatureReported { device, .. } => {
356                [device.tag.clone()].into_iter().collect()
357            }
358        }
359    }
360
361    fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
362        codec.encode(self)
363    }
364
365    fn decode<C: Codec>(
366        codec: &C,
367        _event_type: &EventType,
368        data: &Bytes,
369    ) -> Result<Self, CodecError> {
370        codec.decode(data)
371    }
372}
373
374// ---------------------------------------------------------------------------
375// The domain, as it is now
376// ---------------------------------------------------------------------------
377
378/// Everything that can happen to a device, in this version's vocabulary.
379///
380/// One temperature variant, in thousandths. The fold does not know there were
381/// ever two shapes, and that is the whole reason the upcast lives in `decode`
382/// rather than in every `apply` that has to deal with a reading.
383#[derive(Debug, Serialize, Deserialize)]
384enum Telemetry {
385    /// A device came online.
386    DeviceRegistered {
387        /// The device now known.
388        device: DeviceId,
389        /// What it was running.
390        firmware: String,
391    },
392    /// A device's firmware changed.
393    FirmwareUpgraded {
394        /// The device upgraded.
395        device: DeviceId,
396        /// What it is running now.
397        firmware: String,
398    },
399    /// A reading, in thousandths of a degree.
400    TemperatureReported {
401        /// Which device reported.
402        device: DeviceId,
403        /// The reading, in thousandths of a degree.
404        millidegrees: i32,
405    },
406}
407
408impl DomainEvent for Telemetry {
409    /// Four names for three variants.
410    ///
411    /// `TemperatureReported` is the **old** name and nothing writes it any
412    /// more. It is declared because the query is derived from this list, so
413    /// removing it would stop every boundary nominating the readings written
414    /// before the upgrade — silently, and with no test, lint or conformance
415    /// rule that has an opinion. The list is where a log's past is kept alive.
416    const EVENT_TYPES: &'static [EventType] = &[
417        DEVICE_REGISTERED,
418        FIRMWARE_UPGRADED,
419        TEMPERATURE_REPORTED,
420        TEMPERATURE_REPORTED_V2,
421    ];
422
423    fn event_type(&self) -> EventType {
424        match self {
425            Self::DeviceRegistered { .. } => DEVICE_REGISTERED,
426            Self::FirmwareUpgraded { .. } => FIRMWARE_UPGRADED,
427            // The v2 name, never the v1 one. A reading written now is a v2
428            // reading; the v1 name is read-only. This used to be a subscript
429            // into the list above, carried by a comment saying "index 3, never
430            // index 2" — the comment a named constant makes unnecessary.
431            Self::TemperatureReported { .. } => TEMPERATURE_REPORTED_V2,
432        }
433    }
434
435    fn tags(&self) -> Tags {
436        match self {
437            Self::DeviceRegistered { device, .. }
438            | Self::FirmwareUpgraded { device, .. }
439            | Self::TemperatureReported { device, .. } => {
440                [device.tag.clone()].into_iter().collect()
441            }
442        }
443    }
444
445    fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
446        codec.encode(self)
447    }
448
449    /// Decodes a payload written for `event_type`, upcasting the old shape.
450    ///
451    /// **The one place in this workspace where that parameter is used.** The
452    /// codec tag in the framing region has already decided *how* these bytes
453    /// were encoded; what it cannot decide is what they meant, because a v1
454    /// reading deserialises perfectly into a number that is a thousand times
455    /// too small. Only the event type distinguishes them.
456    fn decode<C: Codec>(
457        codec: &C,
458        event_type: &EventType,
459        data: &Bytes,
460    ) -> Result<Self, CodecError> {
461        // The named v1 constant, not the literal `"TemperatureReported"`: one
462        // declaration, so there is no second spelling to get wrong.
463        if *event_type == TEMPERATURE_REPORTED {
464            return Ok(upcast(codec.decode::<Legacy>(data)?));
465        }
466
467        codec.decode(data)
468    }
469}
470
471/// Maps an event written by the previous version into this one's vocabulary.
472///
473/// Total, and deliberately so: an upcast that can fail is a log that can stop
474/// being readable, and there is nothing a caller could do about it at the
475/// moment it happens. Whole degrees multiply into thousandths exactly, so the
476/// conversion loses nothing — `i32` covers the plausible range this
477/// application accepts several hundred times over.
478fn upcast(old: Legacy) -> Telemetry {
479    match old {
480        Legacy::DeviceRegistered { device, firmware } => {
481            Telemetry::DeviceRegistered { device, firmware }
482        }
483        Legacy::TemperatureReported { device, celsius } => Telemetry::TemperatureReported {
484            device,
485            millidegrees: celsius.saturating_mul(PER_DEGREE),
486        },
487    }
488}
489
490/// Why a decision refused.
491///
492/// Every variant carries the value the transcript prints — `900000 is outside
493/// -60000..=150000` and never `invalid reading` — so a reader can act on the
494/// refusal where it is printed.
495#[derive(Debug, thiserror::Error)]
496enum Refusal {
497    /// Nothing can be reported for a device nobody registered.
498    #[error("device {device} is not registered")]
499    NotRegistered {
500        /// The unknown device.
501        device: String,
502    },
503    /// A device registers once.
504    #[error("device {device} is already registered")]
505    AlreadyRegistered {
506        /// The device already known.
507        device: String,
508    },
509    /// A reading outside the range this application accepts.
510    #[error("{millidegrees} is outside {MIN_MILLIDEGREES}..={MAX_MILLIDEGREES}")]
511    Implausible {
512        /// The reading that was refused.
513        millidegrees: i32,
514    },
515}
516
517// ---------------------------------------------------------------------------
518// The decision models
519// ---------------------------------------------------------------------------
520
521/// One device's history, as the old binary saw it.
522///
523/// It exists to write the old log honestly. Its query is derived from
524/// `Legacy::EVENT_TYPES`, which is the two names that version knew — which is
525/// exactly the boundary the old binary had, and exactly why the new one has to
526/// declare four.
527#[derive(Debug, Clone)]
528struct LegacyDevice {
529    /// The tags every event inside this boundary carries.
530    scope: Tags,
531    /// Whether the device has been registered.
532    registered: bool,
533}
534
535impl LegacyDevice {
536    /// Validates the scope once, here, where the caller already writes a `?`.
537    fn new(device: &DeviceId) -> Result<Self, InvalidTag> {
538        Ok(Self {
539            scope: Tags::from_pairs([("device", device.as_str())])?,
540            registered: false,
541        })
542    }
543}
544
545impl DecisionModel for LegacyDevice {
546    type Event = Legacy;
547
548    fn scope(&self) -> &Tags {
549        &self.scope
550    }
551
552    fn apply(&mut self, event: Self::Event) {
553        match event {
554            Legacy::DeviceRegistered { .. } => self.registered = true,
555            // A reading changes nothing this model decides on. The arm exists
556            // because the fold is exhaustive over the enum, and that
557            // exhaustiveness is the whole guarantee.
558            Legacy::TemperatureReported { .. } => {}
559        }
560    }
561}
562
563/// One device's history, in this version's vocabulary.
564///
565/// Its `millidegrees` holds every reading the boundary nominated, from both
566/// eras, in one unit. There is no branch in `apply` that knows about the
567/// upgrade, because by the time an event reaches `apply` it has already been
568/// upcast.
569#[derive(Debug, Clone)]
570struct Readings {
571    /// The tags every event inside this boundary carries.
572    scope: Tags,
573    /// Whether the device has been registered.
574    registered: bool,
575    /// What it is running now, once anything has said.
576    firmware: Option<String>,
577    /// Every reading the boundary nominated, in thousandths of a degree.
578    millidegrees: Vec<i32>,
579}
580
581impl Readings {
582    /// Validates the scope once, here, where the caller already writes a `?`.
583    fn new(device: &DeviceId) -> Result<Self, InvalidTag> {
584        Ok(Self {
585            scope: Tags::from_pairs([("device", device.as_str())])?,
586            registered: false,
587            firmware: None,
588            millidegrees: Vec::new(),
589        })
590    }
591}
592
593impl DecisionModel for Readings {
594    type Event = Telemetry;
595
596    fn scope(&self) -> &Tags {
597        &self.scope
598    }
599
600    fn apply(&mut self, event: Self::Event) {
601        match event {
602            Telemetry::DeviceRegistered { firmware, .. } => {
603                self.registered = true;
604                self.firmware = Some(firmware);
605            }
606            Telemetry::FirmwareUpgraded { firmware, .. } => self.firmware = Some(firmware),
607            Telemetry::TemperatureReported { millidegrees, .. } => {
608                self.millidegrees.push(millidegrees);
609            }
610        }
611    }
612}
613
614// ---------------------------------------------------------------------------
615// The command handlers, in two generations
616// ---------------------------------------------------------------------------
617
618/// Registers a device, as the old binary did: `commit`, so JSON.
619async fn register(events: &SqliteEventStore, device: &str, firmware: &str) -> Result<()> {
620    let device = DeviceId::new(device)?;
621    let boundary = LegacyDevice::new(&device)?;
622
623    commit(
624        events,
625        boundary,
626        Retry::attempts(ATTEMPTS.try_into()?),
627        |known: &LegacyDevice| {
628            if known.registered {
629                return Err(Refusal::AlreadyRegistered {
630                    device: device.id.clone(),
631                });
632            }
633            Ok(vec![Legacy::DeviceRegistered {
634                device: device.clone(),
635                firmware: firmware.to_owned(),
636            }])
637        },
638    )
639    .await
640    .map(|_| ())
641    .map_err(rejected)
642}
643
644/// Reports a reading in whole degrees, as the old binary did: `commit`, so JSON.
645async fn report_celsius(events: &SqliteEventStore, device: &str, celsius: i32) -> Result<()> {
646    let device = DeviceId::new(device)?;
647    let boundary = LegacyDevice::new(&device)?;
648
649    commit(
650        events,
651        boundary,
652        Retry::attempts(ATTEMPTS.try_into()?),
653        |known: &LegacyDevice| {
654            if !known.registered {
655                return Err(Refusal::NotRegistered {
656                    device: device.id.clone(),
657                });
658            }
659            Ok(vec![Legacy::TemperatureReported {
660                device: device.clone(),
661                celsius,
662            }])
663        },
664    )
665    .await
666    .map(|_| ())
667    .map_err(rejected)
668}
669
670/// Records a firmware upgrade, in the new encoding.
671async fn upgrade_firmware(events: &SqliteEventStore, device: &str, firmware: &str) -> Result<()> {
672    let device = DeviceId::new(device)?;
673    let boundary = Readings::new(&device)?;
674
675    commit_with(
676        events,
677        boundary,
678        &Postcard,
679        Retry::attempts(ATTEMPTS.try_into()?),
680        |known: &Readings| {
681            if !known.registered {
682                return Err(Refusal::NotRegistered {
683                    device: device.id.clone(),
684                });
685            }
686            Ok(vec![Telemetry::FirmwareUpgraded {
687                device: device.clone(),
688                firmware: firmware.to_owned(),
689            }])
690        },
691    )
692    .await
693    .map(|_| ())
694    .map_err(rejected)
695}
696
697/// Reports a reading in thousandths, in the new encoding.
698///
699/// `commit_with` and an explicit `&Postcard`. It is the ungated entry point —
700/// `commit` is this function with `Json` already chosen — and naming the codec
701/// here is the only difference between this handler and the one above it that
702/// wrote JSON. The boundary it reads is a `Readings`, so this decision is taken
703/// against a fold that has already absorbed the *JSON* events written before
704/// the upgrade.
705async fn report_millidegrees(
706    events: &SqliteEventStore,
707    device: &str,
708    millidegrees: i32,
709) -> Result<()> {
710    let device = DeviceId::new(device)?;
711    let boundary = Readings::new(&device)?;
712
713    commit_with(
714        events,
715        boundary,
716        &Postcard,
717        Retry::attempts(ATTEMPTS.try_into()?),
718        |known: &Readings| {
719            if !known.registered {
720                return Err(Refusal::NotRegistered {
721                    device: device.id.clone(),
722                });
723            }
724            if !(MIN_MILLIDEGREES..=MAX_MILLIDEGREES).contains(&millidegrees) {
725                return Err(Refusal::Implausible { millidegrees });
726            }
727            Ok(vec![Telemetry::TemperatureReported {
728                device: device.clone(),
729                millidegrees,
730            }])
731        },
732    )
733    .await
734    .map(|_| ())
735    .map_err(rejected)
736}
737
738// ---------------------------------------------------------------------------
739// Reading
740// ---------------------------------------------------------------------------
741
742/// The codec tag an event was framed with, read out of its metadata.
743///
744/// **Nothing needs this.** The framing region is documented as opaque to
745/// stores and adapters, and the decode path resolves it without any caller
746/// looking; it is parsed here so the transcript can show that two encodings
747/// really are sitting in one log. Every step is fallible and none of it
748/// panics: an event written by something that does not frame its payloads at
749/// all is a legitimate thing to meet, and it renders as `unframed`.
750fn framed_codec(event: &SequencedEvent) -> Option<String> {
751    let metadata = event.event.metadata()?;
752    let after_magic = metadata.strip_prefix(b"hpst\x01")?;
753    let end = after_magic.iter().position(|byte| *byte == 0xFF)?;
754
755    core::str::from_utf8(&after_magic[..end])
756        .ok()
757        .map(str::to_owned)
758}
759
760/// Prints every event in the store, in the order the store assigned.
761async fn print_log(events: &SqliteEventStore) -> Result<()> {
762    let log = collect(events.read(&Query::all(), ReadOptions::new())).await?;
763
764    for event in log {
765        println!(
766            "   {:>3}  {:<22} {:?}",
767            event.position.get(),
768            event.event_type().as_str(),
769            event.tags()
770        );
771    }
772
773    Ok(())
774}
775
776// ---------------------------------------------------------------------------
777// The file this run owns
778// ---------------------------------------------------------------------------
779
780/// Where this run's database lives.
781///
782/// Under the process id, so a `cargo run` and the test that spawns the binary
783/// never meet on one file.
784fn database_path() -> PathBuf {
785    std::env::temp_dir().join(format!("happenstance-telemetry-{}.db", std::process::id()))
786}
787
788/// Removes the database and the two files WAL mode keeps beside it.
789///
790/// Deleting only the `.db` and leaving `-wal` behind is how a "fresh" run
791/// starts on the tail of the last one.
792fn remove_database(path: &Path) {
793    for suffix in ["", "-wal", "-shm"] {
794        let mut name = path.as_os_str().to_owned();
795        name.push(suffix);
796        drop(std::fs::remove_file(PathBuf::from(name)));
797    }
798}
799
800/// Renders a command failure as the message the transcript prints.
801///
802/// `CommandError::Refused` carries the handler's *own* refusal, and that is
803/// what a reader must see: `CommandError`'s own `Display` says "the decision
804/// refused", which is a category rather than a value.
805fn rejected(err: CommandError<SqliteEventStoreError, Refusal>) -> anyhow::Error {
806    match err {
807        CommandError::Refused(refusal) => refusal.into(),
808        other => other.into(),
809    }
810}