use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use chrono::{DateTime, Utc};
use futures_util::stream::SplitStream;
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::net::TcpStream;
use tokio::sync::{mpsc, oneshot, watch};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
use crate::authentification::{CredentialsOrApiKey, Profile};
use crate::billing::PageQuery;
use crate::error::{Error, Result};
use crate::http::{client, encode, ok, websocket};
#[derive(Debug, Clone)]
pub enum Authorization {
Server {
authorization: CredentialsOrApiKey,
server: String,
group: Option<String>,
},
AccessCode {
authorization: CredentialsOrApiKey,
access_code: String,
},
}
pub trait Hooks: Send + Sync {
fn create_room(&self, _room: &Room, _state: &Value) {}
fn create_presence(&self, _room: &Room, _presence: &Presence) {}
fn remove_presence(&self, _room: &Room, _presence: &Presence) {}
fn on_connection(&self, _room: &Room, _state: &Value) {}
fn on_event(&self, _room: &Room, _packet: &Value) -> bool {
false
}
fn on_binary(&self, _room: &Room, _data: &[u8]) {}
fn on_presence(&self, _room: &Room) {}
fn on_closed(&self, _room: &Room, _reason: Option<&str>) {}
}
impl Hooks for () {}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct PresencePatch {
#[serde(default)]
pub position: Option<[f64; 3]>,
#[serde(default)]
pub status: Option<String>,
}
#[derive(Default)]
struct PresenceState {
position: [f64; 3],
status: Option<String>,
}
struct PresenceInner {
room: Room,
id: String,
profile: Profile,
state: Mutex<PresenceState>,
}
#[derive(Clone)]
pub struct Presence(Arc<PresenceInner>);
impl Presence {
fn new(room: &Room, id: String, profile: Profile) -> Self {
Presence(Arc::new(PresenceInner {
room: room.clone(),
id,
profile,
state: Mutex::new(PresenceState::default()),
}))
}
fn state(&self) -> MutexGuard<'_, PresenceState> {
self.0.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn room(&self) -> &Room {
&self.0.room
}
pub fn id(&self) -> &str {
&self.0.id
}
pub fn profile(&self) -> &Profile {
&self.0.profile
}
pub fn position(&self) -> [f64; 3] {
self.state().position
}
pub fn status(&self) -> String {
self.state().status.clone().unwrap_or_default()
}
pub fn r#move(&self, position: [f64; 3]) {
self.state().position = position;
self.room().post(&json!({
"event": "update-client",
"client": self.to_json(),
}));
}
pub fn set_status(&self, status: &str) {
self.state().status = Some(status.to_string());
self.room().post(&json!({
"event": "update-client",
"client": self.to_json(),
}));
}
pub fn update(&self, patch: &PresencePatch) {
let mut state = self.state();
if let Some(position) = patch.position {
state.position = position;
}
if let Some(status) = &patch.status {
state.status = Some(status.clone());
}
}
pub fn to_json(&self) -> Value {
let (position, status) = {
let state = self.state();
(state.position, state.status.clone().unwrap_or_default())
};
json!({
"id": self.id(),
"profile": self.profile(),
"position": position,
"status": status,
})
}
}
struct RoomInner {
endpoint: String,
ws: mpsc::UnboundedSender<Message>,
authorization: Authorization,
id: String,
presences: Mutex<Vec<Presence>>,
closed: watch::Sender<bool>,
}
#[derive(Clone)]
pub struct Room(Arc<RoomInner>);
#[derive(Clone)]
pub struct RoomSocket {
outbox: mpsc::UnboundedSender<Message>,
closed: watch::Receiver<bool>,
}
impl RoomSocket {
pub fn is_open(&self) -> bool {
!*self.closed.borrow() && !self.outbox.is_closed()
}
}
impl Room {
pub(crate) fn new(
endpoint: String,
ws: mpsc::UnboundedSender<Message>,
authorization: Authorization,
id: String,
) -> Self {
Room(Arc::new(RoomInner {
endpoint,
ws,
authorization,
id,
presences: Mutex::new(Vec::new()),
closed: watch::channel(false).0,
}))
}
fn presences(&self) -> MutexGuard<'_, Vec<Presence>> {
self.0
.presences
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
pub fn endpoint(&self) -> &str {
&self.0.endpoint
}
pub fn ws(&self) -> RoomSocket {
RoomSocket {
outbox: self.0.ws.clone(),
closed: self.0.closed.subscribe(),
}
}
pub fn authorization(&self) -> &Authorization {
&self.0.authorization
}
pub fn id(&self) -> &str {
&self.0.id
}
pub fn get_presences(&self) -> Vec<Presence> {
self.presences().clone()
}
pub(crate) fn clear_presences(&self) {
self.presences().clear();
}
pub(crate) fn socket_closed(&self) -> watch::Receiver<bool> {
self.0.closed.subscribe()
}
pub fn get_authorization(&self) -> &CredentialsOrApiKey {
match &self.0.authorization {
Authorization::Server { authorization, .. } => authorization,
Authorization::AccessCode { authorization, .. } => authorization,
}
}
pub fn post(&self, packet: &Value) {
let _ = self.0.ws.send(Message::text(packet.to_string()));
}
pub fn disconnect(&self) {
self.presences().clear();
let _ = self.0.ws.send(Message::Close(None));
}
pub async fn generate_access_code(&self) -> Result<String> {
let endpoint = self.endpoint().strip_suffix('/').unwrap_or(self.endpoint());
let request = client().post(format!("{endpoint}/access-code")).header(
"Authorization",
match self.get_authorization() {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
let request = match self.authorization() {
Authorization::Server { server, group, .. } => {
let request = request.header("Server", server);
match group {
Some(group) => request.header("Group", group),
None => request,
}
}
Authorization::AccessCode { .. } => request,
};
let response = request.send().await?;
Ok(ok(response).await?.text().await?)
}
}
type Reader = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
pub async fn connect(
authorization: Authorization,
endpoint: &str,
hooks: Arc<dyn Hooks>,
) -> Result<Presence> {
let mut params = Map::new();
let header = match &authorization {
Authorization::Server { authorization, .. }
| Authorization::AccessCode { authorization, .. } => match authorization {
CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
};
params.insert("Authorization".to_string(), Value::String(header));
match &authorization {
Authorization::Server { server, group, .. } => {
params.insert("Server".to_string(), Value::String(server.clone()));
if let Some(group) = group {
params.insert("Group".to_string(), Value::String(group.clone()));
}
}
Authorization::AccessCode { access_code, .. } => {
params.insert("AccessCode".to_string(), Value::String(access_code.clone()));
}
}
let auth_param = crate::http::encode(&Value::Object(params).to_string());
let ws_url = websocket(endpoint);
let ws_url = ws_url.strip_suffix('/').unwrap_or(&ws_url).to_string();
let timer = Duration::from_secs(15);
let connected = tokio::time::timeout(
timer,
tokio_tungstenite::connect_async(format!("{ws_url}?authorization={auth_param}")),
)
.await;
let stream = match connected {
Ok(Ok((stream, _))) => stream,
Ok(Err(_)) => {
return Err(Error::Message(format!(
"WebSocket connection failed ({ws_url})"
)));
}
Err(_) => {
return Err(Error::Message(format!(
"Timed out waiting for the room ({ws_url})."
)));
}
};
let (mut write, read) = stream.split();
let (ws, mut outbox) = mpsc::unbounded_channel::<Message>();
tokio::spawn(async move {
while let Some(message) = outbox.recv().await {
let closing = matches!(message, Message::Close(_));
if write.send(message).await.is_err() || closing {
break;
}
}
let _ = write.close().await;
});
let (ready, settled) = oneshot::channel();
tokio::spawn(listen(
read,
ws.clone(),
authorization,
endpoint.to_string(),
ws_url.clone(),
hooks,
ready,
));
match tokio::time::timeout(timer, settled).await {
Ok(Ok(result)) => result,
Ok(Err(_)) => Err(Error::Message(format!(
"WebSocket closed before the room connected ({ws_url})"
))),
Err(_) => {
let _ = ws.send(Message::Close(None));
Err(Error::Message(format!(
"Timed out waiting for the room ({ws_url})."
)))
}
}
}
fn fail(
ready: &mut Option<oneshot::Sender<Result<Presence>>>,
ws: &mpsc::UnboundedSender<Message>,
message: String,
) {
if let Some(ready) = ready.take() {
let _ = ws.send(Message::Close(None));
let _ = ready.send(Err(Error::Message(message)));
}
}
fn text(value: &Value) -> String {
match value {
Value::String(value) => value.clone(),
Value::Null => String::new(),
value => value.to_string(),
}
}
fn profile(client: &Value) -> Profile {
serde_json::from_value(client["profile"].clone()).unwrap_or_default()
}
fn patch(client: &Value) -> PresencePatch {
serde_json::from_value(client.clone()).unwrap_or_default()
}
async fn listen(
mut read: Reader,
ws: mpsc::UnboundedSender<Message>,
authorization: Authorization,
endpoint: String,
ws_url: String,
hooks: Arc<dyn Hooks>,
ready: oneshot::Sender<Result<Presence>>,
) {
let mut ready = Some(ready);
let mut room: Option<Room> = None;
let mut self_id: Option<String> = None;
while let Some(message) = read.next().await {
let raw = match message {
Ok(Message::Text(text)) => text.to_string(),
Ok(Message::Binary(bytes)) => {
if let Some(room) = &room {
hooks.on_binary(room, &bytes);
}
continue;
}
Ok(Message::Close(_)) => break,
Ok(_) => continue,
Err(_) => {
fail(
&mut ready,
&ws,
format!("WebSocket connection failed ({ws_url})"),
);
break;
}
};
let Ok(json) = serde_json::from_str::<Value>(&raw) else {
fail(&mut ready, &ws, "Room connection failed".to_string());
continue;
};
if json["event"] == "error" {
let message = json["message"]
.as_str()
.filter(|message| !message.is_empty());
fail(
&mut ready,
&ws,
message.unwrap_or("Room connection failed").to_string(),
);
continue;
}
match json["event"].as_str().unwrap_or_default() {
"connection" => {
let client = &json["data"]["client"];
let client_id = text(&client["id"]);
if client_id.is_empty() {
fail(&mut ready, &ws, "Room connection missing self.".to_string());
continue;
}
self_id = Some(client_id.clone());
let id = text(&json["data"]["server"]["id"]);
let state = json["data"]["state"].clone();
let joined = Room::new(endpoint.clone(), ws.clone(), authorization.clone(), id);
hooks.create_room(&joined, &state);
let me = Presence::new(&joined, client_id.clone(), profile(client));
hooks.create_presence(&joined, &me);
me.update(&patch(client));
for presence in json["data"]["clients"].as_array().into_iter().flatten() {
if text(&presence["id"]) == client_id {
continue;
}
let other = Presence::new(&joined, text(&presence["id"]), profile(presence));
hooks.create_presence(&joined, &other);
other.update(&patch(presence));
joined.presences().push(other);
}
hooks.on_connection(&joined, &state);
room = Some(joined);
if let Some(ready) = ready.take() {
let _ = ready.send(Ok(me));
}
}
"add-client" => {
let Some(room) = &room else {
fail(&mut ready, &ws, "Room not found".to_string());
continue;
};
let client = &json["data"]["client"];
if Some(text(&client["id"])) == self_id {
continue;
}
let presence = Presence::new(room, text(&client["id"]), profile(client));
hooks.create_presence(room, &presence);
presence.update(&patch(client));
room.presences().push(presence);
hooks.on_presence(room);
}
"update-client" => {
let Some(room) = &room else {
fail(&mut ready, &ws, "Room not found".to_string());
continue;
};
let client = &json["data"]["client"];
let id = text(&client["id"]);
if Some(id.clone()) == self_id {
continue;
}
let presence = room
.presences()
.iter()
.find(|presence| presence.id() == id)
.cloned();
let Some(presence) = presence else {
fail(&mut ready, &ws, "Presence not found".to_string());
continue;
};
presence.update(&patch(client));
hooks.on_presence(room);
}
"remove-client" => {
let Some(room) = &room else {
fail(&mut ready, &ws, "Room not found".to_string());
continue;
};
let id = text(&json["data"]["client"]["id"]);
let presence = room
.presences()
.iter()
.find(|presence| presence.id() == id)
.cloned();
if let Some(presence) = &presence {
hooks.remove_presence(room, presence);
room.presences().retain(|other| other.id() != id);
}
hooks.on_presence(room);
}
"server-closed" => {
let Some(room) = &room else {
fail(&mut ready, &ws, "Room closed before connect".to_string());
continue;
};
let reason = json["data"]["reason"].as_str();
room.presences().clear();
hooks.on_closed(room, reason);
let _ = ws.send(Message::Close(None));
}
_ => {
if let Some(room) = &room {
hooks.on_event(room, &json);
}
}
}
}
if let Some(room) = &room {
room.0.closed.send_replace(true);
}
fail(
&mut ready,
&ws,
format!("WebSocket closed before the room connected ({ws_url})"),
);
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccessCode {
pub code: String,
pub reference: String,
pub write: bool,
pub expires: DateTime<Utc>,
}
impl AccessCode {
pub fn from_json(json: &Value) -> AccessCode {
AccessCode {
code: json["code"].as_str().unwrap_or_default().to_string(),
reference: json["reference"].as_str().unwrap_or_default().to_string(),
write: json["write"].as_bool().unwrap_or(false),
expires: crate::tickets::parse_date(&json["expires"]).unwrap_or_default(),
}
}
}
pub async fn list_access_codes(
authorization: &CredentialsOrApiKey,
query: PageQuery,
) -> Result<Vec<AccessCode>> {
let response = client()
.get(format!(
"{}/access-codes?cursor={}&max={}",
crate::get_url(),
query.cursor,
query.max
))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.send()
.await?;
let rows: Vec<Value> = ok(response).await?.json().await?;
Ok(rows.iter().map(AccessCode::from_json).collect())
}
pub async fn revoke_access_code(authorization: &CredentialsOrApiKey, code: &str) -> Result<()> {
let response = client()
.delete(format!(
"{}/access-codes/{}",
crate::get_url(),
encode(code)
))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.send()
.await?;
ok(response).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::authentification::ApiKey;
fn joined() -> (Room, mpsc::UnboundedReceiver<Message>) {
let (ws, outbox) = mpsc::unbounded_channel();
let authorization = Authorization::Server {
authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
server: "fauna:ticket:1".to_string(),
group: None,
};
let endpoint = "http://localhost/tickets".to_string();
(
Room::new(endpoint, ws, authorization, "1".to_string()),
outbox,
)
}
#[test]
fn the_socket_is_open_until_either_side_closes_it() {
let (room, outbox) = joined();
let socket = room.ws();
assert!(socket.is_open());
drop(outbox);
assert!(!socket.is_open());
let (room, _outbox) = joined();
let socket = room.ws();
room.0.closed.send_replace(true);
assert!(!socket.is_open());
assert!(!room.ws().is_open());
}
}