two_devices_one_seat/uplink.rs
1//! The device's link to central: an [`Exchange`] that is a function call.
2//!
3//! Every pull and push a device makes is encoded into the sync envelope by
4//! [`RemoteSyncPeer`](happenstance_sync::RemoteSyncPeer), handed here as
5//! bytes, answered by [`serve_sync_adjudicated`] over central's
6//! [`StoreSyncPeer`], which judges each push by central's rule before it
7//! lands, and decoded on the way back. That is the whole network
8//! path with the network replaced by a call, so replacing [`Uplink`] with an
9//! HTTP client changes the transport and nothing else.
10//!
11//! # Why `Cell`, and why the bare `Exchange`
12//!
13//! The story turns the signal off and on while a peer holds the exchange and
14//! an edge borrows the peer, so the switch is flipped through `&self`. `Cell`
15//! is the smallest tool for that: a `Copy` value replaced whole, no borrow to
16//! hold, no lock. It costs `Sync`, which nothing here needs, because the story
17//! runs on one thread. So this implements the **bare** [`Exchange`], the
18//! flavour without a `Send` bound; the runner takes `!Send` peers (SY-17).
19//! The alternative was an `AtomicBool` and `SendExchange`, which buys thread
20//! safety nobody uses at the price of a memory-ordering argument.
21//!
22//! # Why there is no timeout
23//!
24//! One round trip is one function call into a local file. There is no
25//! external I/O to bound; an HTTP `Exchange` puts its timeout here, and maps
26//! it to [`FailureClass::Transient`].
27
28use core::cell::Cell;
29
30use happenstance::EventStore;
31use happenstance_sqlite::event_store::SqliteEventStore;
32use happenstance_sync::runner::Adjudicate;
33use happenstance_sync::wire::Route;
34use happenstance_sync::{
35 Classify, Exchange, FailureClass, ServeError, StoreSyncPeer, serve_sync_adjudicated,
36};
37
38use crate::rule::{CentralRule, RuleError};
39
40/// The central store's type.
41///
42/// The sync path names central only through this alias, [`CentralError`] and
43/// [`CentralPeer`], so on that path a Postgres central changes this one line.
44/// It is not the whole swap: central's file is opened by the same SQLite
45/// `Site` the devices use, its read model writes through a SQLite batch, and
46/// some `StoryError` variants name SQLite's errors for every place. The
47/// crate's overview lists each, under *Swapping central for Postgres or Neon*.
48pub type Central = SqliteEventStore;
49
50/// What central's store fails with, on its read half and its ingest half
51/// alike, as the [`EventStore`] contract names it rather than the adapter.
52pub type CentralError = <Central as EventStore>::Error;
53
54/// Central's side of a sync: its log to read, its ingest to write, and the
55/// rule it judges each push by before the push lands (SY-7).
56///
57/// The rule is a type parameter with central's own as its default, so the
58/// test that shows what goes wrong without it can mount one that answers
59/// nothing, while the binary has no way to.
60pub type CentralPeer<A = CentralRule> = StoreSyncPeer<Central, Central, A>;
61
62/// Whether a device has signal.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum Link {
65 /// Requests reach central.
66 Up,
67 /// Nothing leaves the device.
68 Down,
69 /// A pull reaches central and its answer comes back; a push is lost
70 /// before it leaves. The case that shows a failed push loses no event: the
71 /// step fails in its push phase, after the pull has already landed.
72 PullOnly,
73}
74
75/// One device's link to central, whose peer judges what it is pushed by `A`.
76///
77/// No bound on the struct, as on every generic type here: the bound sits on
78/// the `Exchange` impl, the one place that calls the rule.
79#[derive(Debug)]
80pub struct Uplink<A = CentralRule> {
81 far: CentralPeer<A>,
82 link: Cell<Link>,
83}
84
85impl<A> Uplink<A> {
86 /// A link to `far`, with signal.
87 #[must_use]
88 pub const fn new(far: CentralPeer<A>) -> Self {
89 Self {
90 far,
91 link: Cell::new(Link::Up),
92 }
93 }
94
95 /// Turns the signal on or off, or leaves it able to pull only.
96 pub fn set(&self, link: Link) {
97 self.link.set(link);
98 }
99}
100
101/// Any rule central mounts fails as a [`RuleError`], so every uplink fails
102/// with one [`UplinkError`] and a sync failure has one type, whichever rule
103/// judged it.
104impl<A: Adjudicate<Error = RuleError>> Exchange for Uplink<A> {
105 type Error = UplinkError;
106
107 async fn exchange(&self, route: Route, request: Vec<u8>) -> Result<Vec<u8>, UplinkError> {
108 // A pull-only link lets exactly the pull through and loses every other
109 // route: the push, and, because `Route` is non-exhaustive, any route a
110 // later version adds.
111 match (self.link.get(), route) {
112 (Link::Up, _) | (Link::PullOnly, Route::Pull) => {
113 Ok(serve_sync_adjudicated(&self.far, route, &request).await?)
114 }
115 (Link::Down | Link::PullOnly, _) => Err(UplinkError::Offline),
116 }
117 }
118}
119
120/// Why an exchange failed.
121#[derive(Debug, thiserror::Error)]
122pub enum UplinkError {
123 /// No signal: the request never left the device.
124 #[error("no signal: the request never left the device")]
125 Offline,
126 /// Central answered with a failure of its own, its rule's included.
127 #[error(transparent)]
128 Serve(#[from] ServeError<CentralError, CentralError, RuleError>),
129}
130
131impl Classify for UplinkError {
132 /// No signal is the textbook transient failure: nothing was sent, and
133 /// the same request will do when the signal returns. Central's own
134 /// failures keep the class central stated (SY-36).
135 fn class(&self) -> FailureClass {
136 match self {
137 Self::Offline => FailureClass::Transient,
138 Self::Serve(error) => error.class(),
139 }
140 }
141}