Skip to main content

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    /// Called once per tick after `extract_deltas`, before the next `advance_tick`.
137    ///
138    /// Implementations should use this to clear ECS change-detection trackers so that
139    /// only mutations from the *next* simulation step appear as changed in the following
140    /// extraction.  The default no-op is safe for non-Bevy adapters.
141    fn post_extract(&mut self) {}
142
143    /// Spawns a new network-replicated entity and returns its `NetworkId`.
144    fn spawn_networked(&mut self) -> NetworkId;
145
146    /// Spawns a new network-replicated entity owned by a specific client.
147    fn spawn_networked_for(&mut self, _client_id: ClientId) -> NetworkId {
148        self.spawn_networked()
149    }
150
151    /// Despawn a network-replicated entity by its `NetworkId`.
152    ///
153    /// # Errors
154    ///
155    /// Returns [`WorldError`] if the entity with the given `network_id` does not exist.
156    fn despawn_networked(&mut self, network_id: NetworkId) -> Result<(), WorldError>;
157
158    /// Triggers a bulk spawn of entities for stress testing.
159    fn stress_test(&mut self, _count: u16, _rotate: bool) {}
160
161    /// Spawns a new network-replicated entity of a specific kind.
162    fn spawn_kind(&mut self, _kind: u16, _x: f32, _y: f32, _rot: f32) -> NetworkId {
163        self.spawn_networked() // Fallback to basic networked spawn
164    }
165
166    /// Spawns a new network-replicated entity of a specific kind for a specific client.
167    fn spawn_kind_for(
168        &mut self,
169        kind: u16,
170        x: f32,
171        y: f32,
172        rot: f32,
173        _client_id: ClientId,
174    ) -> NetworkId {
175        self.spawn_kind(kind, x, y, rot)
176    }
177
178    /// Spawns the authoritative session ship for a client and marks it as
179    /// the possession target.
180    ///
181    /// The default implementation delegates to `spawn_kind_for`.  Adapters
182    /// that support a `SessionShip` marker component should override this to
183    /// attach that marker so the input pipeline can gate `InputCommand`
184    /// processing exclusively to the session ship.
185    fn spawn_session_ship(
186        &mut self,
187        kind: u16,
188        x: f32,
189        y: f32,
190        rot: f32,
191        client_id: ClientId,
192    ) -> NetworkId {
193        self.spawn_kind_for(kind, x, y, rot, client_id)
194    }
195
196    /// Despawns all entities from the world.
197    fn clear_world(&mut self) {}
198
199    /// Queues a reliable game event to be sent to a specific client (or all if None).
200    fn queue_reliable_event(
201        &mut self,
202        _client_id: Option<ClientId>,
203        _event: crate::events::GameEvent,
204    ) {
205    }
206
207    /// Setups the initial world state (e.g. Master Room).
208    fn setup_world(&mut self) {}
209
210    /// Returns the Room `network_id` for a given entity, if any.
211    fn get_entity_room(&self, _network_id: NetworkId) -> Option<NetworkId> {
212        None
213    }
214
215    /// Returns the Room `network_id` for a client's session ship, if any.
216    fn get_client_room(&self, _client_id: ClientId) -> Option<NetworkId> {
217        None
218    }
219}
220
221/// Defines the serialization strategy for network payloads.
222///
223/// # Why this exists
224/// In Phase 1, this wraps `serde` + `rmp-serde` for rapid iteration.
225/// In Phase 3, this becomes a custom bit-packer that writes individual
226/// bits across 32-bit word boundaries for maximum compression.
227///
228/// # Performance contract
229/// Phase 1 (current) implementations may allocate during serialization
230/// to simplify development. However, avoiding allocations is a primary
231/// Phase 3 goal for the custom bit-packer.
232///
233/// In Phase 3, implementations MUST be allocation-free on the hot path.
234/// The `encode` method writes into a caller-provided buffer.
235/// The `decode` method reads from a borrowed slice.
236/// No `Vec`, no `String`, no heap allocation during steady-state operation.
237pub trait Encoder: Send + Sync {
238    /// Returns the codec ID used by this encoder.
239    ///
240    /// P1: `SerdeEncoder` = 1 (rmp-serde).
241    /// P3: `BitpackEncoder` = 2.
242    fn codec_id(&self) -> u32;
243
244    /// Serializes a replication event into the provided buffer.
245    ///
246    /// Returns the number of bytes written. If the buffer is too small,
247    /// returns `EncodeError::BufferOverflow` — the caller must retry
248    /// with a larger buffer or fragment the event.
249    ///
250    /// # Errors
251    /// Returns `EncodeError::BufferOverflow` if the buffer is too small.
252    fn encode(&self, event: &ReplicationEvent, buffer: &mut [u8]) -> Result<usize, EncodeError>;
253
254    /// Deserializes raw bytes into a component update.
255    ///
256    /// Returns `EncodeError::MalformedPayload` if the bytes do not
257    /// constitute a valid event. The caller must handle this gracefully
258    /// (log + discard) — malformed packets are expected from lossy networks.
259    ///
260    /// # Errors
261    /// Returns `EncodeError::MalformedPayload` on invalid payload bytes, or
262    /// `EncodeError::UnknownComponent` for unregistered component types.
263    fn decode(&self, buffer: &[u8]) -> Result<ComponentUpdate, EncodeError>;
264
265    /// Encodes a high-level `NetworkEvent` into a byte vector.
266    ///
267    /// # Errors
268    /// Returns `EncodeError::Io` if serialization fails.
269    fn encode_event(&self, event: &NetworkEvent) -> Result<Vec<u8>, EncodeError>;
270
271    /// Decodes a high-level `NetworkEvent` from a byte slice.
272    ///
273    /// # Errors
274    /// Returns `EncodeError::MalformedPayload` if the bytes are not a valid event.
275    fn decode_event(&self, data: &[u8]) -> Result<NetworkEvent, EncodeError>;
276
277    /// Returns the maximum possible encoded size for a single event.
278    ///
279    /// Used by the transport layer to pre-allocate datagram buffers.
280    /// Implementations should return a tight upper bound, not a wild guess.
281    fn max_encoded_size(&self) -> usize;
282}