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 /// Injects parsed state updates from the network into the ECS.
114 ///
115 /// On the server, these are client inputs (movement commands, actions).
116 /// On the client, these are authoritative state corrections from the server.
117 ///
118 /// The `ClientId` in the update pair provides context for ownership verification
119 /// to prevent unauthorized updates from malicious clients.
120 fn apply_updates(&mut self, updates: &[(ClientId, ComponentUpdate)]);
121
122 /// Advances the world change tick at the start of each server tick, before inputs are applied.
123 fn advance_tick(&mut self) {}
124
125 /// Runs a single simulation frame for the ECS.
126 fn simulate(&mut self) {}
127
128 /// Spawns a new network-replicated entity and returns its `NetworkId`.
129 fn spawn_networked(&mut self) -> NetworkId;
130
131 /// Spawns a new network-replicated entity owned by a specific client.
132 fn spawn_networked_for(&mut self, _client_id: ClientId) -> NetworkId {
133 self.spawn_networked()
134 }
135
136 /// Despawn a network-replicated entity by its `NetworkId`.
137 ///
138 /// # Errors
139 ///
140 /// Returns [`WorldError`] if the entity with the given `network_id` does not exist.
141 fn despawn_networked(&mut self, network_id: NetworkId) -> Result<(), WorldError>;
142
143 /// Triggers a bulk spawn of entities for stress testing.
144 fn stress_test(&mut self, _count: u16, _rotate: bool) {}
145
146 /// Spawns a new network-replicated entity of a specific kind.
147 fn spawn_kind(&mut self, _kind: u16, _x: f32, _y: f32, _rot: f32) -> NetworkId {
148 self.spawn_networked() // Fallback to basic networked spawn
149 }
150
151 /// Despawns all entities from the world.
152 fn clear_world(&mut self) {}
153}
154
155/// Defines the serialization strategy for network payloads.
156///
157/// # Why this exists
158/// In Phase 1, this wraps `serde` + `rmp-serde` for rapid iteration.
159/// In Phase 3, this becomes a custom bit-packer that writes individual
160/// bits across 32-bit word boundaries for maximum compression.
161///
162/// # Performance contract
163/// Phase 1 (current) implementations may allocate during serialization
164/// to simplify development. However, avoiding allocations is a primary
165/// Phase 3 goal for the custom bit-packer.
166///
167/// In Phase 3, implementations MUST be allocation-free on the hot path.
168/// The `encode` method writes into a caller-provided buffer.
169/// The `decode` method reads from a borrowed slice.
170/// No `Vec`, no `String`, no heap allocation during steady-state operation.
171pub trait Encoder: Send + Sync {
172 /// Serializes a replication event into the provided buffer.
173 ///
174 /// Returns the number of bytes written. If the buffer is too small,
175 /// returns `EncodeError::BufferOverflow` — the caller must retry
176 /// with a larger buffer or fragment the event.
177 ///
178 /// # Errors
179 /// Returns `EncodeError::BufferOverflow` if the buffer is too small.
180 fn encode(&self, event: &ReplicationEvent, buffer: &mut [u8]) -> Result<usize, EncodeError>;
181
182 /// Deserializes raw bytes into a component update.
183 ///
184 /// Returns `EncodeError::MalformedPayload` if the bytes do not
185 /// constitute a valid event. The caller must handle this gracefully
186 /// (log + discard) — malformed packets are expected from lossy networks.
187 ///
188 /// # Errors
189 /// Returns `EncodeError::MalformedPayload` on invalid payload bytes, or
190 /// `EncodeError::UnknownComponent` for unregistered component types.
191 fn decode(&self, buffer: &[u8]) -> Result<ComponentUpdate, EncodeError>;
192
193 /// Encodes a high-level `NetworkEvent` into a byte vector.
194 ///
195 /// # Errors
196 /// Returns `EncodeError::Io` if serialization fails.
197 fn encode_event(&self, event: &NetworkEvent) -> Result<Vec<u8>, EncodeError>;
198
199 /// Decodes a high-level `NetworkEvent` from a byte slice.
200 ///
201 /// # Errors
202 /// Returns `EncodeError::MalformedPayload` if the bytes are not a valid event.
203 fn decode_event(&self, data: &[u8]) -> Result<NetworkEvent, EncodeError>;
204
205 /// Returns the maximum possible encoded size for a single event.
206 ///
207 /// Used by the transport layer to pre-allocate datagram buffers.
208 /// Implementations should return a tight upper bound, not a wild guess.
209 fn max_encoded_size(&self) -> usize;
210}