quoter/src/main.rs

136 lines
4.9 KiB
Rust
Raw Normal View History

2023-10-02 15:36:02 +00:00
use actix_web::{web, App, HttpResponse, HttpServer, Responder, web::Bytes};
2023-10-02 09:22:04 +00:00
use redis::{Client, AsyncCommands};
2023-09-27 23:08:48 +00:00
use std::collections::HashMap;
use std::env;
2023-10-02 12:37:56 +00:00
use futures::StreamExt;
2023-10-02 09:22:04 +00:00
use tokio::sync::broadcast::{self, Receiver};
2023-10-02 20:35:49 +00:00
2023-10-03 08:30:59 +00:00
pub mod data;
2023-10-02 13:47:22 +00:00
2023-09-28 10:12:07 +00:00
async fn sse_handler(
token: web::Path<String>,
2023-10-02 20:34:30 +00:00
rx: web::Data<Receiver<String>>,
2023-10-02 09:22:04 +00:00
redis: web::Data<Client>,
2023-09-28 10:12:07 +00:00
) -> impl Responder {
2023-10-03 08:30:59 +00:00
let author_id = match data::get_auth_id(&token).await {
2023-09-27 23:08:48 +00:00
Ok(id) => id,
Err(e) => {
2023-10-02 13:55:31 +00:00
eprintln!("TOKEN check failed: {}", e);
2023-10-02 09:22:04 +00:00
return HttpResponse::Unauthorized().finish();
2023-09-27 23:08:48 +00:00
}
};
2023-10-02 18:55:10 +00:00
let mut con = match redis.get_async_connection().await {
Ok(con) => con,
Err(e) => {
eprintln!("Failed to get async connection: {}", e);
return HttpResponse::InternalServerError().finish();
}
};
2023-10-02 20:28:36 +00:00
let _ = match con.sadd::<&str, &i32, usize>("authors-online", &author_id).await {
2023-10-02 18:55:10 +00:00
Ok(_) => (),
Err(e) => {
eprintln!("Failed to add author to online list: {}", e);
return HttpResponse::InternalServerError().finish();
}
};
2023-10-02 09:22:04 +00:00
2023-10-02 20:12:33 +00:00
let chats: Vec<String> = match con.smembers::<String, Vec<String>>(format!("chats_by_author/{}", author_id)).await {
2023-10-02 13:47:22 +00:00
Ok(chats) => {
if chats.is_empty() {
2023-10-03 08:30:59 +00:00
match data::create_first_chat(author_id, &mut con).await {
2023-10-02 18:55:10 +00:00
Ok(chat) => chat,
Err(e) => {
eprintln!("Failed to create first chat: {}", e);
return HttpResponse::InternalServerError().finish();
}
}
2023-10-02 13:47:22 +00:00
} else {
chats
}
},
2023-10-02 18:55:10 +00:00
Err(e) => {
eprintln!("Failed to get chats by author: {}", e);
2023-10-03 08:30:59 +00:00
match data::create_first_chat(author_id, &mut con).await {
2023-10-02 20:22:05 +00:00
Ok(chat) => chat,
Err(e) => {
eprintln!("Failed to create first chat: {}", e);
return HttpResponse::InternalServerError().finish();
2023-10-02 18:55:10 +00:00
}
2023-10-02 20:22:05 +00:00
}
2023-10-02 18:55:10 +00:00
}
2023-10-02 13:47:22 +00:00
};
2023-09-28 10:12:07 +00:00
2023-10-02 09:22:04 +00:00
let mut pubsub = con.into_pubsub();
2023-10-03 04:41:17 +00:00
for chat_id in &chats {
if let Err(e) = pubsub.subscribe(format!("chat:{}", chat_id)).await {
eprintln!("Failed to subscribe to chat: {}", e);
2023-10-02 18:55:10 +00:00
return HttpResponse::InternalServerError().finish();
}
2023-10-03 04:41:17 +00:00
}
2023-09-28 10:12:07 +00:00
2023-10-03 05:02:11 +00:00
let mut con = match redis.get_async_connection().await {
Ok(con) => con,
Err(e) => {
eprintln!("Failed to get async connection: {}", e);
return HttpResponse::InternalServerError().finish();
}
};
2023-10-03 04:52:48 +00:00
let _ = match con.srem::<&str, &i32, usize>("authors-online", &author_id).await {
Ok(_) => (),
Err(e) => {
eprintln!("Failed to remove author from online list: {}", e);
return HttpResponse::InternalServerError().finish();
}
};
2023-10-03 08:30:59 +00:00
// FIXME: cannot borrow data in an `Arc` as mutable
// trait `DerefMut` is required to modify through a dereference,
// but it is not implemented for `Arc<tokio::sync::broadcast::Receiver<std::string::String>>`
let server_event = match rx.recv().await {
2023-10-02 18:55:10 +00:00
Ok(event) => event,
Err(e) => {
eprintln!("Failed to receive server event: {}", e);
return HttpResponse::InternalServerError().finish();
}
};
2023-10-02 15:27:55 +00:00
let server_event_stream = futures::stream::once(async move { Ok::<_, actix_web::Error>(Bytes::from(server_event)) });
2023-10-02 09:22:04 +00:00
HttpResponse::Ok()
2023-10-02 11:24:45 +00:00
.append_header(("content-type", "text/event-stream"))
2023-10-02 15:27:55 +00:00
.streaming(server_event_stream)
2023-09-27 23:08:48 +00:00
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
2023-10-02 12:37:56 +00:00
let (tx, _rx) = broadcast::channel(100);
2023-10-02 18:55:10 +00:00
let redis_url = env::var("REDIS_URL").expect("REDIS_URL must be set");
let client = redis::Client::open(redis_url).expect("Failed to open Redis client");
2023-09-28 10:12:07 +00:00
let _handle = tokio::spawn(async move {
2023-10-02 18:55:10 +00:00
let mut conn = client.get_async_connection().await.expect("Failed to get async connection");
2023-09-28 10:12:07 +00:00
let mut pubsub = conn.into_pubsub();
2023-10-02 18:55:10 +00:00
pubsub.subscribe("new_follower").await.expect("Failed to subscribe to new_follower");
pubsub.subscribe("new_shout").await.expect("Failed to subscribe to new_shout");
pubsub.subscribe("new_reaction").await.expect("Failed to subscribe to new_reaction");
2023-09-28 10:12:07 +00:00
2023-10-02 12:30:53 +00:00
while let Some(msg) = pubsub.on_message().next().await {
2023-10-02 18:55:10 +00:00
let payload: HashMap<String, String> = msg.get_payload().expect("Failed to get payload");
tx.send(serde_json::to_string(&payload).expect("Failed to serialize payload")).expect("Failed to send payload");
2023-09-28 10:12:07 +00:00
}
});
2023-09-27 23:08:48 +00:00
HttpServer::new(move || {
2023-10-02 12:35:16 +00:00
let rx = tx.subscribe();
2023-09-27 23:08:48 +00:00
App::new()
2023-10-02 12:35:16 +00:00
.app_data(web::Data::new(rx))
2023-10-02 11:48:27 +00:00
.app_data(web::Data::new(client.clone()))
2023-10-02 18:55:10 +00:00
.route("/presence/{token}", web::get().to(sse_handler))
2023-09-27 23:08:48 +00:00
})
.bind("127.0.0.1:8080")?
.run()
.await
}