mill_net/tcp/traits.rs
1use crate::errors::Result;
2use crate::errors::{NetworkError, NetworkEvent};
3
4use super::ServerContext;
5
6/// Unique identifier for connections.
7///
8/// Each TCP connection is assigned a unique ConnectionId when accepted or established.
9/// The ID is generated atomically and remains constant for the connection's lifetime.
10///
11/// ConnectionIds are used to target specific connections for operations like sending
12/// data or closing connections.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct ConnectionId(pub u64);
15
16impl ConnectionId {
17 pub fn new(id: u64) -> Self {
18 ConnectionId(id)
19 }
20
21 pub fn as_u64(&self) -> u64 {
22 self.0
23 }
24}
25
26/// Handler for network events on TCP connections.
27///
28/// Implement this trait to define how your application responds to network events.
29/// All methods except on_data have default implementations that do nothing.
30///
31/// The handler is invoked by worker threads from the event loop's thread pool,
32/// so implementations must be thread-safe (Send + Sync).
33///
34/// ## Execution Context
35///
36/// Handler methods are called from worker threads in the thread pool. Multiple
37/// handlers may execute concurrently for different connections. Your implementation
38/// should be efficient to avoid blocking worker threads.
39///
40/// ## Error Handling
41///
42/// Return errors from handler methods to indicate processing failures. The connection
43/// will be closed automatically when handlers return errors from on_data.
44pub trait NetworkHandler: Send + Sync + 'static {
45 /// Called when a non-error network event occurs
46 fn on_event(&self, ctx: &ServerContext, event: NetworkEvent) -> Result<()> {
47 let _ = (ctx, event);
48 Ok(())
49 }
50
51 /// Called when connection is established (TCP only)
52 fn on_connect(&self, ctx: &ServerContext, conn_id: ConnectionId) -> Result<()> {
53 let _ = (ctx, conn_id);
54 Ok(())
55 }
56
57 /// Called when data is received
58 fn on_data(&self, ctx: &ServerContext, conn_id: ConnectionId, data: &[u8]) -> Result<()>;
59
60 /// Called when connection is closed (TCP only)
61 fn on_disconnect(&self, ctx: &ServerContext, conn_id: ConnectionId) -> Result<()> {
62 let _ = (ctx, conn_id);
63 Ok(())
64 }
65
66 /// Called on write readiness (for backpressure handling)
67 fn on_writable(&self, ctx: &ServerContext, conn_id: ConnectionId) -> Result<()> {
68 let _ = (ctx, conn_id);
69 Ok(())
70 }
71
72 /// Called on errors
73 fn on_error(&self, ctx: &ServerContext, conn_id: Option<ConnectionId>, error: NetworkError) {
74 let _ = (ctx, conn_id, error);
75 }
76}