aetheris_protocol/traits.rs
1//! Core trait contracts for the Aetheris Engine.
2//!
3//! These traits form the boundary between the engine's protocol logic and
4//! external dependencies (ECS, Transport, Serialization).
5
6use async_trait::async_trait;
7
8pub use crate::error::{EncodeError, TransportError, WorldError};
9use crate::events::{ComponentUpdate, NetworkEvent, ReplicationEvent};
10pub use crate::types::{ClientId, LocalId, NetworkId, NetworkIdAllocator};
11
12/// Abstracts the underlying network transport.
13///
14/// # Why this exists
15/// In Phase 1, this wraps `renet`. In Phase 3, this wraps `quinn` directly.
16/// The game loop never knows which library is underneath.
17///
18/// # Reliability semantics
19/// - `send_unreliable`: Fire-and-forget. Used for position updates that are
20/// invalidated by the next tick. If the packet is lost, the client simply
21/// interpolates from the last known position.
22/// - `send_reliable`: Ordered and guaranteed delivery. Used for discrete game
23/// events (damage, death, loot) where loss would desync the client.
24#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
25#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
26pub trait GameTransport: Sync + GameTransportBounds {
27 /// Sends an unreliable datagram to a specific client.
28 ///
29 /// Returns immediately. The transport layer may silently drop this packet
30 /// under congestion — this is by design for volatile data.
31 ///
32 /// # Errors
33 /// Returns `TransportError::ClientNotConnected` if the `client_id` is unknown,
34 /// or `TransportError::PayloadTooLarge` if the packet exceeds MTU.
35 async fn send_unreliable(&self, client_id: ClientId, data: &[u8])
36 -> Result<(), TransportError>;
37
38 /// Sends a reliable, ordered message to a specific client.
39 ///
40 /// The transport guarantees delivery and ordering within a single stream.
41 /// Callers must not assume delivery timing — only eventual delivery.
42 ///
43 /// # Errors
44 /// Returns `TransportError::ClientNotConnected` if the `client_id` is unknown,
45 /// or `TransportError::Io` on underlying transport failure.
46 async fn send_reliable(&self, client_id: ClientId, data: &[u8]) -> Result<(), TransportError>;
47
48 /// Broadcasts an unreliable datagram to all connected clients.
49 ///
50 /// Useful for world-wide events (weather changes, global announcements)
51 /// where individual targeting is unnecessary.
52 ///
53 /// # Errors
54 /// Returns `TransportError::PayloadTooLarge` if the packet exceeds MTU.
55 async fn broadcast_unreliable(&self, data: &[u8]) -> Result<(), TransportError>;
56
57 /// Drains all pending inbound network events since the last call.
58 ///
59 /// This is called exactly once per tick at the top of the game loop.
60 /// Events include: client connections, disconnections, and inbound data.
61 ///
62 /// # Errors
63 /// Returns `TransportError::Io` on underlying transport failure or internal
64 /// state corruption (e.g. mutex poisoning).
65 async fn poll_events(&mut self) -> Result<Vec<NetworkEvent>, TransportError>;
66
67 /// Returns the number of currently connected clients.
68 async fn connected_client_count(&self) -> usize;
69}
70
71/// Helper trait to provide conditional `Send` bounds for [`GameTransport`].
72#[cfg(target_arch = "wasm32")]
73pub trait GameTransportBounds {}
74#[cfg(target_arch = "wasm32")]
75impl<T: ?Sized> GameTransportBounds for T {}
76
77#[cfg(not(target_arch = "wasm32"))]
78pub trait GameTransportBounds: Send {}
79#[cfg(not(target_arch = "wasm32"))]
80impl<T: ?Sized + Send> GameTransportBounds for T {}
81
82/// The ECS Facade. Translates between the engine's protocol-level types
83/// and the concrete ECS's internal representation.
84///
85/// # Why this exists
86/// Bevy uses `Entity`, an opaque 64-bit handle with generation bits.
87/// Our network protocol uses `NetworkId`, a globally unique `u64`.
88/// This trait is the translation layer. The game loop never touches
89/// a Bevy `Entity` directly — it only speaks `NetworkId`.
90///
91/// # Delta extraction
92/// On every tick, modified components are detected and emitted as
93/// `ReplicationEvent` items. Only changed fields are sent — never the full
94/// component. This is the foundation of delta compression.
95pub trait WorldState: Send {
96 /// Maps a protocol-level `NetworkId` to the ECS's local entity handle.
97 ///
98 /// Returns `None` if the entity has been despawned or never existed.
99 fn get_local_id(&self, network_id: NetworkId) -> Option<LocalId>;
100
101 /// Maps a local ECS entity handle back to its protocol-level `NetworkId`.
102 ///
103 /// Returns `None` if the entity is not network-replicated.
104 fn get_network_id(&self, local_id: LocalId) -> Option<NetworkId>;
105
106 /// Extracts replication deltas for all components modified since the last tick.
107 ///
108 /// The returned events contain only the *changed* fields, not full snapshots.
109 /// The caller (the game loop) never interprets these events — it passes them
110 /// directly to the `Encoder` for serialization.
111 fn extract_deltas(&mut self) -> Vec<ReplicationEvent>;
112
113 /// Extracts discrete game events that should be sent reliably.
114 ///
115 /// Returns a list of `(Target ClientId, WireEvent)`.
116 /// If `ClientId` is `None`, the event should be broadcast to all authenticated clients.
117 fn extract_reliable_events(&mut self) -> Vec<(Option<ClientId>, crate::events::WireEvent)> {
118 Vec::new()
119 }
120
121 /// Injects parsed state updates from the network into the ECS.
122 ///
123 /// On the server, these are client inputs (movement commands, actions).
124 /// On the client, these are authoritative state corrections from the server.
125 ///
126 /// The `ClientId` in the update pair provides context for ownership verification
127 /// to prevent unauthorized updates from malicious clients.
128 fn apply_updates(&mut self, updates: &[(ClientId, ComponentUpdate)]);
129
130 /// Advances the world change tick at the start of each server tick, before inputs are applied.
131 fn advance_tick(&mut self) {}
132
133 /// Runs a single simulation frame for the ECS.
134 fn simulate(&mut self) {}
135
136 /// Spawns a new network-replicated entity and returns its `NetworkId`.
137 fn spawn_networked(&mut self) -> NetworkId;
138
139 /// Spawns a new network-replicated entity owned by a specific client.
140 fn spawn_networked_for(&mut self, _client_id: ClientId) -> NetworkId {
141 self.spawn_networked()
142 }
143
144 /// Despawn a network-replicated entity by its `NetworkId`.
145 ///
146 /// # Errors
147 ///
148 /// Returns [`WorldError`] if the entity with the given `network_id` does not exist.
149 fn despawn_networked(&mut self, network_id: NetworkId) -> Result<(), WorldError>;
150
151 /// Triggers a bulk spawn of entities for stress testing.
152 fn stress_test(&mut self, _count: u16, _rotate: bool) {}
153
154 /// Spawns a new network-replicated entity of a specific kind.
155 fn spawn_kind(&mut self, _kind: u16, _x: f32, _y: f32, _rot: f32) -> NetworkId {
156 self.spawn_networked() // Fallback to basic networked spawn
157 }
158
159 /// Despawns all entities from the world.
160 fn clear_world(&mut self) {}
161}
162
163/// Defines the serialization strategy for network payloads.
164///
165/// # Why this exists
166/// In Phase 1, this wraps `serde` + `rmp-serde` for rapid iteration.
167/// In Phase 3, this becomes a custom bit-packer that writes individual
168/// bits across 32-bit word boundaries for maximum compression.
169///
170/// # Performance contract
171/// Phase 1 (current) implementations may allocate during serialization
172/// to simplify development. However, avoiding allocations is a primary
173/// Phase 3 goal for the custom bit-packer.
174///
175/// In Phase 3, implementations MUST be allocation-free on the hot path.
176/// The `encode` method writes into a caller-provided buffer.
177/// The `decode` method reads from a borrowed slice.
178/// No `Vec`, no `String`, no heap allocation during steady-state operation.
179pub trait Encoder: Send + Sync {
180 /// Returns the codec ID used by this encoder.
181 ///
182 /// P1: `SerdeEncoder` = 1 (rmp-serde).
183 /// P3: `BitpackEncoder` = 2.
184 fn codec_id(&self) -> u32;
185
186 /// Serializes a replication event into the provided buffer.
187 ///
188 /// Returns the number of bytes written. If the buffer is too small,
189 /// returns `EncodeError::BufferOverflow` — the caller must retry
190 /// with a larger buffer or fragment the event.
191 ///
192 /// # Errors
193 /// Returns `EncodeError::BufferOverflow` if the buffer is too small.
194 fn encode(&self, event: &ReplicationEvent, buffer: &mut [u8]) -> Result<usize, EncodeError>;
195
196 /// Deserializes raw bytes into a component update.
197 ///
198 /// Returns `EncodeError::MalformedPayload` if the bytes do not
199 /// constitute a valid event. The caller must handle this gracefully
200 /// (log + discard) — malformed packets are expected from lossy networks.
201 ///
202 /// # Errors
203 /// Returns `EncodeError::MalformedPayload` on invalid payload bytes, or
204 /// `EncodeError::UnknownComponent` for unregistered component types.
205 fn decode(&self, buffer: &[u8]) -> Result<ComponentUpdate, EncodeError>;
206
207 /// Encodes a high-level `NetworkEvent` into a byte vector.
208 ///
209 /// # Errors
210 /// Returns `EncodeError::Io` if serialization fails.
211 fn encode_event(&self, event: &NetworkEvent) -> Result<Vec<u8>, EncodeError>;
212
213 /// Decodes a high-level `NetworkEvent` from a byte slice.
214 ///
215 /// # Errors
216 /// Returns `EncodeError::MalformedPayload` if the bytes are not a valid event.
217 fn decode_event(&self, data: &[u8]) -> Result<NetworkEvent, EncodeError>;
218
219 /// Returns the maximum possible encoded size for a single event.
220 ///
221 /// Used by the transport layer to pre-allocate datagram buffers.
222 /// Implementations should return a tight upper bound, not a wild guess.
223 fn max_encoded_size(&self) -> usize;
224}