use std::fmt;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::{Validate, ValidationError, check_known};
pub mod client;
pub mod events;
pub mod server;
pub use client::ClientOp;
pub use events::{Event, EventName};
pub use server::ServerOp;
pub const GATEWAY_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Frame {
pub op: u8,
#[serde(default)]
pub d: Value,
#[serde(default)]
pub s: Option<u64>,
#[serde(default)]
pub t: Option<String>,
}
impl Frame {
pub fn new(op: Opcode, d: Value) -> Self {
Frame {
op: op.as_u8(),
d,
s: None,
t: None,
}
}
}
pub(crate) fn to_value_or_panic<T: Serialize>(what: &str, v: &T) -> Value {
match serde_json::to_value(v) {
Ok(v) => v,
Err(e) => panic!("sew-proto: serializing {what} failed: {e}"),
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum Encoding {
Json = "json",
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum Compression {
ZstdStream = "zstd-stream",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GatewayQuery {
pub v: u32,
pub encoding: Encoding,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compress: Option<Compression>,
}
impl Validate for GatewayQuery {
fn validate(&self) -> Result<(), ValidationError> {
if self.v != GATEWAY_VERSION {
return Err(ValidationError::invalid(
"v",
format!(
"gateway version {} is not supported; use {GATEWAY_VERSION}",
self.v
),
));
}
check_known("encoding", self.encoding)?;
if let Some(c) = self.compress {
check_known("compress", c)?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
ServerToClient,
ClientToServer,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Opcode {
Dispatch,
Heartbeat,
Identify,
PresenceSet,
Resume,
Subscribe,
Reconnect,
InvalidSession,
Hello,
HeartbeatAck,
Typing,
Reauth,
Activity,
}
impl Opcode {
pub const ALL: &'static [Opcode] = &[
Opcode::Dispatch,
Opcode::Heartbeat,
Opcode::Identify,
Opcode::PresenceSet,
Opcode::Resume,
Opcode::Subscribe,
Opcode::Reconnect,
Opcode::InvalidSession,
Opcode::Hello,
Opcode::HeartbeatAck,
Opcode::Typing,
Opcode::Reauth,
Opcode::Activity,
];
pub const fn as_u8(self) -> u8 {
match self {
Opcode::Dispatch => 0,
Opcode::Heartbeat => 1,
Opcode::Identify => 2,
Opcode::PresenceSet => 3,
Opcode::Resume => 4,
Opcode::Subscribe => 5,
Opcode::Reconnect => 6,
Opcode::InvalidSession => 7,
Opcode::Hello => 8,
Opcode::HeartbeatAck => 9,
Opcode::Typing => 10,
Opcode::Reauth => 11,
Opcode::Activity => 12,
}
}
pub const fn from_u8(n: u8) -> Option<Opcode> {
Some(match n {
0 => Opcode::Dispatch,
1 => Opcode::Heartbeat,
2 => Opcode::Identify,
3 => Opcode::PresenceSet,
4 => Opcode::Resume,
5 => Opcode::Subscribe,
6 => Opcode::Reconnect,
7 => Opcode::InvalidSession,
8 => Opcode::Hello,
9 => Opcode::HeartbeatAck,
10 => Opcode::Typing,
11 => Opcode::Reauth,
12 => Opcode::Activity,
_ => return None,
})
}
pub const fn name(self) -> &'static str {
match self {
Opcode::Dispatch => "DISPATCH",
Opcode::Heartbeat => "HEARTBEAT",
Opcode::Identify => "IDENTIFY",
Opcode::PresenceSet => "PRESENCE_SET",
Opcode::Resume => "RESUME",
Opcode::Subscribe => "SUBSCRIBE",
Opcode::Reconnect => "RECONNECT",
Opcode::InvalidSession => "INVALID_SESSION",
Opcode::Hello => "HELLO",
Opcode::HeartbeatAck => "HEARTBEAT_ACK",
Opcode::Typing => "TYPING",
Opcode::Reauth => "REAUTH",
Opcode::Activity => "ACTIVITY",
}
}
pub const fn direction(self) -> Direction {
match self {
Opcode::Dispatch
| Opcode::Reconnect
| Opcode::InvalidSession
| Opcode::Hello
| Opcode::HeartbeatAck => Direction::ServerToClient,
Opcode::Heartbeat
| Opcode::Identify
| Opcode::PresenceSet
| Opcode::Resume
| Opcode::Subscribe
| Opcode::Typing
| Opcode::Reauth
| Opcode::Activity => Direction::ClientToServer,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClientAction {
Resume,
Reidentify,
Identify,
NewSessionNoRetry,
FixClient,
WaitRetryAfter,
StopDropLocalData,
Stop,
ResumeAfterDelay,
FixAndResend,
RefreshAndResume,
}
pub const CLOSE_REASON_SESSION_EXPIRED: &str = "session_expired";
pub const CLOSE_REASON_RESUMED_ELSEWHERE: &str = "resumed_elsewhere";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CloseCode {
UnknownError,
UnknownOpcode,
DecodeError,
NotAuthenticated,
AuthenticationFailed,
AlreadyAuthenticated,
InvalidSeq,
RateLimited,
SessionTimedOut,
SlowConsumer,
SessionRevoked,
InvalidApiVersion,
ServerRestarting,
InvalidSubscription,
}
impl CloseCode {
pub const ALL: &'static [CloseCode] = &[
CloseCode::UnknownError,
CloseCode::UnknownOpcode,
CloseCode::DecodeError,
CloseCode::NotAuthenticated,
CloseCode::AuthenticationFailed,
CloseCode::AlreadyAuthenticated,
CloseCode::InvalidSeq,
CloseCode::RateLimited,
CloseCode::SessionTimedOut,
CloseCode::SlowConsumer,
CloseCode::SessionRevoked,
CloseCode::InvalidApiVersion,
CloseCode::ServerRestarting,
CloseCode::InvalidSubscription,
];
pub const fn as_u16(self) -> u16 {
match self {
CloseCode::UnknownError => 4000,
CloseCode::UnknownOpcode => 4001,
CloseCode::DecodeError => 4002,
CloseCode::NotAuthenticated => 4003,
CloseCode::AuthenticationFailed => 4004,
CloseCode::AlreadyAuthenticated => 4005,
CloseCode::InvalidSeq => 4007,
CloseCode::RateLimited => 4008,
CloseCode::SessionTimedOut => 4009,
CloseCode::SlowConsumer => 4010,
CloseCode::SessionRevoked => 4011,
CloseCode::InvalidApiVersion => 4012,
CloseCode::ServerRestarting => 4013,
CloseCode::InvalidSubscription => 4014,
}
}
pub const fn from_u16(n: u16) -> Option<CloseCode> {
Some(match n {
4000 => CloseCode::UnknownError,
4001 => CloseCode::UnknownOpcode,
4002 => CloseCode::DecodeError,
4003 => CloseCode::NotAuthenticated,
4004 => CloseCode::AuthenticationFailed,
4005 => CloseCode::AlreadyAuthenticated,
4007 => CloseCode::InvalidSeq,
4008 => CloseCode::RateLimited,
4009 => CloseCode::SessionTimedOut,
4010 => CloseCode::SlowConsumer,
4011 => CloseCode::SessionRevoked,
4012 => CloseCode::InvalidApiVersion,
4013 => CloseCode::ServerRestarting,
4014 => CloseCode::InvalidSubscription,
_ => return None,
})
}
pub const fn client_action(self) -> ClientAction {
match self {
CloseCode::UnknownError => ClientAction::Resume,
CloseCode::UnknownOpcode => ClientAction::Reidentify,
CloseCode::DecodeError => ClientAction::Reidentify,
CloseCode::NotAuthenticated => ClientAction::Identify,
CloseCode::AuthenticationFailed => ClientAction::NewSessionNoRetry,
CloseCode::AlreadyAuthenticated => ClientAction::FixClient,
CloseCode::InvalidSeq => ClientAction::Reidentify,
CloseCode::RateLimited => ClientAction::WaitRetryAfter,
CloseCode::SessionTimedOut => ClientAction::Resume,
CloseCode::SlowConsumer => ClientAction::Reidentify,
CloseCode::SessionRevoked => ClientAction::StopDropLocalData,
CloseCode::InvalidApiVersion => ClientAction::Stop,
CloseCode::ServerRestarting => ClientAction::ResumeAfterDelay,
CloseCode::InvalidSubscription => ClientAction::FixAndResend,
}
}
pub fn client_action_for(self, reason: &str) -> ClientAction {
match (self, reason) {
(CloseCode::AuthenticationFailed, CLOSE_REASON_SESSION_EXPIRED) => {
ClientAction::RefreshAndResume
}
_ => self.client_action(),
}
}
}
impl fmt::Display for CloseCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({self:?})", self.as_u16())
}
}