Deliver idle native editor previews over a persistent socket
This commit is contained in:
1 parent
3504a43bde
commit
44e5774b3a
5 files changed
+529
-129
No files matched your search
@@ -0,0 +1,131 @@
|
||||
use super::{Edit, EditorSession, MAX_EDIT_BODY, PreviewReply, reply};
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
sync::{Mutex, Weak, mpsc},
|
||||
time::Instant,
|
||||
};
|
||||
use tiny_http::{Header, Request, Response};
|
||||
use tungstenite::{
|
||||
Message, WebSocket,
|
||||
handshake::server::{Request as HandshakeRequest, create_response},
|
||||
protocol::{Role, WebSocketConfig},
|
||||
};
|
||||
|
||||
pub(super) fn open(request: Request, session: Weak<Mutex<EditorSession>>) {
|
||||
let host = header(&request, "Host");
|
||||
let origin = header(&request, "Origin");
|
||||
if !host.zip(origin).is_some_and(|(host, origin)| {
|
||||
origin.strip_prefix("http://") == Some(host)
|
||||
&& host
|
||||
.parse::<tungstenite::http::uri::Authority>()
|
||||
.is_ok_and(|authority| matches!(authority.host(), "127.0.0.1" | "localhost"))
|
||||
}) {
|
||||
reply(
|
||||
request,
|
||||
403,
|
||||
json!({ "error": "Preview socket requires the editor origin" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
let Some(accept) = websocket_accept(&request) else {
|
||||
reply(
|
||||
request,
|
||||
400,
|
||||
json!({ "error": "Invalid preview socket handshake" }),
|
||||
);
|
||||
return;
|
||||
};
|
||||
std::thread::spawn(move || {
|
||||
let response = Response::empty(101).with_header(accept);
|
||||
let stream = request.upgrade("websocket", response);
|
||||
let config = WebSocketConfig::default()
|
||||
.max_message_size(Some(MAX_EDIT_BODY as usize))
|
||||
.max_frame_size(Some(MAX_EDIT_BODY as usize));
|
||||
let mut socket = WebSocket::from_raw_socket(stream, Role::Server, Some(config));
|
||||
while let Ok(message) = socket.read() {
|
||||
let received = Instant::now();
|
||||
let result = match message {
|
||||
Message::Text(text) => serde_json::from_slice::<Edit>(text.as_bytes()),
|
||||
Message::Binary(bytes) => serde_json::from_slice::<Edit>(&bytes),
|
||||
Message::Ping(_) => {
|
||||
// Tungstenite queues the pong when reading a ping.
|
||||
if socket.flush().is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Message::Pong(_) => continue,
|
||||
Message::Close(_) => {
|
||||
let _ = socket.flush();
|
||||
break;
|
||||
}
|
||||
Message::Frame(_) => break,
|
||||
};
|
||||
let Ok(edit) = result else {
|
||||
// Invalid JSON cannot be attributed to a pending sequence.
|
||||
let _ = socket.close(None);
|
||||
break;
|
||||
};
|
||||
let sequence = edit.sequence;
|
||||
let (status, body) = if let Some(session) = session.upgrade() {
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
session
|
||||
.lock()
|
||||
.unwrap()
|
||||
.submit_edit(edit, received, PreviewReply::Socket(sender));
|
||||
drop(session);
|
||||
let Ok(response) = receiver.recv() else {
|
||||
break;
|
||||
};
|
||||
response
|
||||
} else {
|
||||
(
|
||||
409,
|
||||
json!({ "error": "The project is no longer open. Reload to reopen it." }),
|
||||
)
|
||||
};
|
||||
if socket
|
||||
.send(Message::text(
|
||||
json!({ "sequence": sequence, "status": status, "body": body }).to_string(),
|
||||
))
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn header<'a>(request: &'a Request, name: &'static str) -> Option<&'a str> {
|
||||
let mut matches = request
|
||||
.headers()
|
||||
.iter()
|
||||
.filter(|header| header.field.equiv(name));
|
||||
let value = matches.next()?.value.as_str();
|
||||
matches.next().is_none().then_some(value)
|
||||
}
|
||||
|
||||
fn websocket_accept(request: &Request) -> Option<Header> {
|
||||
let mut handshake = HandshakeRequest::builder()
|
||||
.method("GET")
|
||||
.version(tungstenite::http::Version::HTTP_11);
|
||||
if request.http_version() != &tiny_http::HTTPVersion(1, 1)
|
||||
|| request.body_length().is_some_and(|length| length != 0)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
for name in [
|
||||
"Connection",
|
||||
"Upgrade",
|
||||
"Sec-WebSocket-Version",
|
||||
"Sec-WebSocket-Key",
|
||||
] {
|
||||
handshake = handshake.header(name, header(request, name)?);
|
||||
}
|
||||
let response = create_response(&handshake.body(()).ok()?).ok()?;
|
||||
Header::from_bytes(
|
||||
"Sec-WebSocket-Accept",
|
||||
response.headers().get("Sec-WebSocket-Accept")?.as_bytes(),
|
||||
)
|
||||
.ok()
|
||||
}
|
||||
Reference in new issue
Block a user