use std::{
borrow::Cow,
collections::VecDeque,
future::Future,
io,
pin::Pin,
sync::{Mutex, PoisonError},
task::{Context, Poll},
time::Duration,
};
use bytes::{BufMut, BytesMut};
use futures_util::{
stream::{SplitSink, SplitStream},
SinkExt, StreamExt,
};
use rho_protocol::{
methods::{
AUTH_CHOOSE_STORE, AUTH_KEY, AUTH_LIST, AUTH_LOGIN, AUTH_LOGOUT, HELLO, HOOKS_LIST,
MCP_LIST, MCP_PROBE, MODEL_LIST, MODEL_REFRESH, PLUGINS_INSTALL, PLUGINS_LIST,
PLUGINS_SET_ENABLED, PLUGINS_UPDATE, RUNTIME_LIST, SESSION_ATTACH, SESSION_FORK,
SESSION_NEW, SESSION_PROMPT,
},
FrameError, Message, MessageReader, RequestId, Response, MAX_LINE_BYTES,
};
use serde_json::{Map, Value};
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf},
sync::mpsc,
time::{Instant, Sleep},
};
use tokio_tungstenite::{
tungstenite::{
protocol::{
frame::{coding::CloseCode, CloseFrame},
Role, WebSocketConfig,
},
Error as WsError, Message as WsMessage,
},
WebSocketStream,
};
const OUTGOING_QUEUE: usize = 16;
const STREAM_FRAME_BYTES: usize = 64 * 1024;
const PING_INTERVAL: Duration = Duration::from_secs(30);
const IDLE_TIMEOUT: Duration = Duration::from_secs(300);
const ENVIRONMENT_METHODS: [&str; 19] = [
SESSION_NEW,
SESSION_FORK,
SESSION_PROMPT,
SESSION_ATTACH,
AUTH_LIST,
AUTH_KEY,
AUTH_LOGOUT,
AUTH_LOGIN,
AUTH_CHOOSE_STORE,
MODEL_LIST,
MODEL_REFRESH,
RUNTIME_LIST,
MCP_LIST,
MCP_PROBE,
HOOKS_LIST,
PLUGINS_LIST,
PLUGINS_INSTALL,
PLUGINS_UPDATE,
PLUGINS_SET_ENABLED,
];
fn websocket_config() -> WebSocketConfig {
WebSocketConfig::default()
.max_message_size(Some(MAX_LINE_BYTES))
.max_frame_size(Some(MAX_LINE_BYTES))
}
pub(super) async fn relay_websocket<S, D>(
socket: S,
daemon: D,
relayed: &Relayed<'_>,
draining: impl Future<Output = ()>,
cut_off: impl Future<Output = CloseFrame>,
) where
S: AsyncRead + AsyncWrite + Unpin,
D: AsyncRead + AsyncWrite + Unpin,
{
let ws = WebSocketStream::from_raw_socket(
ClientSocket::new(socket),
Role::Server,
Some(websocket_config()),
)
.await;
let (ws_sink, ws_stream) = ws.split();
let (daemon_read, daemon_write) = tokio::io::split(daemon);
let (frames, outgoing) = mpsc::channel::<WsMessage>(OUTGOING_QUEUE);
let hello = PendingHellos::default();
let hello = &hello;
let relay = async move {
let outbound = daemon_to_client(daemon_read, frames.clone(), hello);
tokio::pin!(outbound);
let inbound = client_to_daemon(ws_stream, daemon_write, relayed, hello, draining, cut_off);
let first = tokio::select! {
ended = inbound => First::Client(ended),
close = &mut outbound => First::Daemon(close),
};
let close = match first {
First::Client(Inbound::ClientGone) => None,
First::Client(Inbound::Refused(close)) => Some(close),
First::Client(Inbound::Draining) => {
(&mut outbound).await;
Some(close_frame(CloseCode::Away, "server going away".to_owned()))
}
First::Client(Inbound::DaemonGone) => Some(outbound.await),
First::Daemon(close) => Some(close),
};
if let Some(close) = close {
let _ = frames.send(WsMessage::Close(Some(close))).await;
}
};
tokio::join!(write_frames(ws_sink, outgoing), relay);
}
enum First {
Client(Inbound),
Daemon(CloseFrame),
}
enum Inbound {
ClientGone,
Refused(CloseFrame),
Draining,
DaemonGone,
}
async fn write_frames<S>(
mut sink: SplitSink<WebSocketStream<S>, WsMessage>,
mut outgoing: mpsc::Receiver<WsMessage>,
) where
S: AsyncRead + AsyncWrite + Unpin,
{
let mut ping = tokio::time::interval_at(Instant::now() + PING_INTERVAL, PING_INTERVAL);
ping.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
let message = tokio::select! {
message = outgoing.recv() => match message {
Some(message) => message,
None => break,
},
_ = ping.tick() => WsMessage::Ping(Default::default()),
};
if sink.send(message).await.is_err() {
return;
}
}
let _ = sink.close().await;
}
#[derive(Default)]
struct PendingHellos(Mutex<DaemonOutput>);
enum DaemonOutput {
Lines(VecDeque<RequestId>),
Compressed,
}
impl Default for DaemonOutput {
fn default() -> Self {
Self::Lines(VecDeque::new())
}
}
impl PendingHellos {
fn forwarded(&self, id: RequestId) {
match &mut *self.lock() {
DaemonOutput::Lines(pending) => pending.push_back(id),
DaemonOutput::Compressed => {}
}
}
fn switched_by(&self, line: &[u8]) -> bool {
let mut output = self.lock();
let DaemonOutput::Lines(pending) = &mut *output else {
return false;
};
let Some(oldest) = pending.front() else {
return false;
};
let Ok(Message::Response(Response {
id: Some(id),
outcome,
})) = Message::parse(line)
else {
return false;
};
if id != *oldest {
return false;
}
pending.pop_front();
let switched = outcome.is_ok_and(|result| result.get("compression").is_some());
if switched {
*output = DaemonOutput::Compressed;
}
switched
}
fn lock(&self) -> std::sync::MutexGuard<'_, DaemonOutput> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
async fn client_to_daemon<S, W>(
mut stream: SplitStream<WebSocketStream<S>>,
mut daemon: W,
relayed: &Relayed<'_>,
hello: &PendingHellos,
draining: impl Future<Output = ()>,
cut_off: impl Future<Output = CloseFrame>,
) -> Inbound
where
S: AsyncRead + AsyncWrite + Unpin,
W: AsyncWrite + Unpin,
{
tokio::pin!(draining);
tokio::pin!(cut_off);
let ended = loop {
let next = tokio::select! {
biased;
close = &mut cut_off => break Inbound::Refused(close),
() = &mut draining => break Inbound::Draining,
next = stream.next() => next,
};
let message = match next {
None => break Inbound::ClientGone,
Some(Err(WsError::Capacity(error))) => {
tracing::debug!(%error, "WebSocket client sent an oversized message");
break Inbound::Refused(too_large("message"));
}
Some(Err(error)) => {
tracing::debug!(%error, "WebSocket read failed");
break Inbound::ClientGone;
}
Some(Ok(message)) => message,
};
match message {
WsMessage::Text(text) => match prepare_daemon_line(text.as_str(), relayed) {
Ok(line) => {
if let Some(id) = line.hello {
hello.forwarded(id);
}
let bytes = &line.bytes;
if daemon.write_all(bytes).await.is_err() || daemon.flush().await.is_err() {
break Inbound::DaemonGone;
}
}
Err(TooLarge { bytes }) => {
break Inbound::Refused(too_large(&format!("message of {bytes} bytes")));
}
},
WsMessage::Binary(_) => {
break Inbound::Refused(close_frame(
CloseCode::Unsupported,
"rho-protocol requires UTF-8 JSON text frames".to_owned(),
));
}
WsMessage::Close(_) => break Inbound::ClientGone,
WsMessage::Ping(_) | WsMessage::Pong(_) | WsMessage::Frame(_) => {}
}
};
let _ = daemon.shutdown().await;
ended
}
struct ClientSocket<S> {
socket: S,
silence: Pin<Box<Sleep>>,
write_waited: bool,
}
impl<S> ClientSocket<S> {
fn new(socket: S) -> Self {
Self {
socket,
silence: Box::pin(tokio::time::sleep(IDLE_TIMEOUT)),
write_waited: false,
}
}
fn heard(&mut self) {
self.silence.as_mut().reset(Instant::now() + IDLE_TIMEOUT);
}
fn wrote(&mut self, written: &Poll<io::Result<usize>>) {
match written {
Poll::Pending => self.write_waited = true,
Poll::Ready(Ok(bytes)) if *bytes > 0 && self.write_waited => {
self.write_waited = false;
self.heard();
}
Poll::Ready(_) => self.write_waited = false,
}
}
}
impl<S: AsyncRead + Unpin> AsyncRead for ClientSocket<S> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let this = self.get_mut();
let before = buf.filled().len();
let read = Pin::new(&mut this.socket).poll_read(cx, buf);
if buf.filled().len() > before {
this.heard();
} else if read.is_pending() && this.silence.as_mut().poll(cx).is_ready() {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::TimedOut,
format!("the client was silent for {IDLE_TIMEOUT:?} (IDLE_TIMEOUT)"),
)));
}
read
}
}
impl<S: AsyncWrite + Unpin> AsyncWrite for ClientSocket<S> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let this = self.get_mut();
let written = Pin::new(&mut this.socket).poll_write(cx, buf);
this.wrote(&written);
written
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> Poll<io::Result<usize>> {
let this = self.get_mut();
let written = Pin::new(&mut this.socket).poll_write_vectored(cx, bufs);
this.wrote(&written);
written
}
fn is_write_vectored(&self) -> bool {
self.socket.is_write_vectored()
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.socket).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.socket).poll_shutdown(cx)
}
}
async fn daemon_to_client<R>(
daemon: R,
frames: mpsc::Sender<WsMessage>,
hello: &PendingHellos,
) -> CloseFrame
where
R: AsyncRead + Unpin,
{
let mut reader = MessageReader::new(daemon);
loop {
let line = match reader.read_line().await {
Ok(Some(line)) => line,
Ok(None) => return daemon_closed(),
Err(FrameError::LineTooLong { .. }) => {
return too_large("a daemon message");
}
Err(error) => return daemon_failed(&error),
};
let switched = hello.switched_by(&line);
let text = match String::from_utf8(line) {
Ok(text) => text,
Err(error) => {
tracing::debug!(%error, "daemon sent a non-UTF-8 line");
return close_frame(CloseCode::Error, "daemon sent invalid UTF-8".to_owned());
}
};
if frames.send(WsMessage::Text(text.into())).await.is_err() {
return client_gone();
}
if switched {
let (daemon, buffered) = reader.into_parts();
return daemon_stream_to_client(daemon, buffered, frames).await;
}
}
}
async fn daemon_stream_to_client<R>(
mut daemon: R,
buffered: Vec<u8>,
frames: mpsc::Sender<WsMessage>,
) -> CloseFrame
where
R: AsyncRead + Unpin,
{
if !buffered.is_empty()
&& frames
.send(WsMessage::Binary(buffered.into()))
.await
.is_err()
{
return client_gone();
}
let mut read = BytesMut::with_capacity(STREAM_FRAME_BYTES);
loop {
match daemon
.read_buf(&mut (&mut read).limit(STREAM_FRAME_BYTES))
.await
{
Ok(0) => return daemon_closed(),
Ok(_) => {}
Err(error) => return daemon_failed(&error),
}
if frames
.send(WsMessage::Binary(read.split().freeze()))
.await
.is_err()
{
return client_gone();
}
read.reserve(STREAM_FRAME_BYTES);
}
}
fn daemon_closed() -> CloseFrame {
close_frame(CloseCode::Normal, "daemon closed the connection".to_owned())
}
fn daemon_failed(error: &dyn std::fmt::Display) -> CloseFrame {
tracing::debug!(%error, "daemon read failed");
close_frame(CloseCode::Error, "daemon stream failed".to_owned())
}
fn client_gone() -> CloseFrame {
close_frame(CloseCode::Normal, "client gone".to_owned())
}
pub(super) fn close_frame(code: CloseCode, reason: String) -> CloseFrame {
CloseFrame {
code,
reason: reason.into(),
}
}
fn too_large(what: &str) -> CloseFrame {
close_frame(
CloseCode::Size,
format!("{what} exceeds MAX_LINE_BYTES ({MAX_LINE_BYTES} bytes)"),
)
}
pub(super) struct Relayed<'a> {
pub(super) host_env: &'a Map<String, Value>,
pub(super) device: Option<&'a str>,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct DaemonLine {
pub(super) bytes: Vec<u8>,
pub(super) hello: Option<RequestId>,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct TooLarge {
pub(super) bytes: usize,
}
pub(super) fn prepare_daemon_line(
frame: &str,
relayed: &Relayed<'_>,
) -> Result<DaemonLine, TooLarge> {
let frame = if frame.contains(['\r', '\n']) {
Cow::Owned(frame.replace(['\r', '\n'], " "))
} else {
Cow::Borrowed(frame)
};
let mut hello = None;
let mut bytes = match serde_json::from_str::<Value>(&frame) {
Ok(mut value) => {
apply_host_environment(&mut value, relayed.host_env);
let is_hello = value.get("method").and_then(Value::as_str) == Some(HELLO);
if is_hello {
stamp_device(&mut value, relayed.device);
}
let bytes = serde_json::to_vec(&value).expect("a serde_json::Value always serializes");
if is_hello {
hello = hello_id(&bytes);
}
bytes
}
Err(_) => frame.into_owned().into_bytes(),
};
if bytes.len() > MAX_LINE_BYTES {
return Err(TooLarge { bytes: bytes.len() });
}
bytes.push(b'\n');
Ok(DaemonLine { bytes, hello })
}
fn stamp_device(hello: &mut Value, device: Option<&str>) {
let Some(object) = hello.as_object_mut() else {
return;
};
match (object.get_mut("params"), device) {
(Some(Value::Object(params)), Some(device)) => {
params.insert("bridge_device".to_owned(), Value::from(device));
}
(Some(Value::Object(params)), None) => {
params.remove("bridge_device");
}
(_, None) => {}
(_, Some(device)) => {
object.insert(
"params".to_owned(),
serde_json::json!({ "bridge_device": device }),
);
}
}
}
fn apply_host_environment(message: &mut Value, host_env: &Map<String, Value>) {
let Some(object) = message.as_object_mut() else {
return;
};
let takes_environment = object
.get("method")
.and_then(Value::as_str)
.is_some_and(|method| ENVIRONMENT_METHODS.contains(&method));
if !takes_environment {
return;
}
let Some(params) = object.get_mut("params").and_then(Value::as_object_mut) else {
return;
};
let environment = match params.remove("environment") {
None => Value::Object(host_env.clone()),
Some(Value::Object(client)) => {
let mut merged = host_env.clone();
merged.extend(client);
Value::Object(merged)
}
Some(malformed) => malformed,
};
params.insert("environment".to_owned(), environment);
}
fn hello_id(line: &[u8]) -> Option<RequestId> {
match Message::parse(line) {
Ok(Message::Request(request)) => Some(request.id),
_ => None,
}
}
#[cfg(test)]
#[path = "bridge_tests.rs"]
mod tests;