dotzuki_engine/link/mod.rs
1//! Link-play transport seam — game-agnostic and zero-I/O.
2//!
3//! Any JRPG on this engine can do link play (battle, trade, … between two
4//! players) by plugging a [`NetworkTransport`] implementation into its link
5//! state machines. The engine defines the transport interface; each game
6//! defines its own wire protocol — the message type `M` (e.g. a serde enum
7//! serialized as JSON lines over TCP).
8//!
9//! This module is deliberately **zero-I/O**: it defines the trait, the shared
10//! [`TransportError`], the [`LinkRole`] connection-side identity, and an
11//! in-memory [`ChannelTransport`] pair for local/testing use. Real transports
12//! (TCP sockets, Web `BroadcastChannel`, …) live in the game or platform
13//! layer, never here. The one exception is [`codec`]: the newline-framed
14//! JSON codec every JSON-line transport shares. It is pure serde (no I/O),
15//! so it lives here where native and wasm transports can both build on it —
16//! keeping the framing byte-identical across transports.
17//!
18//! ## What lives here vs. in the game
19//!
20//! * **Engine (this module):** the [`NetworkTransport<M>`] trait,
21//! [`TransportError`], [`ChannelTransport<M>`], [`LinkRole`] (which
22//! side clocks/hosts the connection — needed by any asymmetric handshake),
23//! and the shared JSON-line [`codec`] ([`codec::encode_line`] /
24//! [`codec::decode_line`] / [`codec::Frame`]).
25//! * **Game:** the wire message type `M`, the link state machines (battles,
26//! trades, …), and the concrete transports that implement this trait.
27//!
28//! ## Why `NetworkTransport<M>` (a type parameter, not an associated type)
29//!
30//! The message type is a plain generic parameter so implementations stay
31//! one line (`impl<M> NetworkTransport<M> for ChannelTransport<M>`), trait
32//! objects read as `dyn NetworkTransport<MyMessage>`, and the trait is usable
33//! with several protocols if a transport ever needs that. An associated type
34//! (`type Message`) would be equally valid — each transport would then own
35//! exactly one message type — but the parameter was chosen for the least
36//! ceremony across implementors.
37//!
38//! ## Usage
39//!
40//! ```text
41//! // Game side: the wire protocol (a serde enum, a byte protocol, …).
42//! enum MyMessage { Hello, Bye }
43//!
44//! // In-memory pair for local play / tests.
45//! let (mut t_a, mut t_b) = ChannelTransport::<MyMessage>::new_pair();
46//! t_a.send(MyMessage::Hello).unwrap();
47//! assert_eq!(t_b.recv().unwrap(), MyMessage::Hello);
48//! ```
49
50use std::sync::mpsc;
51
52pub mod codec;
53
54/// Errors a [`NetworkTransport`] can report.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum TransportError {
57 /// The peer is gone (socket closed, channel dropped, …).
58 Disconnected,
59 /// The operation timed out.
60 Timeout,
61 /// The message could not be (de)serialized on the wire.
62 SerializationError(String),
63 /// An underlying I/O failure (hosted by the implementing transport).
64 IoError(String),
65}
66
67impl std::fmt::Display for TransportError {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 match self {
70 TransportError::Disconnected => write!(f, "peer disconnected"),
71 TransportError::Timeout => write!(f, "operation timed out"),
72 TransportError::SerializationError(e) => write!(f, "serialization error: {}", e),
73 TransportError::IoError(e) => write!(f, "I/O error: {}", e),
74 }
75 }
76}
77
78/// A bidirectional message transport for link play.
79///
80/// Implementors are the wire half of a link connection: they move whole
81/// messages of the game's protocol type `M` in and out, hiding framing,
82/// channels, threads, and sockets. The methods mirror `std::sync::mpsc`
83/// semantics: [`Self::recv`] blocks until a message or a disconnect arrives,
84/// [`Self::try_recv`] never blocks.
85///
86/// The engine defines this interface; each game implements it for its own
87/// wire message type (see the [module docs](self)).
88pub trait NetworkTransport<M> {
89 /// Send one message to the peer.
90 fn send(&mut self, msg: M) -> Result<(), TransportError>;
91
92 /// Block until a message arrives or the connection fails.
93 fn recv(&mut self) -> Result<M, TransportError>;
94
95 /// Non-blocking receive: `Ok(None)` when nothing is pending,
96 /// `Err(Disconnected)` once the peer is gone.
97 fn try_recv(&mut self) -> Result<Option<M>, TransportError>;
98}
99
100/// An in-memory [`NetworkTransport`] pair over `std::sync::mpsc` channels.
101///
102/// The engine's built-in mock: the two ends of one link connection with
103/// zero I/O, used for local play and tests. Dropping one end makes the
104/// other report [`TransportError::Disconnected`] exactly like a closed
105/// socket.
106pub struct ChannelTransport<M> {
107 tx: mpsc::Sender<M>,
108 rx: mpsc::Receiver<M>,
109}
110
111impl<M> ChannelTransport<M> {
112 /// Create a connected pair — the two ends of one link connection.
113 pub fn new_pair() -> (Self, Self) {
114 let (tx_a, rx_b) = mpsc::channel();
115 let (tx_b, rx_a) = mpsc::channel();
116 (
117 ChannelTransport { tx: tx_a, rx: rx_a },
118 ChannelTransport { tx: tx_b, rx: rx_b },
119 )
120 }
121}
122
123impl<M> NetworkTransport<M> for ChannelTransport<M> {
124 fn send(&mut self, msg: M) -> Result<(), TransportError> {
125 self.tx.send(msg).map_err(|_| TransportError::Disconnected)
126 }
127
128 fn recv(&mut self) -> Result<M, TransportError> {
129 self.rx.recv().map_err(|_| TransportError::Disconnected)
130 }
131
132 fn try_recv(&mut self) -> Result<Option<M>, TransportError> {
133 match self.rx.try_recv() {
134 Ok(msg) => Ok(Some(msg)),
135 Err(mpsc::TryRecvError::Empty) => Ok(None),
136 Err(mpsc::TryRecvError::Disconnected) => Err(TransportError::Disconnected),
137 }
138 }
139}
140
141/// Which side of a link connection the local player is.
142///
143/// Link protocols with an asymmetric handshake need a host/guest
144/// distinction — the original Game Boy link cable called it the "internal
145/// clock" (the hosting side: drives synchronization, wins
146/// simultaneous-request ties) versus the "external clock" (the joining
147/// side: starts the handshake, defers to the host). Games map this onto
148/// their own roles (the link club, for example, calls the two
149/// sides the "player" and "friend" warp spots).
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub enum LinkRole {
152 /// The clocking (hosting) side of the connection.
153 Host,
154 /// The joining (guest) side of the connection.
155 Guest,
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 #[test]
163 fn round_trip_send_recv() {
164 let (mut a, mut b) = ChannelTransport::new_pair();
165 a.send("hello".to_string()).unwrap();
166 assert_eq!(b.recv().unwrap(), "hello");
167 b.send("world".to_string()).unwrap();
168 assert_eq!(a.recv().unwrap(), "world");
169 }
170
171 #[test]
172 fn try_recv_empty_then_message() {
173 let (mut a, mut b) = ChannelTransport::new_pair();
174 assert_eq!(a.try_recv().unwrap(), None);
175 b.send(7).unwrap();
176 assert_eq!(a.try_recv().unwrap(), Some(7));
177 }
178
179 #[test]
180 fn pair_ends_are_independent() {
181 let (mut a, mut b) = ChannelTransport::new_pair();
182 a.send(1).unwrap();
183 // Our own send is not looped back to us.
184 assert_eq!(a.try_recv().unwrap(), None);
185 assert_eq!(b.try_recv().unwrap(), Some(1));
186 }
187
188 #[test]
189 fn drop_reports_disconnected_to_peer() {
190 let (a, mut b) = ChannelTransport::<u32>::new_pair();
191 drop(a);
192 assert_eq!(b.try_recv(), Err(TransportError::Disconnected));
193 assert_eq!(b.recv(), Err(TransportError::Disconnected));
194 }
195
196 #[test]
197 fn send_after_peer_drop_reports_disconnected() {
198 let (mut a, b) = ChannelTransport::new_pair();
199 drop(b);
200 assert_eq!(a.send(1), Err(TransportError::Disconnected));
201 }
202
203 #[test]
204 fn transport_error_display() {
205 assert_eq!(
206 TransportError::Disconnected.to_string(),
207 "peer disconnected"
208 );
209 assert_eq!(TransportError::Timeout.to_string(), "operation timed out");
210 assert_eq!(
211 TransportError::SerializationError("bad json".into()).to_string(),
212 "serialization error: bad json"
213 );
214 assert_eq!(
215 TransportError::IoError("reset".into()).to_string(),
216 "I/O error: reset"
217 );
218 }
219}