2 chat_server::ChatServer,
3 messages::{Connect, Disconnect, StandardMessage, WsMessage},
8 use actix_web_actors::ws;
9 use lemmy_utils::{utils::get_ip, ConnectionId, IpAddr};
10 use log::{debug, error, info};
11 use std::time::{Duration, Instant};
13 /// How often heartbeat pings are sent
14 const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
15 /// How long before lack of client response causes a timeout
16 const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
18 pub fn config(cfg: &mut web::ServiceConfig) {
19 cfg.service(web::resource("/ws").to(chat_route));
22 /// Entry point for our route
26 context: web::Data<LemmyContext>,
27 ) -> Result<HttpResponse, Error> {
30 cs_addr: context.chat_server().to_owned(),
33 ip: get_ip(&req.connection_info()),
41 cs_addr: Addr<ChatServer>,
45 /// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
46 /// otherwise we drop connection.
50 impl Actor for WsSession {
51 type Context = ws::WebsocketContext<Self>;
53 /// Method is called on actor start.
54 /// We register ws session with ChatServer
55 fn started(&mut self, ctx: &mut Self::Context) {
56 // we'll start heartbeat process on session start.
59 // register self in chat server. `AsyncContext::wait` register
60 // future within context, but context waits until this future resolves
61 // before processing any other events.
62 // across all routes within application
63 let addr = ctx.address();
67 addr: addr.recipient(),
68 ip: self.ip.to_owned(),
71 .then(|res, act, ctx| {
73 Ok(res) => act.id = res,
74 // something is wrong with chat server
82 fn stopping(&mut self, _ctx: &mut Self::Context) -> Running {
84 self.cs_addr.do_send(Disconnect {
86 ip: self.ip.to_owned(),
92 /// Handle messages from chat server, we simply send it to peer websocket
93 /// These are room messages, IE sent to others in the room
94 impl Handler<WsMessage> for WsSession {
97 fn handle(&mut self, msg: WsMessage, ctx: &mut Self::Context) {
102 /// WebSocket message handler
103 impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsSession {
104 fn handle(&mut self, result: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
105 let message = match result {
113 ws::Message::Ping(msg) => {
114 self.hb = Instant::now();
117 ws::Message::Pong(_) => {
118 self.hb = Instant::now();
120 ws::Message::Text(text) => {
121 let m = text.trim().to_owned();
122 info!("Message received: {:?} from id: {}", &m, self.id);
126 .send(StandardMessage {
131 .then(|res, _, ctx| {
133 Ok(Ok(res)) => ctx.text(res),
135 Err(e) => error!("{}", &e),
137 actix::fut::ready(())
141 ws::Message::Binary(_bin) => info!("Unexpected binary"),
142 ws::Message::Close(_) => {
151 /// helper method that sends ping to client every second.
153 /// also this method checks heartbeats from client
154 fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
155 ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
156 // check client heartbeats
157 if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
158 // heartbeat timed out
159 debug!("Websocket Client heartbeat failed, disconnecting!");
161 // notify chat server
162 act.cs_addr.do_send(Disconnect {
164 ip: act.ip.to_owned(),
170 // don't try to send a ping