BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / realtime / callback.rs

callback.rs

callback.rs 3.4 KiB Download Raw
1use serde::Deserialize;
2use tokio::sync::mpsc;
3
4const CALLBACK_CHANNEL: &str = "callback";
5const MAX_CALLBACK_BODY: usize = 4 * 1024 * 1024;
6
7/// A Trouter request for a callback URL the client handed out (`<surl>callAgent/...`), held open until replied.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct TrouterCallback {
10 pub request_id: i64,
11 pub path: String,
12 pub content_encoding: Option<String>,
13 pub body: String,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub(super) struct CallbackReply {
18 pub request_id: i64,
19 pub status: u16,
20 pub body: String,
21}
22
23/// Answers held Trouter callbacks; unanswered ones get an empty 200 from the page after a few seconds.
24#[derive(Debug, Clone)]
25pub struct CallbackReplier {
26 pub(super) sender: mpsc::UnboundedSender<CallbackReply>,
27}
28
29impl CallbackReplier {
30 pub fn reply(&self, request_id: i64, status: u16, body: impl Into<String>) {
31 let _ = self.sender.send(CallbackReply {
32 request_id,
33 status,
34 body: body.into(),
35 });
36 }
37}
38
39#[derive(Deserialize)]
40struct WireCallback {
41 channel: String,
42 #[serde(rename = "requestId")]
43 request_id: i64,
44 path: String,
45 #[serde(rename = "contentEncoding", default)]
46 content_encoding: Option<String>,
47 #[serde(default)]
48 body: String,
49}
50
51pub(super) fn decode_callback(payload: &str) -> Option<TrouterCallback> {
52 if !payload.contains("\"channel\":\"callback\"") {
53 return None;
54 }
55 let wire: WireCallback = serde_json::from_str(payload).ok()?;
56 if wire.channel != CALLBACK_CHANNEL || wire.body.len() > MAX_CALLBACK_BODY {
57 return None;
58 }
59 Some(TrouterCallback {
60 request_id: wire.request_id,
61 path: wire.path,
62 content_encoding: wire.content_encoding,
63 body: wire.body,
64 })
65}
66
67pub(super) fn reply_expression(global_name: &str, reply: &CallbackReply) -> String {
68 format!(
69 "window.{global_name} ? window.{global_name}.reply({}, {}, {}) : false",
70 reply.request_id,
71 reply.status,
72 serde_json::Value::String(reply.body.clone())
73 )
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 #[test]
81 fn decodes_callback_payload() {
82 let payload = r#"{"channel":"callback","requestId":1941608514,"path":"callAgent/a/b/call/acceptance/","contentEncoding":"gzip","body":"H4sI"}"#;
83 let callback = decode_callback(payload).unwrap();
84 assert_eq!(callback.request_id, 1941608514);
85 assert_eq!(callback.path, "callAgent/a/b/call/acceptance/");
86 assert_eq!(callback.content_encoding.as_deref(), Some("gzip"));
87 assert_eq!(callback.body, "H4sI");
88 }
89
90 #[test]
91 fn negative_request_ids_are_callbacks_too() {
92 let payload = r#"{"channel":"callback","requestId":-2,"path":"callAgent/a/b/conversation/rosterUpdate/","body":"{}"}"#;
93 assert_eq!(decode_callback(payload).unwrap().request_id, -2);
94 }
95
96 #[test]
97 fn other_channels_are_not_callbacks() {
98 assert!(decode_callback(r#"{"channel":"status","kind":"connected"}"#).is_none());
99 assert!(decode_callback("garbage").is_none());
100 }
101
102 #[test]
103 fn reply_body_is_a_js_string_literal() {
104 let reply = CallbackReply {
105 request_id: 7,
106 status: 200,
107 body: "{\"a\":\"</script>'\"}".into(),
108 };
109 assert_eq!(
110 reply_expression("__x", &reply),
111 r#"window.__x ? window.__x.reply(7, 200, "{\"a\":\"</script>'\"}") : false"#
112 );
113 }
114}