use thiserror::Error;
pub type CortexResult<T> = std::result::Result<T, CortexError>;
#[derive(Error)]
pub enum CortexError {
#[error("Failed to connect to Cortex at {url}: {reason}. Is the EMOTIV Launcher running?")]
ConnectionFailed { url: String, reason: String },
#[error("Connection to Cortex lost: {reason}")]
ConnectionLost { reason: String },
#[error("Not connected to Cortex")]
NotConnected,
#[error(
"Authentication failed: {reason}. Check your client_id and client_secret from the Emotiv Developer Portal."
)]
AuthenticationFailed { reason: String },
#[error("Cortex token expired — re-authentication required")]
TokenExpired,
#[error("Access denied: {reason}. Approve the application in the EMOTIV Launcher.")]
AccessDenied { reason: String },
#[error("User not logged in to EmotivID. Open the EMOTIV Launcher and sign in.")]
UserNotLoggedIn,
#[error("Application not approved. Open the EMOTIV Launcher and approve access for your app.")]
NotApproved,
#[error("Emotiv license error: {reason}")]
LicenseError { reason: String },
#[error("No headset found. Ensure the headset is powered on and within range.")]
NoHeadsetFound,
#[error("Headset is in use by another session")]
HeadsetInUse,
#[error("Headset connection error: {reason}")]
HeadsetError { reason: String },
#[error("Session error: {reason}")]
SessionError { reason: String },
#[error("Stream error: {reason}")]
StreamError { reason: String },
#[error("Cortex API error {code}: {message}")]
ApiError { code: i32, message: String },
#[error("Cortex service is starting up — retry in a few seconds")]
CortexStarting,
#[error("API method not found: {method}")]
MethodNotFound { method: String },
#[error("Operation timed out after {seconds}s")]
Timeout { seconds: u64 },
#[error("Operation failed after {attempts} attempts: {last_error}")]
RetriesExhausted {
attempts: u32,
last_error: Box<CortexError>,
},
#[error("Protocol error: {reason}")]
ProtocolError { reason: String },
#[error("Configuration error: {reason}")]
ConfigError { reason: String },
#[error("WebSocket error: {0}")]
WebSocket(String),
#[error("TLS error: {0}")]
Tls(String),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
}
impl std::fmt::Debug for CortexError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CortexError")
.field("category", &self.category())
.field("api_code", &self.api_code())
.finish()
}
}
impl CortexError {
#[must_use]
pub fn category(&self) -> &'static str {
match self {
CortexError::ConnectionFailed { .. } => "connection_failed",
CortexError::ConnectionLost { .. } => "connection_lost",
CortexError::NotConnected => "not_connected",
CortexError::AuthenticationFailed { .. } => "authentication_failed",
CortexError::TokenExpired => "token_expired",
CortexError::AccessDenied { .. } => "access_denied",
CortexError::UserNotLoggedIn => "user_not_logged_in",
CortexError::NotApproved => "not_approved",
CortexError::LicenseError { .. } => "license_error",
CortexError::NoHeadsetFound => "no_headset_found",
CortexError::HeadsetInUse => "headset_in_use",
CortexError::HeadsetError { .. } => "headset_error",
CortexError::SessionError { .. } => "session_error",
CortexError::StreamError { .. } => "stream_error",
CortexError::ApiError { .. } => "api_error",
CortexError::CortexStarting => "cortex_starting",
CortexError::MethodNotFound { .. } => "method_not_found",
CortexError::Timeout { .. } => "timeout",
CortexError::RetriesExhausted { .. } => "retries_exhausted",
CortexError::ProtocolError { .. } => "protocol_error",
CortexError::ConfigError { .. } => "config_error",
CortexError::WebSocket(_) => "websocket_error",
CortexError::Tls(_) => "tls_error",
CortexError::Io(_) => "io_error",
CortexError::Json(_) => "json_error",
}
}
#[must_use]
pub fn api_code(&self) -> Option<i32> {
match self {
CortexError::ApiError { code, .. } => Some(*code),
CortexError::RetriesExhausted { last_error, .. } => last_error.api_code(),
_ => None,
}
}
pub fn from_api_error(code: i32, message: impl Into<String>) -> Self {
let message = message.into();
match code {
-32601 => CortexError::MethodNotFound {
method: message.clone(),
},
-32001 | -32004 => CortexError::NoHeadsetFound,
-32002 | -32024 => CortexError::LicenseError { reason: message },
-32005 | -32012 => CortexError::SessionError { reason: message },
-32014 | -32021 => CortexError::AuthenticationFailed { reason: message },
-32015 => CortexError::TokenExpired,
-32016 => CortexError::StreamError { reason: message },
-32033 => CortexError::UserNotLoggedIn,
-32142 => CortexError::NotApproved,
-32152 => CortexError::HeadsetError { reason: message },
-32102 => CortexError::NotApproved,
-32122 => CortexError::CortexStarting,
_ => CortexError::ApiError { code, message },
}
}
#[must_use]
pub fn is_retryable(&self) -> bool {
matches!(
self,
CortexError::ConnectionLost { .. }
| CortexError::Timeout { .. }
| CortexError::CortexStarting
| CortexError::WebSocket(_)
)
}
#[must_use]
pub fn is_connection_error(&self) -> bool {
matches!(
self,
CortexError::ConnectionFailed { .. }
| CortexError::ConnectionLost { .. }
| CortexError::NotConnected
| CortexError::WebSocket(_)
)
}
}
impl From<tokio_tungstenite::tungstenite::Error> for CortexError {
fn from(err: tokio_tungstenite::tungstenite::Error) -> Self {
CortexError::WebSocket(err.to_string())
}
}
#[cfg(feature = "native-tls")]
impl From<native_tls::Error> for CortexError {
fn from(err: native_tls::Error) -> Self {
CortexError::Tls(err.to_string())
}
}
#[cfg(feature = "config-toml")]
impl From<toml::de::Error> for CortexError {
fn from(err: toml::de::Error) -> Self {
CortexError::ConfigError {
reason: err.to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_redacts_error_details() {
let err = CortexError::ApiError {
code: -32_999,
message: "SENTINEL-SERVER-ERROR".into(),
};
let debug = format!("{err:?}");
assert!(!debug.contains("SENTINEL-SERVER-ERROR"));
assert!(debug.contains("api_error"));
assert!(debug.contains("-32999"));
assert!(err.to_string().contains("SENTINEL-SERVER-ERROR"));
}
#[test]
fn test_from_api_error_known_codes() {
assert!(matches!(
CortexError::from_api_error(-32001, "no headset"),
CortexError::NoHeadsetFound
));
assert!(matches!(
CortexError::from_api_error(-32002, "invalid license"),
CortexError::LicenseError { .. }
));
assert!(matches!(
CortexError::from_api_error(-32004, "headset unavailable"),
CortexError::NoHeadsetFound
));
assert!(matches!(
CortexError::from_api_error(-32005, "session already exists"),
CortexError::SessionError { .. }
));
assert!(matches!(
CortexError::from_api_error(-32012, "session must be activated"),
CortexError::SessionError { .. }
));
assert!(matches!(
CortexError::from_api_error(-32014, "invalid token"),
CortexError::AuthenticationFailed { .. }
));
assert!(matches!(
CortexError::from_api_error(-32015, "expired token"),
CortexError::TokenExpired
));
assert!(matches!(
CortexError::from_api_error(-32016, "invalid stream"),
CortexError::StreamError { .. }
));
assert!(matches!(
CortexError::from_api_error(-32021, "invalid credentials"),
CortexError::AuthenticationFailed { .. }
));
assert!(matches!(
CortexError::from_api_error(-32024, "license expired"),
CortexError::LicenseError { .. }
));
assert!(matches!(
CortexError::from_api_error(-32033, "not logged in"),
CortexError::UserNotLoggedIn
));
assert!(matches!(
CortexError::from_api_error(-32142, "not approved"),
CortexError::NotApproved
));
assert!(matches!(
CortexError::from_api_error(-32152, "headset not ready"),
CortexError::HeadsetError { .. }
));
assert!(matches!(
CortexError::from_api_error(-32601, "unknown"),
CortexError::MethodNotFound { .. }
));
}
#[test]
fn test_from_api_error_legacy_codes() {
assert!(matches!(
CortexError::from_api_error(-32102, "legacy not approved"),
CortexError::NotApproved
));
assert!(matches!(
CortexError::from_api_error(-32122, "legacy starting"),
CortexError::CortexStarting
));
}
#[test]
fn test_from_api_error_unknown_code() {
let err = CortexError::from_api_error(-99999, "something weird");
assert!(matches!(err, CortexError::ApiError { code: -99999, .. }));
assert_eq!(err.to_string(), "Cortex API error -99999: something weird");
}
#[test]
fn test_from_api_error_unknown_code_preserves_message() {
let err = CortexError::from_api_error(12345, "custom server message");
match &err {
CortexError::ApiError { code, message } => {
assert_eq!(*code, 12345);
assert_eq!(message.as_str(), "custom server message");
}
_ => panic!("expected ApiError, got {err:?}"),
}
}
#[test]
fn test_from_api_error_method_not_found_preserves_method() {
let err = CortexError::from_api_error(-32601, "authorize");
match &err {
CortexError::MethodNotFound { method } => assert_eq!(method, "authorize"),
_ => panic!("expected MethodNotFound, got {err:?}"),
}
}
#[test]
fn test_is_retryable() {
assert!(CortexError::CortexStarting.is_retryable());
assert!(CortexError::Timeout { seconds: 10 }.is_retryable());
assert!(CortexError::ConnectionLost { reason: "x".into() }.is_retryable());
assert!(!CortexError::NoHeadsetFound.is_retryable());
assert!(!CortexError::SessionError { reason: "x".into() }.is_retryable());
}
#[test]
fn test_is_connection_error() {
assert!(CortexError::NotConnected.is_connection_error());
assert!(CortexError::ConnectionLost { reason: "x".into() }.is_connection_error());
assert!(!CortexError::TokenExpired.is_connection_error());
}
#[test]
fn test_from_tungstenite_error() {
let ws_error = tokio_tungstenite::tungstenite::Error::Io(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"broken pipe",
));
let err: CortexError = ws_error.into();
assert!(matches!(err, CortexError::WebSocket(_)));
assert!(err.to_string().contains("WebSocket error"));
}
#[cfg(feature = "config-toml")]
#[test]
fn test_from_toml_error_conversion() {
#[derive(Debug, serde::Deserialize)]
struct DummyConfig {
_value: String,
}
let toml_err = toml::from_str::<DummyConfig>("value = [").unwrap_err();
let err: CortexError = toml_err.into();
assert!(matches!(err, CortexError::ConfigError { .. }));
assert!(err.to_string().contains("Configuration error"));
}
#[test]
fn test_is_retryable_additional_variants() {
assert!(CortexError::WebSocket("transport reset".into()).is_retryable());
assert!(
!CortexError::ConnectionFailed {
url: "wss://localhost:6868".into(),
reason: "refused".into(),
}
.is_retryable()
);
assert!(
!CortexError::ProtocolError {
reason: "bad frame".into()
}
.is_retryable()
);
}
#[test]
fn test_is_connection_error_additional_variants() {
assert!(
CortexError::ConnectionFailed {
url: "wss://localhost:6868".into(),
reason: "dial failed".into(),
}
.is_connection_error()
);
assert!(CortexError::WebSocket("closed".into()).is_connection_error());
assert!(!CortexError::Timeout { seconds: 1 }.is_connection_error());
assert!(
!CortexError::AuthenticationFailed {
reason: "bad auth".into()
}
.is_connection_error()
);
}
}