reifydb_sub_server/protocols/
mod.rs

1// Copyright (c) reifydb.com 2025
2// This file is licensed under the AGPL-3.0-or-later, see license.md file
3
4pub mod convert;
5pub mod http;
6pub mod utils;
7pub mod ws;
8
9use std::fmt;
10
11pub use http::HttpHandler;
12pub use ws::WebSocketHandler;
13
14use crate::core::Connection;
15
16/// Result type for protocol operations
17pub type ProtocolResult<T> = Result<T, ProtocolError>;
18
19/// Errors that can occur during protocol handling
20#[derive(Debug)]
21pub enum ProtocolError {
22	Io(std::io::Error),
23	InvalidFrame,
24	InvalidHandshake,
25	UnsupportedProtocol,
26	ConnectionClosed,
27	BufferOverflow,
28	Custom(String),
29}
30
31impl fmt::Display for ProtocolError {
32	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33		match self {
34			Self::Io(e) => write!(f, "I/O error: {}", e),
35			Self::InvalidFrame => {
36				write!(f, "Invalid protocol frame")
37			}
38			Self::InvalidHandshake => {
39				write!(f, "Invalid protocol handshake")
40			}
41			Self::UnsupportedProtocol => {
42				write!(f, "Unsupported protocol")
43			}
44			Self::ConnectionClosed => {
45				write!(f, "Connection closed")
46			}
47			Self::BufferOverflow => write!(f, "Buffer overflow"),
48			Self::Custom(msg) => write!(f, "{}", msg),
49		}
50	}
51}
52
53impl std::error::Error for ProtocolError {}
54
55impl From<std::io::Error> for ProtocolError {
56	fn from(err: std::io::Error) -> Self {
57		Self::Io(err)
58	}
59}
60
61/// Trait for protocol handlers
62pub trait ProtocolHandler: Send + Sync {
63	/// Protocol name for identification
64	fn name(&self) -> &'static str;
65
66	/// Detect if this protocol can handle the given connection buffer
67	fn can_handle(&self, buffer: &[u8]) -> bool;
68
69	/// Handle a connection using this protocol
70	fn handle_connection(&self, conn: &mut Connection) -> ProtocolResult<()>;
71
72	/// Handle readable events for this connection
73	fn handle_read(&self, conn: &mut Connection) -> ProtocolResult<()>;
74
75	/// Handle writable events for this connection
76	fn handle_write(&self, conn: &mut Connection) -> ProtocolResult<()>;
77
78	/// Check if the connection should be closed
79	fn should_close(&self, conn: &Connection) -> bool;
80}