Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
6
akode-rs/app-server-transport/BUILD.bazel
Normal file
6
akode-rs/app-server-transport/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "app-server-transport",
|
||||
crate_name = "akode_app_server_transport",
|
||||
)
|
||||
70
akode-rs/app-server-transport/Cargo.toml
Normal file
70
akode-rs/app-server-transport/Cargo.toml
Normal file
@@ -0,0 +1,70 @@
|
||||
[package]
|
||||
name = "akode-app-server-transport"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "akode_app_server_transport"
|
||||
path = "src/lib.rs"
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-http-client = { workspace = true }
|
||||
akode-websocket-client = { workspace = true }
|
||||
axum = { workspace = true, default-features = false, features = [
|
||||
"http1",
|
||||
"json",
|
||||
"tokio",
|
||||
"ws",
|
||||
] }
|
||||
base64 = { workspace = true }
|
||||
akode-api = { workspace = true }
|
||||
akode-app-server-protocol = { workspace = true }
|
||||
akode-core = { workspace = true }
|
||||
akode-login = { workspace = true }
|
||||
akode-model-provider = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-state = { workspace = true }
|
||||
akode-uds = { workspace = true }
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
akode-utils-rustls-provider = { workspace = true }
|
||||
akode-websocket-auth = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
gethostname = { workspace = true }
|
||||
httpdate = { workspace = true }
|
||||
owo-colors = { workspace = true, features = ["supports-colors"] }
|
||||
rand = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
time = { workspace = true }
|
||||
tokio = { workspace = true, features = [
|
||||
"io-std",
|
||||
"macros",
|
||||
"process",
|
||||
"rt-multi-thread",
|
||||
] }
|
||||
tokio-tungstenite = { workspace = true }
|
||||
tokio-util = { workspace = true }
|
||||
tracing = { workspace = true, features = ["log"] }
|
||||
url = { workspace = true }
|
||||
uuid = { workspace = true, features = ["serde", "v7"] }
|
||||
zstd = { workspace = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = { workspace = true }
|
||||
signal-hook = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = { workspace = true }
|
||||
core_test_support = { workspace = true }
|
||||
wiremock = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
akode-config = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
19
akode-rs/app-server-transport/src/connection_auth.rs
Normal file
19
akode-rs/app-server-transport/src/connection_auth.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
//! Binds a transport connection to the authentication owner that established it.
|
||||
//! Owner revisions invalidate queued work even before transport closure is delivered.
|
||||
//! aKode: only remote control created these bindings; it was removed, so none are created today.
|
||||
|
||||
use akode_login::AuthChangeState;
|
||||
use tokio::sync::watch;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ConnectionAuth {
|
||||
changes: watch::Receiver<AuthChangeState>,
|
||||
owner_generation: u64,
|
||||
}
|
||||
|
||||
impl ConnectionAuth {
|
||||
pub fn is_current(&self) -> bool {
|
||||
self.changes.borrow().owner_generation == self.owner_generation
|
||||
&& self.changes.has_changed().is_ok()
|
||||
}
|
||||
}
|
||||
81
akode-rs/app-server-transport/src/daemon_recovery.rs
Normal file
81
akode-rs/app-server-transport/src/daemon_recovery.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
//! Shared on-disk candidate set for managed daemon restarts.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
use akode_core::path_utils::write_atomically;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct RecoverySnapshot {
|
||||
#[serde(skip)]
|
||||
pub loaded: BTreeSet<String>,
|
||||
pub interrupted: BTreeMap<String, InterruptedTurn>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct InterruptedTurn {
|
||||
pub turn_id: String,
|
||||
pub output_schema: Option<serde_json::Value>,
|
||||
pub service_tier: Option<String>,
|
||||
/// Only local execution with thread-owned configuration can continue automatically.
|
||||
/// Older snapshots without this identity are reloaded without continuation.
|
||||
pub local_environment: Option<akode_app_server_protocol::ThreadEnvironment>,
|
||||
}
|
||||
|
||||
// Old servers accept the array and skip this non-thread entry during best-effort
|
||||
// restoration. Keeping metadata in the same atomic file avoids stale sidecars.
|
||||
const INTERRUPTION_PREFIX: &str = "codex-interrupted-v1:";
|
||||
|
||||
pub fn read_snapshot(path: &Path) -> io::Result<RecoverySnapshot> {
|
||||
let mut loaded: BTreeSet<String> = match std::fs::read(path) {
|
||||
Ok(contents) => serde_json::from_slice(&contents).map_err(io::Error::other)?,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(RecoverySnapshot::default()),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let mut snapshot = RecoverySnapshot::default();
|
||||
loaded.retain(|entry| {
|
||||
if let Some(metadata) = entry.strip_prefix(INTERRUPTION_PREFIX) {
|
||||
if let Ok(saved) = serde_json::from_str::<RecoverySnapshot>(metadata) {
|
||||
snapshot = saved;
|
||||
}
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
snapshot.interrupted.retain(|id, _| loaded.contains(id));
|
||||
snapshot.loaded = loaded;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
pub fn read_candidates(path: &Path) -> io::Result<BTreeSet<String>> {
|
||||
Ok(read_snapshot(path)?.loaded)
|
||||
}
|
||||
|
||||
pub fn write_candidates(path: &Path, candidates: &BTreeSet<String>) -> io::Result<()> {
|
||||
write_snapshot(
|
||||
path,
|
||||
&RecoverySnapshot {
|
||||
loaded: candidates.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn write_snapshot(path: &Path, snapshot: &RecoverySnapshot) -> io::Result<()> {
|
||||
let mut saved = snapshot.loaded.clone();
|
||||
if !snapshot.interrupted.is_empty() {
|
||||
saved.insert(format!(
|
||||
"{INTERRUPTION_PREFIX}{}",
|
||||
serde_json::to_string(snapshot).map_err(io::Error::other)?
|
||||
));
|
||||
}
|
||||
write_atomically(
|
||||
path,
|
||||
&serde_json::to_string(&saved).map_err(io::Error::other)?,
|
||||
)
|
||||
}
|
||||
53
akode-rs/app-server-transport/src/daemon_shutdown.rs
Normal file
53
akode-rs/app-server-transport/src/daemon_shutdown.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
//! The detached Windows updater has no control socket, so its owner requests
|
||||
//! termination through a file in its private state directory. Managed app-server
|
||||
//! shutdown instead uses the protected local socket.
|
||||
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
#[cfg(windows)]
|
||||
use std::path::PathBuf;
|
||||
#[cfg(windows)]
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(windows)]
|
||||
pub const DAEMON_SHUTDOWN_FILE_ENV: &str = "AKODE_DAEMON_SHUTDOWN_FILE";
|
||||
|
||||
/// Waits for and consumes one updater shutdown request.
|
||||
#[cfg(windows)]
|
||||
pub async fn daemon_shutdown_signal() -> io::Result<()> {
|
||||
let Some(path) = std::env::var_os(DAEMON_SHUTDOWN_FILE_ENV).map(PathBuf::from) else {
|
||||
return std::future::pending().await;
|
||||
};
|
||||
loop {
|
||||
if take_shutdown_request(&path, std::process::id())? {
|
||||
return Ok(());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn take_shutdown_request(path: &Path, pid: u32) -> io::Result<bool> {
|
||||
let file = match std::fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
// Descendant app-servers may inherit the control path. Only the intended
|
||||
// process can consume a request. Bound reads to a u32 PID plus one extra byte.
|
||||
let mut contents = Vec::new();
|
||||
file.take(/*limit*/ 11).read_to_end(&mut contents)?;
|
||||
if contents != pid.to_string().as_bytes() {
|
||||
return Ok(false);
|
||||
}
|
||||
// Synchronous consumption cannot lose a request to select cancellation.
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "daemon_shutdown_tests.rs"]
|
||||
mod tests;
|
||||
22
akode-rs/app-server-transport/src/daemon_shutdown_tests.rs
Normal file
22
akode-rs/app-server-transport/src/daemon_shutdown_tests.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use super::take_shutdown_request;
|
||||
|
||||
#[test]
|
||||
fn inherited_control_path_cannot_consume_another_process_request() {
|
||||
let directory = tempfile::tempdir().expect("directory");
|
||||
let request = directory.path().join("shutdown");
|
||||
std::fs::write(&request, "1234").expect("request");
|
||||
assert!(!take_shutdown_request(&request, /*pid*/ 5678).expect("descendant probe"));
|
||||
assert!(take_shutdown_request(&request, /*pid*/ 1234).expect("parent probe"));
|
||||
assert!(!take_shutdown_request(&request, /*pid*/ 1234).expect("already consumed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_or_invalid_requests_are_not_consumed() {
|
||||
let directory = tempfile::tempdir().expect("directory");
|
||||
let request = directory.path().join("shutdown");
|
||||
for contents in [b"".as_slice(), b"123", b"1234junk", &[0xff; 20]] {
|
||||
std::fs::write(&request, contents).expect("request");
|
||||
assert!(!take_shutdown_request(&request, /*pid*/ 1234).expect("probe"));
|
||||
assert!(request.exists());
|
||||
}
|
||||
}
|
||||
54
akode-rs/app-server-transport/src/lib.rs
Normal file
54
akode-rs/app-server-transport/src/lib.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
pub mod daemon_recovery;
|
||||
#[cfg(any(windows, test))]
|
||||
mod daemon_shutdown;
|
||||
#[cfg(windows)]
|
||||
pub use daemon_shutdown::DAEMON_SHUTDOWN_FILE_ENV;
|
||||
#[cfg(windows)]
|
||||
pub use daemon_shutdown::daemon_shutdown_signal;
|
||||
/// Only managed app-server launches accept the local socket shutdown request.
|
||||
pub const DAEMON_SHUTDOWN_SOCKET_ENV: &str = "AKODE_DAEMON_SHUTDOWN_SOCKET";
|
||||
mod connection_auth;
|
||||
mod outgoing_message;
|
||||
mod transport;
|
||||
mod websocket_compression;
|
||||
|
||||
pub use connection_auth::ConnectionAuth;
|
||||
pub use outgoing_message::ConnectionId;
|
||||
pub use outgoing_message::OutgoingError;
|
||||
pub use outgoing_message::OutgoingMessage;
|
||||
pub use outgoing_message::OutgoingResponse;
|
||||
pub use outgoing_message::QueuedOutgoingMessage;
|
||||
pub use transport::AppServerStartupLock;
|
||||
pub use transport::AppServerTransport;
|
||||
pub use transport::AppServerTransportParseError;
|
||||
pub use transport::CHANNEL_CAPACITY;
|
||||
pub use transport::ConnectionOrigin;
|
||||
pub use transport::DaemonShutdownAccess;
|
||||
pub use transport::DaemonSocketFileGuard;
|
||||
pub use transport::REMOTE_CONTROL_DISABLED_ENV_VAR;
|
||||
pub use transport::RemoteControlDisabledByRequirements;
|
||||
pub use transport::RemoteControlEnableError;
|
||||
pub use transport::RemoteControlHandle;
|
||||
pub use transport::RemoteControlPolicy;
|
||||
pub use transport::RemoteControlStartConfig;
|
||||
pub use transport::RemoteControlStartupMode;
|
||||
pub use transport::RemoteControlUnavailable;
|
||||
pub use transport::TransportEvent;
|
||||
pub use transport::acquire_app_server_startup_lock;
|
||||
pub use transport::app_server_control_socket_path;
|
||||
pub use transport::app_server_startup_lock_path;
|
||||
pub use transport::bind_private_daemon_socket;
|
||||
pub use transport::daemon_recovery_file_path;
|
||||
pub use transport::start_control_socket_acceptor;
|
||||
pub use transport::start_remote_control;
|
||||
pub use transport::start_stdio_connection;
|
||||
pub use transport::start_websocket_acceptor;
|
||||
pub use transport::take_remote_control_disabled_env;
|
||||
pub use transport::verified_local_daemon_socket;
|
||||
pub use websocket_compression::CompressionConnection;
|
||||
pub use websocket_compression::WEBSOCKET_COMPRESSION_HEADER;
|
||||
pub use websocket_compression::WebSocketCompression;
|
||||
pub use websocket_compression::ZSTD_STREAM_PROTOCOL;
|
||||
pub use websocket_compression::ZstdDecoder;
|
||||
pub use websocket_compression::ZstdEncoder;
|
||||
pub use websocket_compression::zstd_codec_pair;
|
||||
59
akode-rs/app-server-transport/src/outgoing_message.rs
Normal file
59
akode-rs/app-server-transport/src/outgoing_message.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
use std::fmt;
|
||||
|
||||
use akode_app_server_protocol::ClientResponsePayload;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::ServerNotificationEnvelope;
|
||||
use akode_app_server_protocol::ServerRequest;
|
||||
use serde::Serialize;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// Stable identifier for a transport connection.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub struct ConnectionId(pub u64);
|
||||
|
||||
impl fmt::Display for ConnectionId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Outgoing message from the server to the client.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(untagged)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum OutgoingMessage {
|
||||
Request(ServerRequest),
|
||||
/// AppServerNotification is specific to the case where this is run as an
|
||||
/// "app server" as opposed to an MCP server.
|
||||
AppServerNotification(ServerNotificationEnvelope),
|
||||
Response(OutgoingResponse),
|
||||
Error(OutgoingError),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct OutgoingResponse {
|
||||
pub id: RequestId,
|
||||
pub result: Box<ClientResponsePayload>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct OutgoingError {
|
||||
pub error: JSONRPCErrorError,
|
||||
pub id: RequestId,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct QueuedOutgoingMessage {
|
||||
pub message: OutgoingMessage,
|
||||
pub write_complete_tx: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl QueuedOutgoingMessage {
|
||||
pub fn new(message: OutgoingMessage) -> Self {
|
||||
Self {
|
||||
message,
|
||||
write_complete_tx: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
602
akode-rs/app-server-transport/src/transport/mod.rs
Normal file
602
akode-rs/app-server-transport/src/transport/mod.rs
Normal file
@@ -0,0 +1,602 @@
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::OutgoingError;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use crate::outgoing_message::QueuedOutgoingMessage;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::JSONRPCMessage;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_core::config::find_codex_home;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::error;
|
||||
use tracing::warn;
|
||||
|
||||
/// Size of the bounded channels used to communicate between tasks. The value
|
||||
/// is a balance between throughput and memory usage - 128 messages should be
|
||||
/// plenty for an interactive CLI.
|
||||
pub const CHANNEL_CAPACITY: usize = 128;
|
||||
|
||||
mod remote_control;
|
||||
mod stdio;
|
||||
mod unix_socket;
|
||||
#[cfg(test)]
|
||||
mod unix_socket_tests;
|
||||
mod websocket;
|
||||
|
||||
pub use remote_control::REMOTE_CONTROL_DISABLED_ENV_VAR;
|
||||
pub use remote_control::RemoteControlDisabledByRequirements;
|
||||
pub use remote_control::RemoteControlEnableError;
|
||||
pub use remote_control::RemoteControlHandle;
|
||||
pub use remote_control::RemoteControlPolicy;
|
||||
pub use remote_control::RemoteControlStartConfig;
|
||||
pub use remote_control::RemoteControlStartupMode;
|
||||
pub use remote_control::RemoteControlUnavailable;
|
||||
pub use remote_control::start_remote_control;
|
||||
pub use remote_control::take_remote_control_disabled_env;
|
||||
pub use stdio::start_stdio_connection;
|
||||
pub use unix_socket::AppServerStartupLock;
|
||||
pub use unix_socket::DaemonShutdownAccess;
|
||||
pub use unix_socket::DaemonSocketFileGuard;
|
||||
pub use unix_socket::acquire_app_server_startup_lock;
|
||||
pub use unix_socket::bind_private_daemon_socket;
|
||||
pub use unix_socket::start_control_socket_acceptor;
|
||||
pub use unix_socket::verified_local_daemon_socket;
|
||||
pub use websocket::start_websocket_acceptor;
|
||||
|
||||
const INTERNAL_ERROR_CODE: i64 = -32603;
|
||||
const OVERLOADED_ERROR_CODE: i64 = -32001;
|
||||
|
||||
const APP_SERVER_CONTROL_SOCKET_DIR_NAME: &str = "app-server-control";
|
||||
const APP_SERVER_CONTROL_SOCKET_FILE_NAME: &str = "app-server-control.sock";
|
||||
const APP_SERVER_STARTUP_LOCK_FILE_NAME: &str = "app-server-startup.lock";
|
||||
const DAEMON_RECOVERY_FILE_NAME: &str = "loaded-threads.json";
|
||||
|
||||
pub fn daemon_recovery_file_path(codex_home: &Path) -> PathBuf {
|
||||
codex_home
|
||||
.join("app-server-daemon")
|
||||
.join(DAEMON_RECOVERY_FILE_NAME)
|
||||
}
|
||||
|
||||
pub fn app_server_control_socket_path(codex_home: &Path) -> std::io::Result<AbsolutePathBuf> {
|
||||
AbsolutePathBuf::from_absolute_path(
|
||||
codex_home
|
||||
.join(APP_SERVER_CONTROL_SOCKET_DIR_NAME)
|
||||
.join(APP_SERVER_CONTROL_SOCKET_FILE_NAME),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn app_server_startup_lock_path(codex_home: &Path) -> std::io::Result<AbsolutePathBuf> {
|
||||
AbsolutePathBuf::from_absolute_path(
|
||||
codex_home
|
||||
.join(APP_SERVER_CONTROL_SOCKET_DIR_NAME)
|
||||
.join(APP_SERVER_STARTUP_LOCK_FILE_NAME),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum AppServerTransport {
|
||||
Stdio,
|
||||
UnixSocket { socket_path: AbsolutePathBuf },
|
||||
WebSocket { bind_address: SocketAddr },
|
||||
Off,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub enum AppServerTransportParseError {
|
||||
UnsupportedListenUrl(String),
|
||||
InvalidUnixSocketPath { listen_url: String, message: String },
|
||||
InvalidWebSocketListenUrl(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for AppServerTransportParseError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
AppServerTransportParseError::UnsupportedListenUrl(listen_url) => write!(
|
||||
f,
|
||||
"unsupported --listen URL `{listen_url}`; expected `stdio://`, `unix://`, `unix://PATH`, `ws://IP:PORT`, or `off`"
|
||||
),
|
||||
AppServerTransportParseError::InvalidUnixSocketPath {
|
||||
listen_url,
|
||||
message,
|
||||
} => write!(
|
||||
f,
|
||||
"invalid unix socket --listen URL `{listen_url}`; failed to resolve socket path: {message}"
|
||||
),
|
||||
AppServerTransportParseError::InvalidWebSocketListenUrl(listen_url) => write!(
|
||||
f,
|
||||
"invalid websocket --listen URL `{listen_url}`; expected `ws://IP:PORT`"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AppServerTransportParseError {}
|
||||
|
||||
impl AppServerTransport {
|
||||
pub const DEFAULT_LISTEN_URL: &'static str = "stdio://";
|
||||
|
||||
pub fn from_listen_url(listen_url: &str) -> Result<Self, AppServerTransportParseError> {
|
||||
if listen_url == Self::DEFAULT_LISTEN_URL {
|
||||
return Ok(Self::Stdio);
|
||||
}
|
||||
|
||||
if let Some(raw_socket_path) = listen_url.strip_prefix("unix://") {
|
||||
let socket_path = if raw_socket_path.is_empty() {
|
||||
let codex_home = find_codex_home().map_err(|err| {
|
||||
AppServerTransportParseError::InvalidUnixSocketPath {
|
||||
listen_url: listen_url.to_string(),
|
||||
message: format!("failed to resolve AKODE_HOME: {err}"),
|
||||
}
|
||||
})?;
|
||||
app_server_control_socket_path(&codex_home).map_err(|err| {
|
||||
AppServerTransportParseError::InvalidUnixSocketPath {
|
||||
listen_url: listen_url.to_string(),
|
||||
message: err.to_string(),
|
||||
}
|
||||
})?
|
||||
} else {
|
||||
AbsolutePathBuf::relative_to_current_dir(raw_socket_path).map_err(|err| {
|
||||
AppServerTransportParseError::InvalidUnixSocketPath {
|
||||
listen_url: listen_url.to_string(),
|
||||
message: err.to_string(),
|
||||
}
|
||||
})?
|
||||
};
|
||||
return Ok(Self::UnixSocket { socket_path });
|
||||
}
|
||||
|
||||
if listen_url == "off" {
|
||||
return Ok(Self::Off);
|
||||
}
|
||||
|
||||
if let Some(socket_addr) = listen_url.strip_prefix("ws://") {
|
||||
let bind_address = socket_addr.parse::<SocketAddr>().map_err(|_| {
|
||||
AppServerTransportParseError::InvalidWebSocketListenUrl(listen_url.to_string())
|
||||
})?;
|
||||
return Ok(Self::WebSocket { bind_address });
|
||||
}
|
||||
|
||||
Err(AppServerTransportParseError::UnsupportedListenUrl(
|
||||
listen_url.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for AppServerTransport {
|
||||
type Err = AppServerTransportParseError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Self::from_listen_url(s)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum TransportEvent {
|
||||
/// Accepted on the managed local control socket, outside JSON-RPC.
|
||||
DaemonShutdown,
|
||||
ConnectionOpened {
|
||||
connection_id: ConnectionId,
|
||||
origin: ConnectionOrigin,
|
||||
auth: Option<crate::ConnectionAuth>,
|
||||
writer: mpsc::Sender<QueuedOutgoingMessage>,
|
||||
disconnect_sender: Option<CancellationToken>,
|
||||
},
|
||||
ConnectionClosed {
|
||||
connection_id: ConnectionId,
|
||||
},
|
||||
IncomingMessage {
|
||||
connection_id: ConnectionId,
|
||||
message: JSONRPCMessage,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ConnectionOrigin {
|
||||
Stdio,
|
||||
InProcess,
|
||||
WebSocket,
|
||||
RemoteControl,
|
||||
}
|
||||
|
||||
static CONNECTION_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn next_connection_id() -> ConnectionId {
|
||||
ConnectionId(CONNECTION_ID_COUNTER.fetch_add(1, Ordering::Relaxed))
|
||||
}
|
||||
|
||||
async fn forward_incoming_message(
|
||||
transport_event_tx: &mpsc::Sender<TransportEvent>,
|
||||
writer: &mpsc::Sender<QueuedOutgoingMessage>,
|
||||
connection_id: ConnectionId,
|
||||
payload: &str,
|
||||
) -> bool {
|
||||
match serde_json::from_str::<JSONRPCMessage>(payload) {
|
||||
Ok(message) => {
|
||||
enqueue_incoming_message(transport_event_tx, writer, connection_id, message).await
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to deserialize JSONRPCMessage: {err}");
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn enqueue_incoming_message(
|
||||
transport_event_tx: &mpsc::Sender<TransportEvent>,
|
||||
writer: &mpsc::Sender<QueuedOutgoingMessage>,
|
||||
connection_id: ConnectionId,
|
||||
message: JSONRPCMessage,
|
||||
) -> bool {
|
||||
let event = TransportEvent::IncomingMessage {
|
||||
connection_id,
|
||||
message,
|
||||
};
|
||||
match transport_event_tx.try_send(event) {
|
||||
Ok(()) => true,
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => false,
|
||||
Err(mpsc::error::TrySendError::Full(TransportEvent::IncomingMessage {
|
||||
connection_id,
|
||||
message: JSONRPCMessage::Request(request),
|
||||
})) => {
|
||||
let overload_error = OutgoingMessage::Error(OutgoingError {
|
||||
id: request.id,
|
||||
error: JSONRPCErrorError {
|
||||
code: OVERLOADED_ERROR_CODE,
|
||||
message: "Server overloaded; retry later.".to_string(),
|
||||
data: None,
|
||||
},
|
||||
});
|
||||
match writer.try_send(QueuedOutgoingMessage::new(overload_error)) {
|
||||
Ok(()) => true,
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => false,
|
||||
Err(mpsc::error::TrySendError::Full(_overload_error)) => {
|
||||
warn!(
|
||||
"dropping overload response for connection {:?}: outbound queue is full",
|
||||
connection_id
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(mpsc::error::TrySendError::Full(event)) => transport_event_tx.send(event).await.is_ok(),
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_outgoing_message(outgoing_message: OutgoingMessage) -> Option<String> {
|
||||
match serde_json::to_string(&outgoing_message) {
|
||||
Ok(json) => Some(json),
|
||||
Err(err) => {
|
||||
error!("Failed to serialize JSONRPCMessage: {err}");
|
||||
let OutgoingMessage::Response(response) = outgoing_message else {
|
||||
return None;
|
||||
};
|
||||
serde_json::to_string(&response_serialization_error(response.id, err))
|
||||
.inspect_err(|err| error!("Failed to serialize JSONRPC error: {err}"))
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn response_serialization_error(
|
||||
request_id: RequestId,
|
||||
err: impl std::fmt::Display,
|
||||
) -> OutgoingMessage {
|
||||
OutgoingMessage::Error(OutgoingError {
|
||||
id: request_id,
|
||||
error: JSONRPCErrorError {
|
||||
code: INTERNAL_ERROR_CODE,
|
||||
message: format!("failed to serialize response: {err}"),
|
||||
data: None,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::outgoing_message::OutgoingResponse;
|
||||
use akode_app_server_protocol::ClientResponsePayload;
|
||||
use akode_app_server_protocol::ConfigWarningNotification;
|
||||
use akode_app_server_protocol::JSONRPCNotification;
|
||||
use akode_app_server_protocol::JSONRPCRequest;
|
||||
use akode_app_server_protocol::JSONRPCResponse;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::ServerNotificationEnvelope;
|
||||
use akode_app_server_protocol::ThreadArchiveResponse;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[test]
|
||||
fn listen_off_parses_as_off_transport() {
|
||||
assert_eq!(
|
||||
AppServerTransport::from_listen_url("off"),
|
||||
Ok(AppServerTransport::Off)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialize_outgoing_message_preserves_wire_shape() {
|
||||
let message = OutgoingMessage::AppServerNotification(ServerNotificationEnvelope {
|
||||
notification: ServerNotification::ConfigWarning(ConfigWarningNotification {
|
||||
summary: "summary".to_string(),
|
||||
details: None,
|
||||
path: None,
|
||||
range: None,
|
||||
}),
|
||||
emitted_at_ms: Some(1_234),
|
||||
});
|
||||
|
||||
let json = serialize_outgoing_message(message).expect("message should serialize");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&json).expect("message should be valid JSON"),
|
||||
json!({
|
||||
"method": "configWarning",
|
||||
"params": {
|
||||
"summary": "summary",
|
||||
"details": null,
|
||||
},
|
||||
"emittedAtMs": 1_234,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialize_typed_response_preserves_wire_shape() {
|
||||
let message = OutgoingMessage::Response(OutgoingResponse {
|
||||
id: RequestId::Integer(7),
|
||||
result: Box::new(ClientResponsePayload::ThreadArchive(
|
||||
ThreadArchiveResponse {},
|
||||
)),
|
||||
});
|
||||
|
||||
let json = serialize_outgoing_message(message).expect("message should serialize");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&json).expect("message should be valid JSON"),
|
||||
json!({ "id": 7, "result": {} })
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn serialize_invalid_typed_response_returns_jsonrpc_error() {
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
let codex_home =
|
||||
AbsolutePathBuf::from_absolute_path(PathBuf::from(OsString::from_vec(vec![
|
||||
b'/', b'b', b'a', b'd', 0xff,
|
||||
])))
|
||||
.expect("non-UTF-8 Unix paths are valid absolute paths");
|
||||
let message = OutgoingMessage::Response(OutgoingResponse {
|
||||
id: RequestId::Integer(7),
|
||||
result: Box::new(ClientResponsePayload::Initialize(
|
||||
akode_app_server_protocol::InitializeResponse {
|
||||
user_agent: "codex-test-agent".to_string(),
|
||||
codex_home,
|
||||
platform_family: "unix".to_string(),
|
||||
platform_os: "linux".to_string(),
|
||||
},
|
||||
)),
|
||||
});
|
||||
|
||||
let json = serialize_outgoing_message(message)
|
||||
.expect("invalid response should serialize as a JSON-RPC error");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&json).expect("message should be valid JSON"),
|
||||
json!({
|
||||
"id": 7,
|
||||
"error": {
|
||||
"code": -32603,
|
||||
"message": "failed to serialize response: path contains invalid UTF-8 characters",
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enqueue_incoming_request_returns_overload_error_when_queue_is_full() {
|
||||
let connection_id = ConnectionId(42);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(1);
|
||||
let (writer_tx, mut writer_rx) = mpsc::channel(1);
|
||||
|
||||
let first_message = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
});
|
||||
transport_event_tx
|
||||
.send(TransportEvent::IncomingMessage {
|
||||
connection_id,
|
||||
message: first_message.clone(),
|
||||
})
|
||||
.await
|
||||
.expect("queue should accept first message");
|
||||
|
||||
let request = JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: RequestId::Integer(7),
|
||||
method: "config/read".to_string(),
|
||||
params: Some(json!({ "includeLayers": false })),
|
||||
trace: None,
|
||||
});
|
||||
assert!(
|
||||
enqueue_incoming_message(&transport_event_tx, &writer_tx, connection_id, request).await
|
||||
);
|
||||
|
||||
let queued_event = transport_event_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("first event should stay queued");
|
||||
match queued_event {
|
||||
TransportEvent::IncomingMessage {
|
||||
connection_id: queued_connection_id,
|
||||
message,
|
||||
} => {
|
||||
assert_eq!(queued_connection_id, connection_id);
|
||||
assert_eq!(message, first_message);
|
||||
}
|
||||
_ => panic!("expected queued incoming message"),
|
||||
}
|
||||
|
||||
let overload = writer_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("request should receive overload error");
|
||||
let overload_json =
|
||||
serde_json::to_value(overload.message).expect("serialize overload error");
|
||||
assert_eq!(
|
||||
overload_json,
|
||||
json!({
|
||||
"id": 7,
|
||||
"error": {
|
||||
"code": OVERLOADED_ERROR_CODE,
|
||||
"message": "Server overloaded; retry later."
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enqueue_incoming_response_waits_instead_of_dropping_when_queue_is_full() {
|
||||
let connection_id = ConnectionId(42);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(1);
|
||||
let (writer_tx, _writer_rx) = mpsc::channel(1);
|
||||
|
||||
let first_message = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
});
|
||||
transport_event_tx
|
||||
.send(TransportEvent::IncomingMessage {
|
||||
connection_id,
|
||||
message: first_message.clone(),
|
||||
})
|
||||
.await
|
||||
.expect("queue should accept first message");
|
||||
|
||||
let response = JSONRPCMessage::Response(JSONRPCResponse {
|
||||
id: RequestId::Integer(7),
|
||||
result: json!({"ok": true}),
|
||||
});
|
||||
let transport_event_tx_for_enqueue = transport_event_tx.clone();
|
||||
let writer_tx_for_enqueue = writer_tx.clone();
|
||||
let enqueue_handle = tokio::spawn(async move {
|
||||
enqueue_incoming_message(
|
||||
&transport_event_tx_for_enqueue,
|
||||
&writer_tx_for_enqueue,
|
||||
connection_id,
|
||||
response,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
let queued_event = transport_event_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("first event should be dequeued");
|
||||
match queued_event {
|
||||
TransportEvent::IncomingMessage {
|
||||
connection_id: queued_connection_id,
|
||||
message,
|
||||
} => {
|
||||
assert_eq!(queued_connection_id, connection_id);
|
||||
assert_eq!(message, first_message);
|
||||
}
|
||||
_ => panic!("expected queued incoming message"),
|
||||
}
|
||||
|
||||
let enqueue_result = enqueue_handle.await.expect("enqueue task should not panic");
|
||||
assert!(enqueue_result);
|
||||
|
||||
let forwarded_event = transport_event_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("response should be forwarded instead of dropped");
|
||||
match forwarded_event {
|
||||
TransportEvent::IncomingMessage {
|
||||
connection_id: queued_connection_id,
|
||||
message: JSONRPCMessage::Response(JSONRPCResponse { id, result }),
|
||||
} => {
|
||||
assert_eq!(queued_connection_id, connection_id);
|
||||
assert_eq!(id, RequestId::Integer(7));
|
||||
assert_eq!(result, json!({"ok": true}));
|
||||
}
|
||||
_ => panic!("expected forwarded response message"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enqueue_incoming_request_does_not_block_when_writer_queue_is_full() {
|
||||
let connection_id = ConnectionId(42);
|
||||
let (transport_event_tx, _transport_event_rx) = mpsc::channel(1);
|
||||
let (writer_tx, mut writer_rx) = mpsc::channel(1);
|
||||
|
||||
transport_event_tx
|
||||
.send(TransportEvent::IncomingMessage {
|
||||
connection_id,
|
||||
message: JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
}),
|
||||
})
|
||||
.await
|
||||
.expect("transport queue should accept first message");
|
||||
|
||||
writer_tx
|
||||
.send(QueuedOutgoingMessage::new(
|
||||
OutgoingMessage::AppServerNotification(ServerNotificationEnvelope {
|
||||
notification: ServerNotification::ConfigWarning(ConfigWarningNotification {
|
||||
summary: "queued".to_string(),
|
||||
details: None,
|
||||
path: None,
|
||||
range: None,
|
||||
}),
|
||||
emitted_at_ms: Some(1_234),
|
||||
}),
|
||||
))
|
||||
.await
|
||||
.expect("writer queue should accept first message");
|
||||
|
||||
let request = JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: RequestId::Integer(7),
|
||||
method: "config/read".to_string(),
|
||||
params: Some(json!({ "includeLayers": false })),
|
||||
trace: None,
|
||||
});
|
||||
|
||||
let enqueue_result = timeout(
|
||||
Duration::from_millis(100),
|
||||
enqueue_incoming_message(&transport_event_tx, &writer_tx, connection_id, request),
|
||||
)
|
||||
.await
|
||||
.expect("enqueue should not block while writer queue is full");
|
||||
assert!(enqueue_result);
|
||||
|
||||
let queued_outgoing = writer_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("writer queue should still contain original message");
|
||||
let queued_json =
|
||||
serde_json::to_value(queued_outgoing.message).expect("serialize queued message");
|
||||
assert_eq!(
|
||||
queued_json,
|
||||
json!({
|
||||
"method": "configWarning",
|
||||
"params": {
|
||||
"summary": "queued",
|
||||
"details": null,
|
||||
},
|
||||
"emittedAtMs": 1_234,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
235
akode-rs/app-server-transport/src/transport/remote_control.rs
Normal file
235
akode-rs/app-server-transport/src/transport/remote_control.rs
Normal file
@@ -0,0 +1,235 @@
|
||||
//! aKode: remote control (the ChatGPT relay on chatgpt.com) was removed.
|
||||
//!
|
||||
//! This module keeps the process-facing API so the app server compiles unchanged, but it never
|
||||
//! opens a network connection: remote control always reports `Disabled`, enabling it fails, and
|
||||
//! pairing or client-management requests return an "unsupported" error.
|
||||
|
||||
use super::TransportEvent;
|
||||
use akode_app_server_protocol::RemoteControlClientsListParams;
|
||||
use akode_app_server_protocol::RemoteControlClientsListResponse;
|
||||
use akode_app_server_protocol::RemoteControlClientsRevokeParams;
|
||||
use akode_app_server_protocol::RemoteControlClientsRevokeResponse;
|
||||
use akode_app_server_protocol::RemoteControlConnectionStatus;
|
||||
use akode_app_server_protocol::RemoteControlPairingStartParams;
|
||||
use akode_app_server_protocol::RemoteControlPairingStartResponse;
|
||||
use akode_app_server_protocol::RemoteControlPairingStatusParams;
|
||||
use akode_app_server_protocol::RemoteControlPairingStatusResponse;
|
||||
use akode_app_server_protocol::RemoteControlStatusChangedNotification;
|
||||
use akode_login::AuthManager;
|
||||
use akode_state::StateRuntime;
|
||||
use gethostname::gethostname;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const REMOTE_CONTROL_REMOVED_MESSAGE: &str = "remote control is not available in this build";
|
||||
|
||||
pub struct RemoteControlStartConfig {
|
||||
pub remote_control_url: String,
|
||||
pub installation_id: String,
|
||||
pub policy: RemoteControlPolicy,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RemoteControlPolicy {
|
||||
#[default]
|
||||
Allowed,
|
||||
DisabledByRequirements,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RemoteControlStartupMode {
|
||||
ResolvePersisted,
|
||||
DisabledEphemeral,
|
||||
EnabledEphemeral,
|
||||
}
|
||||
|
||||
/// Internal marker used by the daemon to disable remote control without requiring a new CLI flag.
|
||||
pub const REMOTE_CONTROL_DISABLED_ENV_VAR: &str =
|
||||
"AKODE_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED";
|
||||
|
||||
/// Reads and removes the daemon's internal disabled-start marker before worker threads start.
|
||||
pub fn take_remote_control_disabled_env() -> bool {
|
||||
let disabled =
|
||||
std::env::var_os(REMOTE_CONTROL_DISABLED_ENV_VAR).is_some_and(|value| value == "1");
|
||||
// SAFETY: app-server calls this synchronously at process startup, before spawning threads.
|
||||
unsafe { std::env::remove_var(REMOTE_CONTROL_DISABLED_ENV_VAR) };
|
||||
disabled
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RemoteControlUnavailable;
|
||||
|
||||
impl fmt::Display for RemoteControlUnavailable {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(REMOTE_CONTROL_REMOVED_MESSAGE)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RemoteControlUnavailable {}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RemoteControlDisabledByRequirements;
|
||||
|
||||
impl fmt::Display for RemoteControlDisabledByRequirements {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "remote control is disabled by managed requirements")
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RemoteControlDisabledByRequirements {}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RemoteControlEnableError {
|
||||
Unavailable(RemoteControlUnavailable),
|
||||
DisabledByRequirements(RemoteControlDisabledByRequirements),
|
||||
AuthenticationChanged,
|
||||
}
|
||||
|
||||
impl fmt::Display for RemoteControlEnableError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Unavailable(err) => err.fmt(f),
|
||||
Self::DisabledByRequirements(err) => err.fmt(f),
|
||||
Self::AuthenticationChanged => f.write_str("remote control authentication changed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RemoteControlEnableError {}
|
||||
|
||||
/// Process-facing handle. Remote control is permanently disabled.
|
||||
#[derive(Clone)]
|
||||
pub struct RemoteControlHandle {
|
||||
policy: RemoteControlPolicy,
|
||||
status: Arc<watch::Sender<RemoteControlStatusChangedNotification>>,
|
||||
}
|
||||
|
||||
impl RemoteControlHandle {
|
||||
fn unsupported() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::Unsupported, RemoteControlUnavailable)
|
||||
}
|
||||
|
||||
pub fn ensure_remote_control_allowed(&self) -> Result<(), RemoteControlDisabledByRequirements> {
|
||||
match self.policy {
|
||||
RemoteControlPolicy::Allowed => Ok(()),
|
||||
RemoteControlPolicy::DisabledByRequirements => Err(RemoteControlDisabledByRequirements),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(&self) -> RemoteControlStatusChangedNotification {
|
||||
self.status.borrow().clone()
|
||||
}
|
||||
|
||||
pub fn status_receiver(&self) -> watch::Receiver<RemoteControlStatusChangedNotification> {
|
||||
self.status.subscribe()
|
||||
}
|
||||
|
||||
pub fn enable_ephemeral(
|
||||
&self,
|
||||
) -> Result<RemoteControlStatusChangedNotification, RemoteControlEnableError> {
|
||||
self.ensure_remote_control_allowed()
|
||||
.map_err(RemoteControlEnableError::DisabledByRequirements)?;
|
||||
Err(RemoteControlEnableError::Unavailable(
|
||||
RemoteControlUnavailable,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn disable_ephemeral(&self) -> RemoteControlStatusChangedNotification {
|
||||
self.status()
|
||||
}
|
||||
|
||||
pub async fn enable(
|
||||
&self,
|
||||
_app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||
self.ensure_remote_control_allowed()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::PermissionDenied, err))?;
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
|
||||
pub async fn disable(
|
||||
&self,
|
||||
_app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||
self.ensure_remote_control_allowed()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::PermissionDenied, err))?;
|
||||
Ok(self.status())
|
||||
}
|
||||
|
||||
pub async fn resolve_persisted_preference(
|
||||
&self,
|
||||
_app_server_client_name: Option<&str>,
|
||||
) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub async fn start_pairing(
|
||||
&self,
|
||||
_params: RemoteControlPairingStartParams,
|
||||
_app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlPairingStartResponse> {
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
|
||||
pub async fn pairing_status(
|
||||
&self,
|
||||
_params: RemoteControlPairingStatusParams,
|
||||
) -> io::Result<RemoteControlPairingStatusResponse> {
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
|
||||
pub async fn list_clients(
|
||||
&self,
|
||||
_params: RemoteControlClientsListParams,
|
||||
) -> io::Result<RemoteControlClientsListResponse> {
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
|
||||
pub async fn revoke_client(
|
||||
&self,
|
||||
_params: RemoteControlClientsRevokeParams,
|
||||
) -> io::Result<RemoteControlClientsRevokeResponse> {
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a handle that never connects. The task only keeps the client-name channel open
|
||||
/// until shutdown so local transports behave as before.
|
||||
pub async fn start_remote_control(
|
||||
config: RemoteControlStartConfig,
|
||||
_state_db: Option<Arc<StateRuntime>>,
|
||||
_auth_manager: Arc<AuthManager>,
|
||||
_transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: CancellationToken,
|
||||
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
||||
startup_mode: RemoteControlStartupMode,
|
||||
) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> {
|
||||
if startup_mode == RemoteControlStartupMode::EnabledEphemeral {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
RemoteControlUnavailable,
|
||||
));
|
||||
}
|
||||
let (status, _) = watch::channel(RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Disabled,
|
||||
server_name: gethostname().to_string_lossy().trim().to_string(),
|
||||
installation_id: config.installation_id,
|
||||
environment_id: None,
|
||||
});
|
||||
let handle = RemoteControlHandle {
|
||||
policy: config.policy,
|
||||
status: Arc::new(status),
|
||||
};
|
||||
let task = tokio::spawn(async move {
|
||||
let _client_name_rx = app_server_client_name_rx;
|
||||
shutdown_token.cancelled().await;
|
||||
});
|
||||
Ok((task, handle))
|
||||
}
|
||||
194
akode-rs/app-server-transport/src/transport/stdio.rs
Normal file
194
akode-rs/app-server-transport/src/transport/stdio.rs
Normal file
@@ -0,0 +1,194 @@
|
||||
//! Stdio transport with EOF cleanup and Unix SIGTERM shutdown. Dedicated I/O
|
||||
//! threads let SIGTERM abandon blocked pipes without holding the runtime open.
|
||||
//! A dedicated signal thread arms the shared EOF/SIGTERM deadline even when
|
||||
//! logging or the Tokio runtime is blocked.
|
||||
|
||||
use super::CHANNEL_CAPACITY;
|
||||
use super::ConnectionOrigin;
|
||||
use super::TransportEvent;
|
||||
use super::forward_incoming_message;
|
||||
use super::next_connection_id;
|
||||
use super::serialize_outgoing_message;
|
||||
use crate::outgoing_message::QueuedOutgoingMessage;
|
||||
use akode_app_server_protocol::InitializeParams;
|
||||
use akode_app_server_protocol::JSONRPCMessage;
|
||||
use akode_app_server_protocol::JSONRPCRequest;
|
||||
use std::io::BufRead;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Result as IoResult;
|
||||
use std::io::Write;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::debug;
|
||||
use tracing::error;
|
||||
use tracing::info;
|
||||
|
||||
pub async fn start_stdio_connection(
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
initialize_client_name_tx: oneshot::Sender<String>,
|
||||
install_shutdown_signal_handler: bool,
|
||||
) -> IoResult<JoinHandle<()>> {
|
||||
let shutdown_signal = CancellationToken::new();
|
||||
#[cfg(unix)]
|
||||
if install_shutdown_signal_handler {
|
||||
use signal_hook::consts::SIGTERM;
|
||||
use signal_hook::iterator::Signals;
|
||||
|
||||
// Register before accepting requests. Receiving SIGTERM and arming the
|
||||
// watchdog must not depend on Tokio or synchronous transport logging.
|
||||
let mut signals = Signals::new([SIGTERM])?;
|
||||
let shutdown_signal = shutdown_signal.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("app-server-signal".to_string())
|
||||
.spawn(move || {
|
||||
if signals.forever().next().is_some() {
|
||||
start_shutdown_watchdog();
|
||||
shutdown_signal.cancel();
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let connection_id = next_connection_id();
|
||||
let (writer_tx, mut writer_rx) = mpsc::channel::<QueuedOutgoingMessage>(CHANNEL_CAPACITY);
|
||||
let writer_tx_for_reader = writer_tx.clone();
|
||||
transport_event_tx
|
||||
.send(TransportEvent::ConnectionOpened {
|
||||
connection_id,
|
||||
origin: ConnectionOrigin::Stdio,
|
||||
auth: None,
|
||||
writer: writer_tx,
|
||||
disconnect_sender: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| std::io::Error::new(ErrorKind::BrokenPipe, "processor unavailable"))?;
|
||||
|
||||
// Tokio's stdin uses an uncancellable blocking task, which keeps its runtime
|
||||
// alive while the client leaves stdin open. This process-owned thread may
|
||||
// remain blocked until process exit, but is not joined by the runtime.
|
||||
let (stdin_tx, mut stdin_rx) = mpsc::channel(/*buffer*/ 1);
|
||||
std::thread::Builder::new()
|
||||
.name("app-server-stdin".to_string())
|
||||
.spawn(move || {
|
||||
for line in std::io::stdin().lock().lines() {
|
||||
if stdin_tx.blocking_send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
||||
// Keep stdout's blocking writes off Tokio's pool too. The forwarding future
|
||||
// owns writer_rx so cancelling it also releases producers stuck on a full queue.
|
||||
let (stdout_tx, mut stdout_rx) =
|
||||
mpsc::channel::<(String, oneshot::Sender<()>)>(/*buffer*/ 1);
|
||||
std::thread::Builder::new()
|
||||
.name("app-server-stdout".to_string())
|
||||
.spawn(move || {
|
||||
let mut stdout = std::io::stdout().lock();
|
||||
while let Some((json, written_tx)) = stdout_rx.blocking_recv() {
|
||||
if let Err(err) = stdout.write_all(json.as_bytes()) {
|
||||
error!("Failed to write to stdout: {err}");
|
||||
break;
|
||||
}
|
||||
let _ = written_tx.send(());
|
||||
}
|
||||
})?;
|
||||
|
||||
let transport_event_tx_for_reader = transport_event_tx.clone();
|
||||
let read_messages = async move {
|
||||
let mut initialize_client_name_tx = Some(initialize_client_name_tx);
|
||||
while let Some(line) = stdin_rx.recv().await {
|
||||
let line = match line {
|
||||
Ok(line) => line,
|
||||
Err(err) => {
|
||||
error!("Failed reading stdin: {err}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
if let Some(client_name) = stdio_initialize_client_name(&line)
|
||||
&& let Some(initialize_client_name_tx) = initialize_client_name_tx.take()
|
||||
{
|
||||
let _ = initialize_client_name_tx.send(client_name);
|
||||
}
|
||||
if !forward_incoming_message(
|
||||
&transport_event_tx_for_reader,
|
||||
&writer_tx_for_reader,
|
||||
connection_id,
|
||||
&line,
|
||||
)
|
||||
.await
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// EOF can finish the transport before RPC or runtime cleanup. Start
|
||||
// the same process deadline even if no SIGTERM arrives.
|
||||
if cfg!(unix) && install_shutdown_signal_handler {
|
||||
start_shutdown_watchdog();
|
||||
}
|
||||
let _ = transport_event_tx_for_reader
|
||||
.send(TransportEvent::ConnectionClosed { connection_id })
|
||||
.await;
|
||||
debug!("stdin reader finished (EOF)");
|
||||
};
|
||||
|
||||
let write_messages = async move {
|
||||
while let Some(queued_message) = writer_rx.recv().await {
|
||||
let Some(mut json) = serialize_outgoing_message(queued_message.message) else {
|
||||
continue;
|
||||
};
|
||||
json.push('\n');
|
||||
let (written_tx, written_rx) = oneshot::channel();
|
||||
if stdout_tx.send((json, written_tx)).await.is_err() || written_rx.await.is_err() {
|
||||
break;
|
||||
}
|
||||
if let Some(write_complete_tx) = queued_message.write_complete_tx {
|
||||
let _ = write_complete_tx.send(());
|
||||
}
|
||||
}
|
||||
info!("stdout writer exited (channel closed)");
|
||||
};
|
||||
|
||||
Ok(tokio::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = shutdown_signal.cancelled() => {
|
||||
// Cancelling both forwarding futures drops their queues before
|
||||
// connection teardown, including when EOF already began draining.
|
||||
info!("SIGTERM received; closing stdio connection (45s shutdown deadline)");
|
||||
let _ = transport_event_tx
|
||||
.send(TransportEvent::ConnectionClosed { connection_id })
|
||||
.await;
|
||||
}
|
||||
_ = async move { tokio::join!(read_messages, write_messages); } => {}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
fn start_shutdown_watchdog() {
|
||||
// EOF and SIGTERM can both start cleanup; keep the first process deadline.
|
||||
static STARTED: std::sync::Once = std::sync::Once::new();
|
||||
STARTED.call_once(|| {
|
||||
std::thread::Builder::new()
|
||||
.name("app-server-shutdown".to_string())
|
||||
.spawn(|| {
|
||||
// Allow the processor's 30s RPC drain, then bound even Tokio's
|
||||
// runtime teardown. Do not log here: stderr may also be blocked.
|
||||
std::thread::sleep(std::time::Duration::from_secs(45));
|
||||
std::process::exit(/*code*/ 1);
|
||||
})
|
||||
.unwrap_or_else(|_| std::process::exit(/*code*/ 1));
|
||||
});
|
||||
}
|
||||
|
||||
fn stdio_initialize_client_name(line: &str) -> Option<String> {
|
||||
let message = serde_json::from_str::<JSONRPCMessage>(line).ok()?;
|
||||
let JSONRPCMessage::Request(JSONRPCRequest { method, params, .. }) = message else {
|
||||
return None;
|
||||
};
|
||||
if method != "initialize" {
|
||||
return None;
|
||||
}
|
||||
let params = serde_json::from_value::<InitializeParams>(params?).ok()?;
|
||||
Some(params.client_info.name)
|
||||
}
|
||||
544
akode-rs/app-server-transport/src/transport/unix_socket.rs
Normal file
544
akode-rs/app-server-transport/src/transport/unix_socket.rs
Normal file
@@ -0,0 +1,544 @@
|
||||
//! Control socket startup, guarded rendezvous paths, and WebSocket acceptance.
|
||||
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Result as IoResult;
|
||||
use std::path::Path;
|
||||
|
||||
use super::TransportEvent;
|
||||
use crate::transport::websocket::run_websocket_connection;
|
||||
use crate::websocket_compression::WEBSOCKET_COMPRESSION_HEADER;
|
||||
use crate::websocket_compression::WebSocketCompression;
|
||||
use crate::websocket_compression::ZSTD_STREAM_PROTOCOL;
|
||||
use akode_uds::UnixListener;
|
||||
use akode_uds::UnixStream;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::Duration;
|
||||
use tokio_tungstenite::accept_hdr_async_with_config;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::handshake::server::Response as HandshakeResponse;
|
||||
use tokio_tungstenite::tungstenite::http::HeaderValue;
|
||||
use tokio_tungstenite::tungstenite::http::Response;
|
||||
use tokio_tungstenite::tungstenite::http::StatusCode;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::error;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
#[cfg(unix)]
|
||||
const CONTROL_SOCKET_MODE: u32 = 0o600;
|
||||
// Advertise the effective incoming cap for single-frame messages so clients can
|
||||
// reject oversized requests before the socket closes.
|
||||
const MAX_UNFRAGMENTED_MESSAGE_BYTES_HEADER: &str =
|
||||
"x-codex-websocket-max-unfragmented-message-bytes";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum DaemonShutdownAccess {
|
||||
Disabled,
|
||||
Managed,
|
||||
}
|
||||
|
||||
pub async fn start_control_socket_acceptor(
|
||||
socket_path: AbsolutePathBuf,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: CancellationToken,
|
||||
daemon_shutdown_access: DaemonShutdownAccess,
|
||||
compression: WebSocketCompression,
|
||||
) -> IoResult<JoinHandle<()>> {
|
||||
let (listener, socket_guard) = bind_private_daemon_socket(socket_path.as_path()).await?;
|
||||
info!(
|
||||
socket_path = %socket_guard.socket_path.display(),
|
||||
"app-server control socket listening"
|
||||
);
|
||||
|
||||
Ok(tokio::spawn(run_control_socket_acceptor(
|
||||
listener,
|
||||
transport_event_tx,
|
||||
shutdown_token,
|
||||
socket_guard,
|
||||
daemon_shutdown_access,
|
||||
compression,
|
||||
)))
|
||||
}
|
||||
|
||||
/// Binds a private daemon socket, retaining its advertised path as a rendezvous
|
||||
/// alias on Unix. Keep the guard alive for as long as the listener is in use.
|
||||
pub async fn bind_private_daemon_socket(
|
||||
socket_path: &Path,
|
||||
) -> IoResult<(UnixListener, DaemonSocketFileGuard)> {
|
||||
let socket_path = AbsolutePathBuf::from_absolute_path(socket_path)?;
|
||||
#[cfg(unix)]
|
||||
let (socket_path, rendezvous_path, mut startup_lock) = {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
if let Some(parent) = socket_path.as_path().parent() {
|
||||
// The advertised path is only an alias; preserve existing parents.
|
||||
match tokio::fs::DirBuilder::new()
|
||||
.mode(0o700)
|
||||
.create(parent)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == ErrorKind::AlreadyExists => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
let metadata = std::fs::metadata(parent)?;
|
||||
if !metadata.is_dir()
|
||||
|| (metadata.uid() != 0 && metadata.uid() != unsafe { libc::geteuid() })
|
||||
|| (metadata.mode() & 0o022 != 0 && metadata.mode() & 0o1000 == 0)
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::PermissionDenied,
|
||||
"socket parent must be owned by the user or root and prevent other users from replacing socket entries",
|
||||
));
|
||||
}
|
||||
}
|
||||
akode_uds::prepare_shared_daemon_socket_directory()?;
|
||||
let physical_path = protected_socket_path(socket_path.as_path())?;
|
||||
let lock = acquire_removable_app_server_startup_lock(
|
||||
AbsolutePathBuf::from_absolute_path_checked(physical_path.with_extension("lock"))?,
|
||||
)
|
||||
.await?;
|
||||
prepare_control_socket_path(socket_path.as_path()).await?;
|
||||
(
|
||||
AbsolutePathBuf::from_absolute_path_checked(physical_path)?,
|
||||
socket_path,
|
||||
lock,
|
||||
)
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let (socket_path, directory_guard) = {
|
||||
if let Some(parent) = socket_path.as_path().parent() {
|
||||
akode_uds::prepare_private_socket_directory(parent).await?;
|
||||
}
|
||||
let (path, guard) = akode_uds::validate_private_socket_path(socket_path.as_path())?;
|
||||
(AbsolutePathBuf::from_absolute_path_checked(path)?, guard)
|
||||
};
|
||||
prepare_control_socket_path(socket_path.as_path()).await?;
|
||||
let listener = UnixListener::bind(socket_path.as_path()).await?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
startup_lock.remove_on_drop = true;
|
||||
}
|
||||
let socket_guard = DaemonSocketFileGuard {
|
||||
socket_path,
|
||||
#[cfg(unix)]
|
||||
rendezvous_path,
|
||||
#[cfg(unix)]
|
||||
_startup_lock: startup_lock,
|
||||
#[cfg(windows)]
|
||||
_directory_guard: directory_guard,
|
||||
};
|
||||
set_control_socket_permissions(socket_guard.socket_path.as_path()).await?;
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(
|
||||
socket_guard.socket_path.as_path(),
|
||||
socket_guard.rendezvous_path.as_path(),
|
||||
)?;
|
||||
#[cfg(unix)]
|
||||
socket_guard._startup_lock._file.unlock()?;
|
||||
Ok((listener, socket_guard))
|
||||
}
|
||||
|
||||
async fn run_control_socket_acceptor(
|
||||
mut listener: UnixListener,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: CancellationToken,
|
||||
socket_guard: DaemonSocketFileGuard,
|
||||
daemon_shutdown_access: DaemonShutdownAccess,
|
||||
compression: WebSocketCompression,
|
||||
) {
|
||||
let _socket_guard = socket_guard;
|
||||
loop {
|
||||
let stream = tokio::select! {
|
||||
_ = shutdown_token.cancelled() => {
|
||||
break;
|
||||
}
|
||||
result = listener.accept() => {
|
||||
match result {
|
||||
Ok(stream) => stream,
|
||||
Err(err) => {
|
||||
if matches!(
|
||||
err.kind(),
|
||||
ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset | ErrorKind::Interrupted
|
||||
) {
|
||||
warn!("recoverable control socket accept error: {err}");
|
||||
continue;
|
||||
}
|
||||
error!("control socket accept error: {err}");
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let transport_event_tx = transport_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut shutdown_request = false;
|
||||
let mut negotiated_compression = WebSocketCompression::Plain;
|
||||
let websocket_config = WebSocketConfig::default();
|
||||
let max_unfragmented_message_bytes = [
|
||||
websocket_config.max_frame_size,
|
||||
websocket_config.max_message_size,
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.min();
|
||||
let websocket_stream = match accept_hdr_async_with_config(
|
||||
stream,
|
||||
|request: &tokio_tungstenite::tungstenite::handshake::server::Request,
|
||||
mut response: HandshakeResponse| {
|
||||
if request.uri().path() == "/daemon/shutdown" {
|
||||
if !matches!(daemon_shutdown_access, DaemonShutdownAccess::Managed) {
|
||||
let mut rejection = Response::new(Some("unmanaged server".to_string()));
|
||||
*rejection.status_mut() = StatusCode::FORBIDDEN;
|
||||
return Err(rejection);
|
||||
}
|
||||
shutdown_request = true;
|
||||
} else if compression == WebSocketCompression::Zstd
|
||||
&& request
|
||||
.headers()
|
||||
.get(WEBSOCKET_COMPRESSION_HEADER)
|
||||
.is_some_and(|value| value == ZSTD_STREAM_PROTOCOL)
|
||||
{
|
||||
negotiated_compression = WebSocketCompression::Zstd;
|
||||
response.headers_mut().insert(
|
||||
WEBSOCKET_COMPRESSION_HEADER,
|
||||
HeaderValue::from_static(ZSTD_STREAM_PROTOCOL),
|
||||
);
|
||||
}
|
||||
if let Some(max_bytes) = max_unfragmented_message_bytes {
|
||||
response.headers_mut().insert(
|
||||
MAX_UNFRAGMENTED_MESSAGE_BYTES_HEADER,
|
||||
HeaderValue::from(max_bytes),
|
||||
);
|
||||
}
|
||||
Ok(response)
|
||||
},
|
||||
Some(websocket_config),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(websocket_stream) => websocket_stream,
|
||||
Err(err) => {
|
||||
warn!("failed to upgrade control socket websocket connection: {err}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if shutdown_request {
|
||||
run_daemon_shutdown(websocket_stream, transport_event_tx).await;
|
||||
return;
|
||||
}
|
||||
let (websocket_writer, websocket_reader) = websocket_stream.split();
|
||||
run_websocket_connection(
|
||||
websocket_writer,
|
||||
websocket_reader,
|
||||
transport_event_tx,
|
||||
negotiated_compression,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
info!("control socket acceptor shutting down");
|
||||
}
|
||||
|
||||
async fn run_daemon_shutdown(
|
||||
mut websocket: tokio_tungstenite::WebSocketStream<UnixStream>,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
) {
|
||||
let pid = std::process::id().to_string();
|
||||
if !matches!(websocket.next().await, Some(Ok(Message::Text(request))) if request == pid) {
|
||||
return;
|
||||
}
|
||||
if websocket.send(Message::Text(pid.into())).await.is_err() {
|
||||
return;
|
||||
}
|
||||
// Let the manager receive the acknowledgment before the main loop closes connections.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(2), websocket.next()).await;
|
||||
let _ = transport_event_tx
|
||||
.send(TransportEvent::DaemonShutdown)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Unix callers hold the physical socket's startup lock through bind and publication.
|
||||
async fn prepare_control_socket_path(socket_path: &Path) -> IoResult<()> {
|
||||
#[cfg(windows)]
|
||||
let (socket_path, _directory_guard) = akode_uds::validate_private_socket_path(socket_path)?;
|
||||
#[cfg(windows)]
|
||||
let socket_path = AbsolutePathBuf::from_absolute_path_checked(socket_path)?;
|
||||
#[cfg(windows)]
|
||||
let socket_path = socket_path.as_path();
|
||||
|
||||
match UnixStream::connect(socket_path).await {
|
||||
Ok(_stream) => {
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::AddrInUse,
|
||||
format!(
|
||||
"app-server control socket is already in use at {}",
|
||||
socket_path.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {}
|
||||
Err(err) if err.kind() == ErrorKind::ConnectionRefused => {}
|
||||
Err(err) => {
|
||||
if !socket_path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
// A crashed daemon can leave a dangling rendezvous symlink. Only recognize
|
||||
// our own deterministic alias; never remove an arbitrary symlink target.
|
||||
#[cfg(unix)]
|
||||
if std::fs::read_link(socket_path).ok().as_deref()
|
||||
== Some(protected_socket_path(socket_path)?.as_path())
|
||||
{
|
||||
return tokio::fs::remove_file(socket_path).await;
|
||||
}
|
||||
|
||||
if !socket_path.try_exists()? {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !akode_uds::is_stale_socket_path(socket_path).await? {
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::AlreadyExists,
|
||||
format!(
|
||||
"app-server control socket path exists and is not a socket: {}",
|
||||
socket_path.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
tokio::fs::remove_file(socket_path).await
|
||||
}
|
||||
|
||||
/// Return a verified local socket endpoint, independent of the advertised Unix alias.
|
||||
/// A socket bound directly at the advertised path (e.g. SSH forwarding) is not ours on Unix.
|
||||
pub fn verified_local_daemon_socket(socket_path: &Path) -> IoResult<Option<AbsolutePathBuf>> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
let protected = protected_socket_path(socket_path)?;
|
||||
if std::fs::read_link(socket_path).ok().as_deref() != Some(protected.as_path()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let directory = std::fs::symlink_metadata(akode_uds::shared_daemon_socket_directory()?)?;
|
||||
// Match the daemon's bind-time check without creating or repairing the directory.
|
||||
if directory.is_dir()
|
||||
&& directory.uid() == unsafe { libc::geteuid() }
|
||||
&& directory.mode() & 0o777 == 0o700
|
||||
{
|
||||
return AbsolutePathBuf::from_absolute_path(protected).map(Some);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// The TUI revalidates this directory and verifies the peer at connection time,
|
||||
// using the same connect_local_daemon path as implicit startup.
|
||||
let (path, _directory) = akode_uds::validate_private_socket_path(socket_path)?;
|
||||
AbsolutePathBuf::from_absolute_path_checked(path).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn protected_socket_path(rendezvous_path: &Path) -> IoResult<std::path::PathBuf> {
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
let parent = rendezvous_path.parent().ok_or_else(|| {
|
||||
std::io::Error::new(ErrorKind::InvalidInput, "socket path must have a parent")
|
||||
})?;
|
||||
let name = rendezvous_path.file_name().ok_or_else(|| {
|
||||
std::io::Error::new(ErrorKind::InvalidInput, "socket path must have a filename")
|
||||
})?;
|
||||
let path = std::fs::canonicalize(parent)?.join(name);
|
||||
let hash = Sha256::digest(path.as_os_str().as_bytes());
|
||||
Ok(akode_uds::shared_daemon_socket_directory()?.join(format!("{hash:x}")))
|
||||
}
|
||||
|
||||
pub struct AppServerStartupLock {
|
||||
_file: std::fs::File,
|
||||
#[cfg(unix)]
|
||||
removable_path: Option<AbsolutePathBuf>,
|
||||
#[cfg(unix)]
|
||||
remove_on_drop: bool,
|
||||
}
|
||||
|
||||
pub async fn acquire_app_server_startup_lock(
|
||||
startup_lock_path: AbsolutePathBuf,
|
||||
) -> IoResult<AppServerStartupLock> {
|
||||
if let Some(parent) = startup_lock_path.as_path().parent() {
|
||||
akode_uds::prepare_private_socket_directory(parent).await?;
|
||||
}
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(startup_lock_path.as_path())?;
|
||||
file.lock()?;
|
||||
Ok(AppServerStartupLock {
|
||||
_file: file,
|
||||
#[cfg(unix)]
|
||||
removable_path: None,
|
||||
#[cfg(unix)]
|
||||
remove_on_drop: false,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|err| std::io::Error::other(format!("startup lock task failed: {err}")))?
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(super) async fn acquire_removable_app_server_startup_lock(
|
||||
startup_lock_path: AbsolutePathBuf,
|
||||
) -> IoResult<AppServerStartupLock> {
|
||||
let parent = startup_lock_path.as_path().parent().ok_or_else(|| {
|
||||
std::io::Error::new(ErrorKind::InvalidInput, "startup lock must have a parent")
|
||||
})?;
|
||||
akode_uds::prepare_private_socket_directory(parent).await?;
|
||||
loop {
|
||||
let startup_lock_path = startup_lock_path.clone();
|
||||
let attempt = tokio::task::spawn_blocking(move || {
|
||||
try_acquire_removable_app_server_startup_lock(startup_lock_path)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| std::io::Error::other(format!("startup lock task failed: {err}")))?;
|
||||
match attempt {
|
||||
Ok(lock) => return Ok(lock),
|
||||
Err(err) if err.kind() == ErrorKind::WouldBlock => {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl AppServerStartupLock {
|
||||
fn remove_file(&self) -> IoResult<()> {
|
||||
let Some(path) = self.removable_path.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
match self._file.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(()),
|
||||
Err(std::fs::TryLockError::Error(err)) => return Err(err),
|
||||
}
|
||||
startup_lock_file_matches_path(&self._file, path.as_path())?
|
||||
.then(|| std::fs::remove_file(path.as_path()))
|
||||
.transpose()
|
||||
.map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(super) fn try_acquire_removable_app_server_startup_lock(
|
||||
startup_lock_path: AbsolutePathBuf,
|
||||
) -> IoResult<AppServerStartupLock> {
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(startup_lock_path.as_path())?;
|
||||
file.try_lock()?;
|
||||
if !startup_lock_file_matches_path(&file, startup_lock_path.as_path())? {
|
||||
return Err(ErrorKind::WouldBlock.into());
|
||||
}
|
||||
Ok(AppServerStartupLock {
|
||||
_file: file,
|
||||
removable_path: Some(startup_lock_path),
|
||||
remove_on_drop: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for AppServerStartupLock {
|
||||
fn drop(&mut self) {
|
||||
if self.remove_on_drop
|
||||
&& let Err(err) = self.remove_file()
|
||||
{
|
||||
warn!(
|
||||
lock_path = ?self.removable_path,
|
||||
%err,
|
||||
"failed to remove app-server startup lock file"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn startup_lock_file_matches_path(file: &std::fs::File, path: &Path) -> IoResult<bool> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
let locked_metadata = file.metadata()?;
|
||||
match std::fs::metadata(path) {
|
||||
Ok(path_metadata) => Ok(locked_metadata.dev() == path_metadata.dev()
|
||||
&& locked_metadata.ino() == path_metadata.ino()),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(false),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn set_control_socket_permissions(socket_path: &Path) -> IoResult<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
tokio::fs::set_permissions(
|
||||
socket_path,
|
||||
std::fs::Permissions::from_mode(CONTROL_SOCKET_MODE),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
async fn set_control_socket_permissions(_socket_path: &Path) -> IoResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Owns the socket files and startup lock until the listener is shut down.
|
||||
pub struct DaemonSocketFileGuard {
|
||||
socket_path: AbsolutePathBuf,
|
||||
#[cfg(unix)]
|
||||
rendezvous_path: AbsolutePathBuf,
|
||||
#[cfg(unix)]
|
||||
_startup_lock: AppServerStartupLock,
|
||||
// Keep the directory pinned until after the socket file is removed in Drop.
|
||||
#[cfg(windows)]
|
||||
_directory_guard: std::os::windows::io::OwnedHandle,
|
||||
}
|
||||
|
||||
impl Drop for DaemonSocketFileGuard {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(unix)]
|
||||
if std::fs::read_link(self.rendezvous_path.as_path())
|
||||
.ok()
|
||||
.as_deref()
|
||||
== Some(self.socket_path.as_path())
|
||||
{
|
||||
let _ = std::fs::remove_file(self.rendezvous_path.as_path());
|
||||
}
|
||||
if let Err(err) = std::fs::remove_file(self.socket_path.as_path())
|
||||
&& err.kind() != ErrorKind::NotFound
|
||||
{
|
||||
warn!(
|
||||
socket_path = %self.socket_path.display(),
|
||||
%err,
|
||||
"failed to remove app-server control socket file"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
553
akode-rs/app-server-transport/src/transport/unix_socket_tests.rs
Normal file
553
akode-rs/app-server-transport/src/transport/unix_socket_tests.rs
Normal file
@@ -0,0 +1,553 @@
|
||||
use super::AppServerTransport;
|
||||
use super::CHANNEL_CAPACITY;
|
||||
use super::DaemonShutdownAccess;
|
||||
use super::TransportEvent;
|
||||
use super::acquire_app_server_startup_lock;
|
||||
use super::app_server_control_socket_path;
|
||||
use super::start_control_socket_acceptor;
|
||||
#[cfg(unix)]
|
||||
use super::unix_socket::acquire_removable_app_server_startup_lock;
|
||||
#[cfg(unix)]
|
||||
use super::unix_socket::try_acquire_removable_app_server_startup_lock;
|
||||
use crate::websocket_compression::WebSocketCompression;
|
||||
use akode_app_server_protocol::JSONRPCMessage;
|
||||
use akode_app_server_protocol::JSONRPCNotification;
|
||||
use akode_core::config::find_codex_home;
|
||||
use akode_uds::UnixStream;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::Result as IoResult;
|
||||
use std::path::Path;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
use tokio_tungstenite::client_async;
|
||||
use tokio_tungstenite::tungstenite::Bytes;
|
||||
use tokio_tungstenite::tungstenite::Message as WebSocketMessage;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[test]
|
||||
fn listen_unix_socket_parses_as_unix_socket_transport() {
|
||||
assert_eq!(
|
||||
AppServerTransport::from_listen_url("unix://"),
|
||||
Ok(AppServerTransport::UnixSocket {
|
||||
socket_path: default_control_socket_path()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listen_unix_socket_accepts_absolute_custom_path() {
|
||||
assert_eq!(
|
||||
AppServerTransport::from_listen_url("unix:///tmp/akode.sock"),
|
||||
Ok(AppServerTransport::UnixSocket {
|
||||
socket_path: absolute_path("/tmp/akode.sock")
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listen_unix_socket_accepts_relative_custom_path() {
|
||||
assert_eq!(
|
||||
AppServerTransport::from_listen_url("unix://akode.sock"),
|
||||
Ok(AppServerTransport::UnixSocket {
|
||||
socket_path: AbsolutePathBuf::relative_to_current_dir("akode.sock")
|
||||
.expect("relative path should resolve")
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn long_control_socket_paths_connect_to_distinct_daemons() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("temp dir");
|
||||
let long_parent = temp_dir.path().join("x".repeat(120));
|
||||
let mut sockets = Vec::new();
|
||||
let mut acceptors = Vec::new();
|
||||
|
||||
for name in ["first", "second"] {
|
||||
let codex_home = long_parent.join(name);
|
||||
std::fs::create_dir_all(&codex_home).expect("codex home");
|
||||
let socket_path = app_server_control_socket_path(&codex_home).expect("socket path");
|
||||
let (transport_event_tx, _transport_event_rx) =
|
||||
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let acceptor = start_control_socket_acceptor(
|
||||
socket_path.clone(),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
DaemonShutdownAccess::Disabled,
|
||||
WebSocketCompression::Plain,
|
||||
)
|
||||
.await
|
||||
.expect("control socket acceptor should start");
|
||||
sockets.push(socket_path);
|
||||
acceptors.push((shutdown_token, acceptor));
|
||||
}
|
||||
|
||||
assert_ne!(
|
||||
std::fs::read_link(sockets[0].as_path()).expect("first socket target"),
|
||||
std::fs::read_link(sockets[1].as_path()).expect("second socket target")
|
||||
);
|
||||
for socket in &sockets {
|
||||
connect_to_socket(socket.as_path())
|
||||
.await
|
||||
.expect("client should connect through long path");
|
||||
}
|
||||
for (shutdown_token, acceptor) in acceptors {
|
||||
shutdown_token.cancel();
|
||||
acceptor.await.expect("acceptor should stop");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn control_socket_acceptor_upgrades_and_forwards_websocket_text_messages_and_pings() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("temp dir");
|
||||
let socket_path = test_socket_path(temp_dir.path());
|
||||
let (transport_event_tx, mut transport_event_rx) =
|
||||
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let accept_handle = start_control_socket_acceptor(
|
||||
socket_path.clone(),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
DaemonShutdownAccess::Disabled,
|
||||
WebSocketCompression::Plain,
|
||||
)
|
||||
.await
|
||||
.expect("control socket acceptor should start");
|
||||
|
||||
let stream = connect_to_socket(socket_path.as_path())
|
||||
.await
|
||||
.expect("client should connect");
|
||||
let (mut websocket, response) = client_async("ws://localhost/rpc", stream)
|
||||
.await
|
||||
.expect("websocket upgrade should complete");
|
||||
assert_eq!(response.status().as_u16(), 101);
|
||||
let advertised_max = response
|
||||
.headers()
|
||||
.get("x-codex-websocket-max-unfragmented-message-bytes")
|
||||
.expect("byte cap header should be advertised")
|
||||
.to_str()
|
||||
.expect("byte cap header should be ASCII")
|
||||
.parse::<usize>()
|
||||
.expect("byte cap header should be a number");
|
||||
let websocket_config = WebSocketConfig::default();
|
||||
assert_eq!(
|
||||
advertised_max,
|
||||
[
|
||||
websocket_config.max_frame_size,
|
||||
websocket_config.max_message_size,
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.min()
|
||||
.expect("default websocket config should have an incoming size limit")
|
||||
);
|
||||
|
||||
let opened = timeout(Duration::from_secs(1), transport_event_rx.recv())
|
||||
.await
|
||||
.expect("connection opened event should arrive")
|
||||
.expect("connection opened event");
|
||||
let connection_id = match opened {
|
||||
TransportEvent::ConnectionOpened { connection_id, .. } => connection_id,
|
||||
_ => panic!("expected connection opened event"),
|
||||
};
|
||||
|
||||
let notification = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
});
|
||||
websocket
|
||||
.send(WebSocketMessage::Text(
|
||||
serde_json::to_string(¬ification)
|
||||
.expect("notification should serialize")
|
||||
.into(),
|
||||
))
|
||||
.await
|
||||
.expect("notification should send");
|
||||
|
||||
let incoming = timeout(Duration::from_secs(1), transport_event_rx.recv())
|
||||
.await
|
||||
.expect("incoming message event should arrive")
|
||||
.expect("incoming message event");
|
||||
assert_eq!(
|
||||
match incoming {
|
||||
TransportEvent::IncomingMessage {
|
||||
connection_id: incoming_connection_id,
|
||||
message,
|
||||
} => (incoming_connection_id, message),
|
||||
_ => panic!("expected incoming message event"),
|
||||
},
|
||||
(connection_id, notification)
|
||||
);
|
||||
|
||||
websocket
|
||||
.send(WebSocketMessage::Ping(Bytes::from_static(b"check")))
|
||||
.await
|
||||
.expect("ping should send");
|
||||
let pong = timeout(Duration::from_secs(1), websocket.next())
|
||||
.await
|
||||
.expect("pong should arrive")
|
||||
.expect("pong frame")
|
||||
.expect("pong should be valid");
|
||||
assert_eq!(pong, WebSocketMessage::Pong(Bytes::from_static(b"check")));
|
||||
|
||||
websocket.close(None).await.expect("close should send");
|
||||
let closed = timeout(Duration::from_secs(1), transport_event_rx.recv())
|
||||
.await
|
||||
.expect("connection closed event should arrive")
|
||||
.expect("connection closed event");
|
||||
assert!(matches!(
|
||||
closed,
|
||||
TransportEvent::ConnectionClosed {
|
||||
connection_id: closed_connection_id,
|
||||
} if closed_connection_id == connection_id
|
||||
));
|
||||
|
||||
shutdown_token.cancel();
|
||||
accept_handle.await.expect("acceptor should join");
|
||||
assert_socket_path_removed(socket_path.as_path());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_is_only_accepted_on_managed_local_socket_for_its_own_pid() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("temp dir");
|
||||
let socket_path = test_socket_path(temp_dir.path());
|
||||
let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown = CancellationToken::new();
|
||||
let acceptor = start_control_socket_acceptor(
|
||||
socket_path.clone(),
|
||||
tx,
|
||||
shutdown.clone(),
|
||||
DaemonShutdownAccess::Disabled,
|
||||
WebSocketCompression::Plain,
|
||||
)
|
||||
.await
|
||||
.expect("acceptor");
|
||||
|
||||
let stream = connect_to_socket(socket_path.as_path())
|
||||
.await
|
||||
.expect("connect");
|
||||
assert!(
|
||||
client_async("ws://localhost/daemon/shutdown", stream)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(rx.try_recv().is_err());
|
||||
shutdown.cancel();
|
||||
acceptor.await.expect("acceptor shutdown");
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown = CancellationToken::new();
|
||||
let acceptor = start_control_socket_acceptor(
|
||||
socket_path.clone(),
|
||||
tx,
|
||||
shutdown.clone(),
|
||||
DaemonShutdownAccess::Managed,
|
||||
WebSocketCompression::Plain,
|
||||
)
|
||||
.await
|
||||
.expect("managed acceptor");
|
||||
let stream = connect_to_socket(socket_path.as_path())
|
||||
.await
|
||||
.expect("connect");
|
||||
let (mut websocket, _) = client_async("ws://localhost/daemon/shutdown", stream)
|
||||
.await
|
||||
.expect("upgrade");
|
||||
websocket
|
||||
.send(WebSocketMessage::Text("0".into()))
|
||||
.await
|
||||
.expect("wrong pid");
|
||||
assert!(!matches!(
|
||||
websocket.next().await,
|
||||
Some(Ok(WebSocketMessage::Text(_)))
|
||||
));
|
||||
assert!(rx.try_recv().is_err());
|
||||
|
||||
let stream = connect_to_socket(socket_path.as_path())
|
||||
.await
|
||||
.expect("connect");
|
||||
let (mut websocket, _) = client_async("ws://localhost/daemon/shutdown", stream)
|
||||
.await
|
||||
.expect("upgrade");
|
||||
let pid = std::process::id().to_string();
|
||||
websocket
|
||||
.send(WebSocketMessage::Text(pid.clone().into()))
|
||||
.await
|
||||
.expect("request");
|
||||
assert_eq!(
|
||||
websocket.next().await.expect("ack").expect("ack frame"),
|
||||
WebSocketMessage::Text(pid.into())
|
||||
);
|
||||
assert!(
|
||||
rx.try_recv().is_err(),
|
||||
"server must wait until the ack is received"
|
||||
);
|
||||
websocket.close(None).await.expect("confirm receipt");
|
||||
assert!(matches!(
|
||||
timeout(Duration::from_secs(2), rx.recv()).await,
|
||||
Ok(Some(TransportEvent::DaemonShutdown))
|
||||
));
|
||||
shutdown.cancel();
|
||||
acceptor.await.expect("acceptor shutdown");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_server_startup_lock_serializes_waiters() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("temp dir");
|
||||
let lock_path = test_startup_lock_path(temp_dir.path());
|
||||
let first_lock = acquire_app_server_startup_lock(lock_path.clone())
|
||||
.await
|
||||
.expect("first startup lock should succeed");
|
||||
let mut second_lock = tokio::spawn(acquire_app_server_startup_lock(lock_path));
|
||||
|
||||
assert!(
|
||||
timeout(Duration::from_millis(100), &mut second_lock)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
drop(first_lock);
|
||||
second_lock
|
||||
.await
|
||||
.expect("second startup lock task should join")
|
||||
.expect("second startup lock should succeed");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn removable_startup_lock_attempt_is_nonblocking() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("temp dir");
|
||||
let lock_path = AbsolutePathBuf::from_absolute_path(temp_dir.path().join("socket.lock"))
|
||||
.expect("lock path should resolve");
|
||||
let _lock = try_acquire_removable_app_server_startup_lock(lock_path.clone())
|
||||
.expect("first lock should succeed");
|
||||
let error = timeout(
|
||||
Duration::from_secs(1),
|
||||
tokio::task::spawn_blocking(move || {
|
||||
try_acquire_removable_app_server_startup_lock(lock_path)
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::WouldBlock);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn removable_startup_lock_rejects_a_dangling_symlink_collision() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("temp dir");
|
||||
let lock_path = AbsolutePathBuf::from_absolute_path(temp_dir.path().join("socket.lock"))
|
||||
.expect("lock path should resolve");
|
||||
std::os::unix::fs::symlink(temp_dir.path().join("missing/target"), lock_path.as_path())
|
||||
.expect("dangling symlink should be created");
|
||||
|
||||
let error = acquire_removable_app_server_startup_lock(lock_path)
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn control_socket_rejects_writable_parent_without_changing_permissions() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o777)).unwrap();
|
||||
let path = AbsolutePathBuf::from_absolute_path(directory.path().join("rpc.sock")).unwrap();
|
||||
let (tx, _rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let error = start_control_socket_acceptor(
|
||||
path.clone(),
|
||||
tx,
|
||||
CancellationToken::new(),
|
||||
DaemonShutdownAccess::Disabled,
|
||||
WebSocketCompression::Plain,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
|
||||
assert_eq!(
|
||||
std::fs::metadata(directory.path())
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode()
|
||||
& 0o777,
|
||||
0o777
|
||||
);
|
||||
assert!(std::fs::symlink_metadata(path).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn control_socket_file_is_private_after_bind() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let temp_dir = tempfile::TempDir::new().expect("temp dir");
|
||||
let socket_path = test_socket_path(temp_dir.path());
|
||||
let parent = socket_path.as_path().parent().unwrap();
|
||||
std::fs::create_dir_all(parent).unwrap();
|
||||
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let (transport_event_tx, _transport_event_rx) =
|
||||
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let accept_handle = start_control_socket_acceptor(
|
||||
socket_path.clone(),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
DaemonShutdownAccess::Disabled,
|
||||
WebSocketCompression::Plain,
|
||||
)
|
||||
.await
|
||||
.expect("control socket acceptor should start");
|
||||
|
||||
let metadata = tokio::fs::metadata(socket_path.as_path())
|
||||
.await
|
||||
.expect("socket metadata should exist");
|
||||
assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
|
||||
assert_eq!(
|
||||
std::fs::metadata(parent).unwrap().permissions().mode() & 0o777,
|
||||
0o755
|
||||
);
|
||||
let physical_path = std::fs::read_link(socket_path.as_path()).expect("rendezvous symlink");
|
||||
assert_eq!(
|
||||
super::verified_local_daemon_socket(socket_path.as_path()).unwrap(),
|
||||
Some(AbsolutePathBuf::from_absolute_path(physical_path.clone()).unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
physical_path.parent(),
|
||||
Some(
|
||||
akode_uds::shared_daemon_socket_directory()
|
||||
.unwrap()
|
||||
.as_path()
|
||||
)
|
||||
);
|
||||
assert!(physical_path.with_extension("lock").exists());
|
||||
|
||||
shutdown_token.cancel();
|
||||
accept_handle.await.expect("acceptor should join");
|
||||
assert!(!physical_path.exists());
|
||||
assert!(!physical_path.with_extension("lock").exists());
|
||||
assert!(std::fs::symlink_metadata(socket_path.as_path()).is_err());
|
||||
|
||||
// SSH/socat may bind directly at the same advertised path.
|
||||
let forwarded = tokio::net::UnixListener::bind(socket_path.as_path()).unwrap();
|
||||
assert_eq!(
|
||||
super::verified_local_daemon_socket(socket_path.as_path()).unwrap(),
|
||||
None
|
||||
);
|
||||
drop(forwarded);
|
||||
std::fs::remove_file(socket_path.as_path()).unwrap();
|
||||
|
||||
// Simulate a dangling rendezvous left by an interrupted cleanup.
|
||||
std::os::unix::fs::symlink(&physical_path, socket_path.as_path()).unwrap();
|
||||
let (sender, _receiver) = mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let shutdown = CancellationToken::new();
|
||||
let (first, second) = tokio::join!(
|
||||
start_control_socket_acceptor(
|
||||
socket_path.clone(),
|
||||
sender.clone(),
|
||||
shutdown.clone(),
|
||||
DaemonShutdownAccess::Disabled,
|
||||
WebSocketCompression::Plain,
|
||||
),
|
||||
start_control_socket_acceptor(
|
||||
socket_path.clone(),
|
||||
sender,
|
||||
shutdown.clone(),
|
||||
DaemonShutdownAccess::Disabled,
|
||||
WebSocketCompression::Plain,
|
||||
),
|
||||
);
|
||||
let (acceptor, error) = match (first, second) {
|
||||
(Ok(acceptor), Err(error)) | (Err(error), Ok(acceptor)) => (acceptor, error),
|
||||
_ => panic!("exactly one concurrent restart should replace the stale symlink"),
|
||||
};
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::AddrInUse);
|
||||
let _client = connect_to_socket(socket_path.as_path()).await.unwrap();
|
||||
|
||||
// Cleanup must not remove a replacement at the advertised path.
|
||||
std::fs::remove_file(socket_path.as_path()).unwrap();
|
||||
std::fs::write(socket_path.as_path(), b"replacement").unwrap();
|
||||
shutdown.cancel();
|
||||
acceptor.await.unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read(socket_path.as_path()).unwrap(),
|
||||
b"replacement"
|
||||
);
|
||||
assert!(!physical_path.exists());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn control_socket_pins_directory_until_shutdown() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("temp dir");
|
||||
let socket_path = test_socket_path(temp_dir.path());
|
||||
let directory = socket_path.as_path().parent().unwrap();
|
||||
let moved = temp_dir.path().join("moved");
|
||||
let (tx, _rx) = mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let shutdown = CancellationToken::new();
|
||||
let acceptor = start_control_socket_acceptor(
|
||||
socket_path.clone(),
|
||||
tx,
|
||||
shutdown.clone(),
|
||||
DaemonShutdownAccess::Disabled,
|
||||
WebSocketCompression::Plain,
|
||||
)
|
||||
.await
|
||||
.expect("acceptor");
|
||||
assert!(std::fs::rename(directory, &moved).is_err());
|
||||
shutdown.cancel();
|
||||
acceptor.await.expect("shutdown");
|
||||
std::fs::rename(directory, moved).expect("directory unpinned after cleanup");
|
||||
}
|
||||
|
||||
fn absolute_path(path: &str) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path(path).expect("absolute path")
|
||||
}
|
||||
|
||||
fn default_control_socket_path() -> AbsolutePathBuf {
|
||||
let codex_home = find_codex_home().expect("codex home");
|
||||
app_server_control_socket_path(&codex_home).expect("default control socket path")
|
||||
}
|
||||
|
||||
fn test_socket_path(temp_dir: &Path) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path(
|
||||
temp_dir
|
||||
.join("app-server-control")
|
||||
.join("app-server-control.sock"),
|
||||
)
|
||||
.expect("socket path should resolve")
|
||||
}
|
||||
|
||||
fn test_startup_lock_path(temp_dir: &Path) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path(
|
||||
temp_dir
|
||||
.join("app-server-control")
|
||||
.join("app-server-startup.lock"),
|
||||
)
|
||||
.expect("startup lock path should resolve")
|
||||
}
|
||||
|
||||
async fn connect_to_socket(socket_path: &Path) -> IoResult<UnixStream> {
|
||||
UnixStream::connect(socket_path).await
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn assert_socket_path_removed(socket_path: &Path) {
|
||||
assert!(!socket_path.exists());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn assert_socket_path_removed(_socket_path: &Path) {
|
||||
// uds_windows uses a regular filesystem path as its rendezvous point,
|
||||
// but there is no Unix socket filesystem node to assert on.
|
||||
}
|
||||
482
akode-rs/app-server-transport/src/transport/websocket.rs
Normal file
482
akode-rs/app-server-transport/src/transport/websocket.rs
Normal file
@@ -0,0 +1,482 @@
|
||||
use super::CHANNEL_CAPACITY;
|
||||
use super::ConnectionOrigin;
|
||||
use super::TransportEvent;
|
||||
use super::forward_incoming_message;
|
||||
use super::next_connection_id;
|
||||
use super::serialize_outgoing_message;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::QueuedOutgoingMessage;
|
||||
use crate::websocket_compression::WEBSOCKET_COMPRESSION_HEADER;
|
||||
use crate::websocket_compression::WebSocketCompression;
|
||||
use crate::websocket_compression::ZSTD_STREAM_PROTOCOL;
|
||||
use crate::websocket_compression::ZstdDecoder;
|
||||
use crate::websocket_compression::ZstdEncoder;
|
||||
use crate::websocket_compression::zstd_codec_pair;
|
||||
use axum::Router;
|
||||
use axum::body::Body;
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::ConnectInfo;
|
||||
use axum::extract::State;
|
||||
use axum::extract::ws::Message as AxumWebSocketMessage;
|
||||
use axum::extract::ws::WebSocketUpgrade;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::HeaderValue;
|
||||
use axum::http::Request;
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::header::ORIGIN;
|
||||
use axum::middleware;
|
||||
use axum::middleware::Next;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::response::Response;
|
||||
use axum::routing::any;
|
||||
use axum::routing::get;
|
||||
use akode_websocket_auth::WebsocketAuthPolicy;
|
||||
use akode_websocket_auth::authorize_upgrade;
|
||||
use akode_websocket_auth::is_unauthenticated_non_loopback_listener;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use owo_colors::OwoColorize;
|
||||
use owo_colors::Stream;
|
||||
use owo_colors::Style;
|
||||
use std::io::Result as IoResult;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_tungstenite::tungstenite::Message as TungsteniteWebSocketMessage;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::error;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
/// WebSocket clients can briefly lag behind normal turn output bursts while the
|
||||
/// writer task is healthy, so give them more headroom than internal channels.
|
||||
const WEBSOCKET_OUTBOUND_CHANNEL_CAPACITY: usize = 32 * 1024;
|
||||
const _: () = assert!(WEBSOCKET_OUTBOUND_CHANNEL_CAPACITY > CHANNEL_CAPACITY);
|
||||
// Match the existing Axum and Tungstenite default WebSocket message limit.
|
||||
pub(super) const MAX_DECOMPRESSED_MESSAGE_SIZE: usize = 64 << 20;
|
||||
|
||||
fn colorize(text: &str, style: Style) -> String {
|
||||
text.if_supports_color(Stream::Stderr, |value| value.style(style))
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[allow(clippy::print_stderr)]
|
||||
fn print_websocket_startup_banner(addr: SocketAddr) {
|
||||
let title = colorize("codex app-server (WebSockets)", Style::new().bold().cyan());
|
||||
let listening_label = colorize("listening on:", Style::new().dimmed());
|
||||
let listen_url = colorize(&format!("ws://{addr}"), Style::new().green());
|
||||
let ready_label = colorize("readyz:", Style::new().dimmed());
|
||||
let ready_url = colorize(&format!("http://{addr}/readyz"), Style::new().green());
|
||||
let health_label = colorize("healthz:", Style::new().dimmed());
|
||||
let health_url = colorize(&format!("http://{addr}/healthz"), Style::new().green());
|
||||
let note_label = colorize("note:", Style::new().dimmed());
|
||||
eprintln!("{title}");
|
||||
eprintln!(" {listening_label} {listen_url}");
|
||||
eprintln!(" {ready_label} {ready_url}");
|
||||
eprintln!(" {health_label} {health_url}");
|
||||
if addr.ip().is_loopback() {
|
||||
eprintln!(
|
||||
" {note_label} binds localhost only (use SSH port-forwarding for remote access)"
|
||||
);
|
||||
} else {
|
||||
eprintln!(" {note_label} websocket auth is required for non-localhost listeners");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct WebSocketListenerState {
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
auth_policy: Arc<WebsocketAuthPolicy>,
|
||||
compression: WebSocketCompression,
|
||||
}
|
||||
|
||||
async fn health_check_handler() -> StatusCode {
|
||||
StatusCode::OK
|
||||
}
|
||||
|
||||
async fn reject_requests_with_origin_header(
|
||||
request: Request<Body>,
|
||||
next: Next,
|
||||
) -> Result<Response, StatusCode> {
|
||||
if request.headers().contains_key(ORIGIN) {
|
||||
warn!(
|
||||
method = %request.method(),
|
||||
uri = %request.uri(),
|
||||
"rejecting websocket listener request with Origin header"
|
||||
);
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
} else {
|
||||
Ok(next.run(request).await)
|
||||
}
|
||||
}
|
||||
|
||||
async fn websocket_upgrade_handler(
|
||||
websocket: WebSocketUpgrade,
|
||||
ConnectInfo(peer_addr): ConnectInfo<SocketAddr>,
|
||||
State(state): State<WebSocketListenerState>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(err) = authorize_upgrade(&headers, state.auth_policy.as_ref()) {
|
||||
warn!(
|
||||
%peer_addr,
|
||||
message = err.message(),
|
||||
"rejecting websocket client during upgrade"
|
||||
);
|
||||
return (err.status_code(), err.message()).into_response();
|
||||
}
|
||||
info!(%peer_addr, "websocket client connected");
|
||||
let compression = if state.compression == WebSocketCompression::Zstd
|
||||
&& headers
|
||||
.get(WEBSOCKET_COMPRESSION_HEADER)
|
||||
.is_some_and(|value| value == ZSTD_STREAM_PROTOCOL)
|
||||
{
|
||||
WebSocketCompression::Zstd
|
||||
} else {
|
||||
WebSocketCompression::Plain
|
||||
};
|
||||
let mut response = websocket
|
||||
.on_upgrade(move |stream| async move {
|
||||
let (websocket_writer, websocket_reader) = stream.split();
|
||||
run_websocket_connection(
|
||||
websocket_writer,
|
||||
websocket_reader,
|
||||
state.transport_event_tx,
|
||||
compression,
|
||||
)
|
||||
.await;
|
||||
})
|
||||
.into_response();
|
||||
if compression == WebSocketCompression::Zstd {
|
||||
response.headers_mut().insert(
|
||||
WEBSOCKET_COMPRESSION_HEADER,
|
||||
HeaderValue::from_static(ZSTD_STREAM_PROTOCOL),
|
||||
);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub async fn start_websocket_acceptor(
|
||||
bind_address: SocketAddr,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: CancellationToken,
|
||||
auth_policy: WebsocketAuthPolicy,
|
||||
compression: WebSocketCompression,
|
||||
) -> IoResult<JoinHandle<()>> {
|
||||
if is_unauthenticated_non_loopback_listener(bind_address, &auth_policy) {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"refusing to start non-loopback websocket listener {bind_address} without auth; configure `--ws-auth capability-token` or `--ws-auth signed-bearer-token`"
|
||||
),
|
||||
));
|
||||
}
|
||||
let listener = TcpListener::bind(bind_address).await?;
|
||||
let local_addr = listener.local_addr()?;
|
||||
print_websocket_startup_banner(local_addr);
|
||||
info!("app-server websocket listening on ws://{local_addr}");
|
||||
|
||||
let router = Router::new()
|
||||
.route("/readyz", get(health_check_handler))
|
||||
.route("/healthz", get(health_check_handler))
|
||||
.fallback(any(websocket_upgrade_handler))
|
||||
.layer(middleware::from_fn(reject_requests_with_origin_header))
|
||||
.with_state(WebSocketListenerState {
|
||||
transport_event_tx,
|
||||
auth_policy: Arc::new(auth_policy),
|
||||
compression,
|
||||
});
|
||||
let server = axum::serve(
|
||||
listener,
|
||||
router.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.with_graceful_shutdown(async move {
|
||||
shutdown_token.cancelled().await;
|
||||
});
|
||||
Ok(tokio::spawn(async move {
|
||||
if let Err(err) = server.await {
|
||||
error!("websocket acceptor failed: {err}");
|
||||
}
|
||||
info!("websocket acceptor shutting down");
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) async fn run_websocket_connection<M, SinkError, StreamError>(
|
||||
websocket_writer: impl futures::sink::Sink<M, Error = SinkError> + Send + 'static,
|
||||
websocket_reader: impl futures::stream::Stream<Item = Result<M, StreamError>> + Send + 'static,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
compression: WebSocketCompression,
|
||||
) where
|
||||
M: AppServerWebSocketMessage + Send + 'static,
|
||||
SinkError: Send + 'static,
|
||||
StreamError: std::fmt::Display + Send + 'static,
|
||||
{
|
||||
let connection_id = next_connection_id();
|
||||
let (encoder, decoder) = match compression {
|
||||
WebSocketCompression::Plain => (None, None),
|
||||
WebSocketCompression::Zstd => {
|
||||
match zstd_codec_pair(
|
||||
MAX_DECOMPRESSED_MESSAGE_SIZE,
|
||||
crate::CompressionConnection::Listener(connection_id),
|
||||
) {
|
||||
Ok((encoder, decoder)) => (Some(encoder), Some(decoder)),
|
||||
Err(_) => {
|
||||
warn!("failed to initialize websocket compression");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let (writer_tx, writer_rx) =
|
||||
mpsc::channel::<QueuedOutgoingMessage>(WEBSOCKET_OUTBOUND_CHANNEL_CAPACITY);
|
||||
let writer_tx_for_reader = writer_tx.clone();
|
||||
let disconnect_token = CancellationToken::new();
|
||||
if transport_event_tx
|
||||
.send(TransportEvent::ConnectionOpened {
|
||||
connection_id,
|
||||
origin: ConnectionOrigin::WebSocket,
|
||||
auth: None,
|
||||
writer: writer_tx,
|
||||
disconnect_sender: Some(disconnect_token.clone()),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let (writer_control_tx, writer_control_rx) = mpsc::channel::<M>(CHANNEL_CAPACITY);
|
||||
let mut outbound_task = tokio::spawn(run_websocket_outbound_loop(
|
||||
websocket_writer,
|
||||
writer_rx,
|
||||
writer_control_rx,
|
||||
disconnect_token.clone(),
|
||||
encoder,
|
||||
));
|
||||
let mut inbound_task = tokio::spawn(run_websocket_inbound_loop(
|
||||
websocket_reader,
|
||||
transport_event_tx.clone(),
|
||||
writer_tx_for_reader,
|
||||
writer_control_tx,
|
||||
connection_id,
|
||||
disconnect_token.clone(),
|
||||
decoder,
|
||||
));
|
||||
|
||||
tokio::select! {
|
||||
_ = &mut outbound_task => {
|
||||
disconnect_token.cancel();
|
||||
inbound_task.abort();
|
||||
}
|
||||
_ = &mut inbound_task => {
|
||||
disconnect_token.cancel();
|
||||
outbound_task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
let _ = transport_event_tx
|
||||
.send(TransportEvent::ConnectionClosed { connection_id })
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(crate) enum IncomingWebSocketMessage {
|
||||
Text(String),
|
||||
Binary(Bytes),
|
||||
Ping(Bytes),
|
||||
Pong,
|
||||
Close,
|
||||
}
|
||||
|
||||
/// Converts concrete WebSocket message types into the small message surface the
|
||||
/// app-server transport needs, and constructs the only outbound frames it
|
||||
/// sends directly.
|
||||
pub(crate) trait AppServerWebSocketMessage: Sized {
|
||||
fn text(text: String) -> Self;
|
||||
fn binary(payload: Bytes) -> Self;
|
||||
fn pong(payload: Bytes) -> Self;
|
||||
fn into_incoming(self) -> Option<IncomingWebSocketMessage>;
|
||||
}
|
||||
|
||||
impl AppServerWebSocketMessage for AxumWebSocketMessage {
|
||||
fn text(text: String) -> Self {
|
||||
Self::Text(text.into())
|
||||
}
|
||||
|
||||
fn binary(payload: Bytes) -> Self {
|
||||
Self::Binary(payload)
|
||||
}
|
||||
|
||||
fn pong(payload: Bytes) -> Self {
|
||||
Self::Pong(payload)
|
||||
}
|
||||
|
||||
fn into_incoming(self) -> Option<IncomingWebSocketMessage> {
|
||||
Some(match self {
|
||||
Self::Text(text) => IncomingWebSocketMessage::Text(text.to_string()),
|
||||
Self::Binary(payload) => IncomingWebSocketMessage::Binary(payload),
|
||||
Self::Ping(payload) => IncomingWebSocketMessage::Ping(payload),
|
||||
Self::Pong(_) => IncomingWebSocketMessage::Pong,
|
||||
Self::Close(_) => IncomingWebSocketMessage::Close,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AppServerWebSocketMessage for TungsteniteWebSocketMessage {
|
||||
fn text(text: String) -> Self {
|
||||
Self::Text(text.into())
|
||||
}
|
||||
|
||||
fn binary(payload: Bytes) -> Self {
|
||||
Self::Binary(payload)
|
||||
}
|
||||
|
||||
fn pong(payload: Bytes) -> Self {
|
||||
Self::Pong(payload)
|
||||
}
|
||||
|
||||
fn into_incoming(self) -> Option<IncomingWebSocketMessage> {
|
||||
Some(match self {
|
||||
Self::Text(text) => IncomingWebSocketMessage::Text(text.to_string()),
|
||||
Self::Binary(payload) => IncomingWebSocketMessage::Binary(payload),
|
||||
Self::Ping(payload) => IncomingWebSocketMessage::Ping(payload),
|
||||
Self::Pong(_) => IncomingWebSocketMessage::Pong,
|
||||
Self::Close(_) => IncomingWebSocketMessage::Close,
|
||||
Self::Frame(_) => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_websocket_outbound_loop<M, SinkError>(
|
||||
websocket_writer: impl futures::sink::Sink<M, Error = SinkError> + Send + 'static,
|
||||
mut writer_rx: mpsc::Receiver<QueuedOutgoingMessage>,
|
||||
mut writer_control_rx: mpsc::Receiver<M>,
|
||||
disconnect_token: CancellationToken,
|
||||
mut encoder: Option<ZstdEncoder>,
|
||||
) where
|
||||
M: AppServerWebSocketMessage + Send + 'static,
|
||||
SinkError: Send + 'static,
|
||||
{
|
||||
tokio::pin!(websocket_writer);
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = disconnect_token.cancelled() => {
|
||||
break;
|
||||
}
|
||||
message = writer_control_rx.recv() => {
|
||||
let Some(message) = message else {
|
||||
break;
|
||||
};
|
||||
if websocket_writer.send(message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
queued_message = writer_rx.recv() => {
|
||||
let Some(queued_message) = queued_message else {
|
||||
break;
|
||||
};
|
||||
let Some(json) = serialize_outgoing_message(queued_message.message) else {
|
||||
continue;
|
||||
};
|
||||
let message = if let Some(encoder) = &mut encoder {
|
||||
match encoder.encode(&json) {
|
||||
Ok(payload) => M::binary(payload.into()),
|
||||
Err(err) => {
|
||||
warn!("websocket compression error: {err}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
M::text(json)
|
||||
};
|
||||
if websocket_writer.send(message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
if let Some(write_complete_tx) = queued_message.write_complete_tx {
|
||||
let _ = write_complete_tx.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_websocket_inbound_loop<M, StreamError>(
|
||||
websocket_reader: impl futures::stream::Stream<Item = Result<M, StreamError>> + Send + 'static,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
writer_tx_for_reader: mpsc::Sender<QueuedOutgoingMessage>,
|
||||
writer_control_tx: mpsc::Sender<M>,
|
||||
connection_id: ConnectionId,
|
||||
disconnect_token: CancellationToken,
|
||||
mut decoder: Option<ZstdDecoder>,
|
||||
) where
|
||||
M: AppServerWebSocketMessage + Send + 'static,
|
||||
StreamError: std::fmt::Display + Send + 'static,
|
||||
{
|
||||
tokio::pin!(websocket_reader);
|
||||
loop {
|
||||
let incoming_message = tokio::select! {
|
||||
_ = disconnect_token.cancelled() => break,
|
||||
incoming_message = websocket_reader.next() => incoming_message,
|
||||
};
|
||||
let message = match incoming_message {
|
||||
Some(Ok(message)) => message,
|
||||
None => break,
|
||||
Some(Err(err)) => {
|
||||
warn!("websocket receive error: {err}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
let text = match message.into_incoming() {
|
||||
Some(IncomingWebSocketMessage::Text(text)) => {
|
||||
if decoder.is_some() {
|
||||
warn!("unexpected text on compressed websocket connection");
|
||||
break;
|
||||
}
|
||||
text
|
||||
}
|
||||
Some(IncomingWebSocketMessage::Binary(payload)) => {
|
||||
let Some(decoder) = &mut decoder else {
|
||||
warn!("dropping unsupported binary websocket message");
|
||||
continue;
|
||||
};
|
||||
match decoder.decode(&payload) {
|
||||
Ok(text) => text,
|
||||
Err(err) => {
|
||||
warn!("websocket decompression error: {err}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(IncomingWebSocketMessage::Ping(payload)) => {
|
||||
match writer_control_tx.try_send(M::pong(payload)) {
|
||||
Ok(()) => {}
|
||||
Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => break,
|
||||
Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
|
||||
warn!(
|
||||
"websocket control queue full while replying to ping; closing connection"
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Some(IncomingWebSocketMessage::Pong) => continue,
|
||||
Some(IncomingWebSocketMessage::Close) => break,
|
||||
None => continue,
|
||||
};
|
||||
if !forward_incoming_message(
|
||||
&transport_event_tx,
|
||||
&writer_tx_for_reader,
|
||||
connection_id,
|
||||
&text,
|
||||
)
|
||||
.await
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "websocket_compression_tests.rs"]
|
||||
mod compression_tests;
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Exercise negotiated and legacy peers through the TCP and local socket listeners.
|
||||
|
||||
use super::*;
|
||||
use crate::OutgoingError;
|
||||
use crate::OutgoingMessage;
|
||||
use crate::transport::DaemonShutdownAccess;
|
||||
use crate::transport::start_control_socket_acceptor;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::JSONRPCMessage;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_uds::UnixStream;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::error::Error;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
use tokio_tungstenite::WebSocketStream;
|
||||
use tokio_tungstenite::client_async;
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_compression_negotiates_and_retains_history() -> Result<(), Box<dyn Error>> {
|
||||
for compression in [WebSocketCompression::Plain, WebSocketCompression::Zstd] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let (transport_event_tx, mut events) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let router = Router::new()
|
||||
.fallback(any(websocket_upgrade_handler))
|
||||
.with_state(WebSocketListenerState {
|
||||
transport_event_tx,
|
||||
auth_policy: Arc::new(WebsocketAuthPolicy::default()),
|
||||
compression,
|
||||
});
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(
|
||||
listener,
|
||||
router.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.await
|
||||
});
|
||||
for offer in [None, Some(ZSTD_STREAM_PROTOCOL), Some("future-protocol")] {
|
||||
let mut request = format!("ws://{address}").into_client_request()?;
|
||||
if let Some(offer) = offer {
|
||||
request.headers_mut().insert(
|
||||
WEBSOCKET_COMPRESSION_HEADER,
|
||||
HeaderValue::from_static(offer),
|
||||
);
|
||||
}
|
||||
let (websocket, response) = connect_async(request).await?;
|
||||
let expected = offer.filter(|offer| {
|
||||
compression == WebSocketCompression::Zstd && *offer == ZSTD_STREAM_PROTOCOL
|
||||
});
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get(WEBSOCKET_COMPRESSION_HEADER)
|
||||
.map(HeaderValue::to_str)
|
||||
.transpose()?,
|
||||
expected
|
||||
);
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 5),
|
||||
roundtrip(
|
||||
websocket,
|
||||
&mut events,
|
||||
WebSocketCompression::from_response_header(expected)?,
|
||||
),
|
||||
)
|
||||
.await??;
|
||||
}
|
||||
server.abort();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_socket_compression_negotiates_and_retains_history() -> Result<(), Box<dyn Error>> {
|
||||
for compression in [WebSocketCompression::Plain, WebSocketCompression::Zstd] {
|
||||
let temp_dir = tempfile::TempDir::new()?;
|
||||
let socket_path = AbsolutePathBuf::from_absolute_path(
|
||||
temp_dir.path().join("app-server-control").join("rpc.sock"),
|
||||
)?;
|
||||
let (transport_event_tx, mut events) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown = CancellationToken::new();
|
||||
let server = start_control_socket_acceptor(
|
||||
socket_path.clone(),
|
||||
transport_event_tx,
|
||||
shutdown.clone(),
|
||||
DaemonShutdownAccess::Disabled,
|
||||
compression,
|
||||
)
|
||||
.await?;
|
||||
for offer in [None, Some(ZSTD_STREAM_PROTOCOL), Some("future-protocol")] {
|
||||
let stream = UnixStream::connect(socket_path.as_path()).await?;
|
||||
let mut request = "ws://localhost/rpc".into_client_request()?;
|
||||
if let Some(offer) = offer {
|
||||
request.headers_mut().insert(
|
||||
WEBSOCKET_COMPRESSION_HEADER,
|
||||
HeaderValue::from_static(offer),
|
||||
);
|
||||
}
|
||||
let (websocket, response) = client_async(request, stream).await?;
|
||||
let expected = offer.filter(|offer| {
|
||||
compression == WebSocketCompression::Zstd && *offer == ZSTD_STREAM_PROTOCOL
|
||||
});
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get(WEBSOCKET_COMPRESSION_HEADER)
|
||||
.map(HeaderValue::to_str)
|
||||
.transpose()?,
|
||||
expected
|
||||
);
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 5),
|
||||
roundtrip(
|
||||
websocket,
|
||||
&mut events,
|
||||
WebSocketCompression::from_response_header(expected)?,
|
||||
),
|
||||
)
|
||||
.await??;
|
||||
}
|
||||
shutdown.cancel();
|
||||
server.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn roundtrip<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
mut websocket: WebSocketStream<S>,
|
||||
events: &mut mpsc::Receiver<TransportEvent>,
|
||||
compression: WebSocketCompression,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let Some(TransportEvent::ConnectionOpened { writer, .. }) = events.recv().await else {
|
||||
return Err("expected connection opened".into());
|
||||
};
|
||||
let mut encoder = ZstdEncoder::new()?;
|
||||
let mut decoder = ZstdDecoder::new(/*max_message_size*/ 1024)?;
|
||||
for index in 0..2 {
|
||||
let request = format!(r#"{{"method":"example","id":{index}}}"#);
|
||||
let message = match compression {
|
||||
WebSocketCompression::Plain => {
|
||||
TungsteniteWebSocketMessage::Text(request.clone().into())
|
||||
}
|
||||
WebSocketCompression::Zstd => {
|
||||
TungsteniteWebSocketMessage::Binary(encoder.encode(&request)?.into())
|
||||
}
|
||||
};
|
||||
websocket.send(message).await?;
|
||||
let Some(TransportEvent::IncomingMessage { message, .. }) = events.recv().await else {
|
||||
return Err("expected incoming RPC".into());
|
||||
};
|
||||
assert_eq!(message, serde_json::from_str::<JSONRPCMessage>(&request)?);
|
||||
let response = OutgoingMessage::Error(OutgoingError {
|
||||
id: RequestId::Integer(index),
|
||||
error: JSONRPCErrorError {
|
||||
code: -32601,
|
||||
message: "unknown method".to_string(),
|
||||
data: None,
|
||||
},
|
||||
});
|
||||
let expected = serde_json::to_string(&response)?;
|
||||
writer.send(QueuedOutgoingMessage::new(response)).await?;
|
||||
let text = loop {
|
||||
let response = websocket.next().await.ok_or("expected response")??;
|
||||
match (compression, response) {
|
||||
(WebSocketCompression::Plain, TungsteniteWebSocketMessage::Text(text)) => {
|
||||
break text.to_string();
|
||||
}
|
||||
(WebSocketCompression::Zstd, TungsteniteWebSocketMessage::Binary(bytes)) => {
|
||||
break decoder.decode(&bytes)?;
|
||||
}
|
||||
(
|
||||
_,
|
||||
TungsteniteWebSocketMessage::Ping(_) | TungsteniteWebSocketMessage::Pong(_),
|
||||
) => {}
|
||||
_ => return Err("response has incorrect WebSocket message type".into()),
|
||||
}
|
||||
};
|
||||
assert_eq!(text, expected);
|
||||
websocket
|
||||
.send(TungsteniteWebSocketMessage::Ping(Bytes::from_static(
|
||||
b"check",
|
||||
)))
|
||||
.await?;
|
||||
assert_eq!(
|
||||
websocket.next().await.ok_or("expected pong")??,
|
||||
TungsteniteWebSocketMessage::Pong(Bytes::from_static(b"check"))
|
||||
);
|
||||
}
|
||||
websocket.close(/*msg*/ None).await?;
|
||||
assert!(matches!(
|
||||
events.recv().await,
|
||||
Some(TransportEvent::ConnectionClosed { .. })
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
231
akode-rs/app-server-transport/src/websocket_compression.rs
Normal file
231
akode-rs/app-server-transport/src/websocket_compression.rs
Normal file
@@ -0,0 +1,231 @@
|
||||
//! Negotiated WebSocket payload compression with one persistent zstd stream per direction.
|
||||
//!
|
||||
//! The upgrade request and response must both carry
|
||||
//! `x-codex-app-server-compression: zstd-stream-v1` to enable compression.
|
||||
//! Without an acknowledgment, messages remain JSON text.
|
||||
//! Each binary message contains one UTF-8 JSON message flushed with `ZSTD_e_flush`.
|
||||
//! Keep separate streams per direction and start fresh on reconnect. Never finish
|
||||
//! the zstd frame between messages.
|
||||
//! Paired codecs report cumulative payload sizes per connection and direction.
|
||||
|
||||
use std::io;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use zstd::stream::raw::CParameter;
|
||||
use zstd::stream::raw::DParameter;
|
||||
use zstd::stream::raw::Decoder;
|
||||
use zstd::stream::raw::Encoder;
|
||||
use zstd::stream::raw::Operation;
|
||||
use zstd::stream::raw::OutBuffer;
|
||||
|
||||
use crate::ConnectionId;
|
||||
|
||||
pub const WEBSOCKET_COMPRESSION_HEADER: &str = "x-codex-app-server-compression";
|
||||
pub const ZSTD_STREAM_PROTOCOL: &str = "zstd-stream-v1";
|
||||
const COMPRESSION_LEVEL: i32 = -7;
|
||||
const WINDOW_LOG: u32 = 20;
|
||||
const BUFFER_SIZE: usize = 32 * 1024;
|
||||
const STATS_INTERVAL: Duration = Duration::from_secs(60);
|
||||
static NEXT_NATIVE_CONNECTION_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum WebSocketCompression {
|
||||
Plain,
|
||||
Zstd,
|
||||
}
|
||||
|
||||
impl WebSocketCompression {
|
||||
/// A missing echo selects the existing text protocol for older peers.
|
||||
pub fn from_response_header(value: Option<&str>) -> io::Result<Self> {
|
||||
match value {
|
||||
None => Ok(Self::Plain),
|
||||
Some(ZSTD_STREAM_PROTOCOL) => Ok(Self::Zstd),
|
||||
Some(_) => Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"unsupported app-server WebSocket compression protocol",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ZstdEncoder {
|
||||
encoder: Encoder<'static>,
|
||||
stats: Option<CompressionStats>,
|
||||
}
|
||||
|
||||
impl ZstdEncoder {
|
||||
pub fn new() -> io::Result<Self> {
|
||||
let mut encoder = Encoder::new(COMPRESSION_LEVEL)?;
|
||||
encoder.set_parameter(CParameter::WindowLog(WINDOW_LOG))?;
|
||||
Ok(Self {
|
||||
encoder,
|
||||
stats: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Flush one message without ending the frame or resetting its history.
|
||||
pub fn encode(&mut self, text: &str) -> io::Result<Vec<u8>> {
|
||||
let mut input = text.as_bytes();
|
||||
let mut encoded = Vec::new();
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
while !input.is_empty() {
|
||||
let status = self.encoder.run_on_buffers(input, &mut buffer)?;
|
||||
encoded.extend_from_slice(&buffer[..status.bytes_written]);
|
||||
input = &input[status.bytes_read..];
|
||||
}
|
||||
loop {
|
||||
let mut output = OutBuffer::around(&mut buffer[..]);
|
||||
let remaining = self.encoder.flush(&mut output)?;
|
||||
encoded.extend_from_slice(output.as_slice());
|
||||
if remaining == 0 {
|
||||
if let Some(stats) = &mut self.stats {
|
||||
stats.record(text.len(), encoded.len());
|
||||
}
|
||||
return Ok(encoded);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ZstdDecoder {
|
||||
decoder: Decoder<'static>,
|
||||
max_message_size: usize,
|
||||
stats: Option<CompressionStats>,
|
||||
}
|
||||
|
||||
impl ZstdDecoder {
|
||||
pub fn new(max_message_size: usize) -> io::Result<Self> {
|
||||
let mut decoder = Decoder::new()?;
|
||||
decoder.set_parameter(DParameter::WindowLogMax(WINDOW_LOG))?;
|
||||
Ok(Self {
|
||||
decoder,
|
||||
max_message_size,
|
||||
stats: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode one flushed message, retaining history and bounding its decoded size.
|
||||
/// Any error invalidates the stream; the caller must close the connection.
|
||||
pub fn decode(&mut self, mut input: &[u8]) -> io::Result<String> {
|
||||
let compressed_bytes = input.len();
|
||||
let mut decoded = Vec::new();
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
loop {
|
||||
let status = self.decoder.run_on_buffers(input, &mut buffer)?;
|
||||
if status.bytes_written > self.max_message_size.saturating_sub(decoded.len()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"decompressed app-server WebSocket message exceeds size limit",
|
||||
));
|
||||
}
|
||||
decoded.extend_from_slice(&buffer[..status.bytes_written]);
|
||||
input = &input[status.bytes_read..];
|
||||
if status.bytes_read == 0 && status.bytes_written == 0 {
|
||||
if !input.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"invalid app-server WebSocket compressed message",
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
let text = String::from_utf8(decoded)
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
if let Some(stats) = &mut self.stats {
|
||||
stats.record(text.len(), compressed_bytes);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies the connection whose compression statistics are reported.
|
||||
pub enum CompressionConnection {
|
||||
Listener(ConnectionId),
|
||||
NativeClient,
|
||||
}
|
||||
|
||||
/// Create codecs whose payload statistics share the transport connection ID.
|
||||
/// TX counts encoded payloads, including those whose subsequent socket write fails.
|
||||
pub fn zstd_codec_pair(
|
||||
max_message_size: usize,
|
||||
connection: CompressionConnection,
|
||||
) -> io::Result<(ZstdEncoder, ZstdDecoder)> {
|
||||
let mut encoder = ZstdEncoder::new()?;
|
||||
let mut decoder = ZstdDecoder::new(max_message_size)?;
|
||||
let (connection_id, connection_kind) = match connection {
|
||||
CompressionConnection::Listener(connection_id) => (connection_id.0, "listener"),
|
||||
CompressionConnection::NativeClient => (
|
||||
NEXT_NATIVE_CONNECTION_ID.fetch_add(1, Ordering::Relaxed),
|
||||
"native_client",
|
||||
),
|
||||
};
|
||||
encoder.stats = Some(CompressionStats::new(connection_id, connection_kind, "tx"));
|
||||
decoder.stats = Some(CompressionStats::new(connection_id, connection_kind, "rx"));
|
||||
Ok((encoder, decoder))
|
||||
}
|
||||
|
||||
struct CompressionStats {
|
||||
connection_id: u64,
|
||||
connection_kind: &'static str,
|
||||
direction: &'static str,
|
||||
uncompressed_bytes: u64,
|
||||
compressed_bytes: u64,
|
||||
messages: u64,
|
||||
last_report: Instant,
|
||||
}
|
||||
|
||||
impl CompressionStats {
|
||||
fn new(connection_id: u64, connection_kind: &'static str, direction: &'static str) -> Self {
|
||||
Self {
|
||||
connection_id,
|
||||
connection_kind,
|
||||
direction,
|
||||
uncompressed_bytes: 0,
|
||||
compressed_bytes: 0,
|
||||
messages: 0,
|
||||
last_report: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record(&mut self, uncompressed_bytes: usize, compressed_bytes: usize) {
|
||||
self.uncompressed_bytes += uncompressed_bytes as u64;
|
||||
self.compressed_bytes += compressed_bytes as u64;
|
||||
self.messages += 1;
|
||||
if self.last_report.elapsed() >= STATS_INTERVAL {
|
||||
self.report("periodic");
|
||||
self.last_report = Instant::now();
|
||||
}
|
||||
}
|
||||
|
||||
fn saved_percent(&self) -> Option<f64> {
|
||||
(self.uncompressed_bytes != 0)
|
||||
.then(|| 100.0 * (1.0 - self.compressed_bytes as f64 / self.uncompressed_bytes as f64))
|
||||
}
|
||||
|
||||
fn report(&self, report: &'static str) {
|
||||
tracing::info!(
|
||||
connection_id = self.connection_id,
|
||||
connection_kind = self.connection_kind,
|
||||
direction = self.direction,
|
||||
report,
|
||||
uncompressed_bytes = self.uncompressed_bytes,
|
||||
compressed_bytes = self.compressed_bytes,
|
||||
messages = self.messages,
|
||||
saved_percent = self.saved_percent(),
|
||||
"app-server WebSocket compression payload totals"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CompressionStats {
|
||||
fn drop(&mut self) {
|
||||
self.report("final");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "websocket_compression_tests.rs"]
|
||||
mod tests;
|
||||
102
akode-rs/app-server-transport/src/websocket_compression_tests.rs
Normal file
102
akode-rs/app-server-transport/src/websocket_compression_tests.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
//! Verify persistent history, peer fallback, and bounded decompression.
|
||||
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn response_header_selects_compression_or_plain_fallback() -> io::Result<()> {
|
||||
assert_eq!(
|
||||
WebSocketCompression::from_response_header(/*value*/ None)?,
|
||||
WebSocketCompression::Plain
|
||||
);
|
||||
assert_eq!(
|
||||
WebSocketCompression::from_response_header(Some(ZSTD_STREAM_PROTOCOL))?,
|
||||
WebSocketCompression::Zstd
|
||||
);
|
||||
assert!(WebSocketCompression::from_response_header(Some("unknown")).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages_keep_history_and_have_independent_size_limits() -> io::Result<()> {
|
||||
let text = serde_json::to_string(
|
||||
&(0..1_000)
|
||||
.map(|index| format!("thread-{index}: individual message body {index}"))
|
||||
.collect::<Vec<_>>(),
|
||||
)?;
|
||||
let connection_id = ConnectionId(42);
|
||||
let (mut encoder, mut decoder) =
|
||||
zstd_codec_pair(text.len(), CompressionConnection::Listener(connection_id))?;
|
||||
assert_eq!(encoder.stats.as_ref().unwrap().saved_percent(), None);
|
||||
let first = encoder.encode(&text)?;
|
||||
let second = encoder.encode(&text)?;
|
||||
assert_eq!(decoder.decode(&first)?, text);
|
||||
assert_eq!(decoder.decode(&second)?, text);
|
||||
let tx = encoder.stats.as_ref().unwrap();
|
||||
let rx = decoder.stats.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
(tx.connection_id, rx.connection_id),
|
||||
(connection_id.0, connection_id.0)
|
||||
);
|
||||
assert_eq!(
|
||||
(tx.uncompressed_bytes, tx.compressed_bytes, tx.messages),
|
||||
(
|
||||
(text.len() * 2) as u64,
|
||||
(first.len() + second.len()) as u64,
|
||||
2
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
(rx.uncompressed_bytes, rx.compressed_bytes, rx.messages),
|
||||
(tx.uncompressed_bytes, tx.compressed_bytes, tx.messages)
|
||||
);
|
||||
assert_eq!(
|
||||
tx.saved_percent(),
|
||||
Some(100.0 * (1.0 - (first.len() + second.len()) as f64 / (text.len() * 2) as f64))
|
||||
);
|
||||
assert!(second.len() < first.len());
|
||||
assert!(ZstdDecoder::new(text.len())?.decode(&second).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_size_limit_covers_output_larger_than_scratch_buffer() -> io::Result<()> {
|
||||
let text = "abcdefgh".repeat(BUFFER_SIZE);
|
||||
let encoded = ZstdEncoder::new()?.encode(&text)?;
|
||||
assert_eq!(ZstdDecoder::new(text.len())?.decode(&encoded)?, text);
|
||||
let (_, mut decoder) = zstd_codec_pair(text.len() - 1, CompressionConnection::NativeClient)?;
|
||||
let error = decoder
|
||||
.decode(&encoded)
|
||||
.expect_err("oversize message must fail");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
let stats = decoder.stats.as_ref().unwrap();
|
||||
assert_eq!((stats.uncompressed_bytes, stats.compressed_bytes), (0, 0));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_compressed_data_fails() -> io::Result<()> {
|
||||
assert!(
|
||||
ZstdDecoder::new(/*max_message_size*/ 1024)?
|
||||
.decode(b"not zstd")
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn larger_compression_window_is_rejected() -> io::Result<()> {
|
||||
let mut encoder = ZstdEncoder::new()?;
|
||||
encoder
|
||||
.encoder
|
||||
.set_parameter(CParameter::WindowLog(WINDOW_LOG + 1))?;
|
||||
let encoded = encoder.encode("a message with an unsupported compression window")?;
|
||||
assert!(
|
||||
ZstdDecoder::new(/*max_message_size*/ 1024)?
|
||||
.decode(&encoded)
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user