aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
21
akode-rs/exec-server/src/server/build_identity.rs
Normal file
21
akode-rs/exec-server/src/server/build_identity.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
//! Cache the running executor's build identity before accepting connections.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use akode_build_info::BuildInfo;
|
||||
use akode_build_info::build_id;
|
||||
|
||||
use crate::protocol::EnvironmentInfo;
|
||||
|
||||
pub(super) static PROVIDER_ID: LazyLock<Option<String>> = LazyLock::new(|| {
|
||||
let info = BuildInfo::get();
|
||||
info.target()
|
||||
.and_then(|target| build_id(info.build_commit(), target))
|
||||
});
|
||||
|
||||
pub(super) fn local_environment_info() -> EnvironmentInfo {
|
||||
EnvironmentInfo {
|
||||
provider_id: PROVIDER_ID.clone(),
|
||||
..super::release_version::local_environment_info()
|
||||
}
|
||||
}
|
||||
445
akode-rs/exec-server/src/server/file_system_handler.rs
Normal file
445
akode-rs/exec-server/src/server/file_system_handler.rs
Normal file
@@ -0,0 +1,445 @@
|
||||
use std::io;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use akode_exec_server_protocol::JSONRPCErrorError;
|
||||
|
||||
use crate::CapabilityRootsDiscoverParams;
|
||||
use crate::CapabilityRootsDiscoverResponse;
|
||||
use crate::CopyOptions;
|
||||
use crate::CreateDirectoryOptions;
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::ExecutorFileSystem;
|
||||
use crate::GetMetadataOptions;
|
||||
use crate::ReadFileOptions;
|
||||
use crate::RemoveOptions;
|
||||
use crate::WriteFileOptions;
|
||||
use crate::file_handle::FileHandleManager;
|
||||
use crate::local_file_system::LocalFileSystem;
|
||||
use crate::protocol::FS_READ_DIRECTORY_METHOD;
|
||||
use crate::protocol::FS_WRITE_FILE_METHOD;
|
||||
use crate::protocol::FsCanonicalizeParams;
|
||||
use crate::protocol::FsCanonicalizeResponse;
|
||||
use crate::protocol::FsCloseParams;
|
||||
use crate::protocol::FsCloseResponse;
|
||||
use crate::protocol::FsCopyParams;
|
||||
use crate::protocol::FsCopyResponse;
|
||||
use crate::protocol::FsCreateDirectoryParams;
|
||||
use crate::protocol::FsCreateDirectoryResponse;
|
||||
use crate::protocol::FsGetMetadataParams;
|
||||
use crate::protocol::FsGetMetadataResponse;
|
||||
use crate::protocol::FsOpenParams;
|
||||
use crate::protocol::FsOpenResponse;
|
||||
use crate::protocol::FsReadBlockParams;
|
||||
use crate::protocol::FsReadBlockResponse;
|
||||
use crate::protocol::FsReadDirectoryEntry;
|
||||
use crate::protocol::FsReadDirectoryParams;
|
||||
use crate::protocol::FsReadDirectoryResponse;
|
||||
use crate::protocol::FsReadFileParams;
|
||||
use crate::protocol::FsReadFileResponse;
|
||||
use crate::protocol::FsRemoveParams;
|
||||
use crate::protocol::FsRemoveResponse;
|
||||
use crate::protocol::FsWalkParams;
|
||||
use crate::protocol::FsWalkResponse;
|
||||
use crate::protocol::FsWriteBlockParams;
|
||||
use crate::protocol::FsWriteBlockResponse;
|
||||
use crate::protocol::FsWriteFileParams;
|
||||
use crate::protocol::FsWriteFileResponse;
|
||||
use crate::rpc::internal_error;
|
||||
use crate::rpc::invalid_request;
|
||||
use crate::rpc::not_found;
|
||||
|
||||
const MAX_FILE_HANDLE_ID_BYTES: usize = 32;
|
||||
// Each read-directory entry needs four JSON values. Keep same-version
|
||||
// producers comfortably below the shared 256K-value decoder budget.
|
||||
const MAX_READ_DIRECTORY_ENTRIES: usize = 50_000;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct FileSystemHandler {
|
||||
file_system: LocalFileSystem,
|
||||
file_handles: FileHandleManager,
|
||||
}
|
||||
|
||||
impl FileSystemHandler {
|
||||
pub(crate) fn new(runtime_paths: ExecServerRuntimeOptions) -> Self {
|
||||
Self {
|
||||
file_system: LocalFileSystem::with_runtime_paths(runtime_paths),
|
||||
file_handles: FileHandleManager::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
self.file_handles.close_all();
|
||||
}
|
||||
|
||||
pub(crate) async fn discover_capability_roots(
|
||||
&self,
|
||||
params: CapabilityRootsDiscoverParams,
|
||||
) -> Result<CapabilityRootsDiscoverResponse, JSONRPCErrorError> {
|
||||
let sandbox = params
|
||||
.roots
|
||||
.first()
|
||||
.and_then(|root| root.sandbox.as_ref())
|
||||
.filter(|sandbox| {
|
||||
sandbox
|
||||
.validate_file_system_paths_for_current_host()
|
||||
.is_ok()
|
||||
&& sandbox.should_read_from_sandbox()
|
||||
&& (!cfg!(target_os = "windows") || sandbox.windows_sandbox_is_requested())
|
||||
&& params
|
||||
.roots
|
||||
.iter()
|
||||
.all(|root| root.sandbox.as_ref() == Some(*sandbox))
|
||||
})
|
||||
.cloned();
|
||||
|
||||
if let Some(sandbox) = sandbox {
|
||||
let mut batched_params = params.clone();
|
||||
for root in &mut batched_params.roots {
|
||||
root.sandbox = None;
|
||||
}
|
||||
let result = match self.file_system.sandboxed() {
|
||||
Ok(file_system) => {
|
||||
file_system
|
||||
.discover_capability_roots(batched_params, &sandbox)
|
||||
.await
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
match result {
|
||||
Ok(response) => return Ok(response),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "batched capability discovery failed; retrying roots separately");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
crate::discover_capability_roots(&self.file_system, params)
|
||||
.await
|
||||
.map_err(|error| invalid_request(error.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) async fn open(
|
||||
&self,
|
||||
params: FsOpenParams,
|
||||
) -> Result<FsOpenResponse, JSONRPCErrorError> {
|
||||
validate_file_handle_id(¶ms.handle_id)?;
|
||||
let handle_id = self
|
||||
.file_handles
|
||||
.open(
|
||||
params.handle_id,
|
||||
self.file_system
|
||||
.open_file(¶ms.path, params.mode, params.sandbox.as_ref()),
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsOpenResponse { handle_id })
|
||||
}
|
||||
|
||||
pub(crate) async fn read_block(
|
||||
&self,
|
||||
params: FsReadBlockParams,
|
||||
) -> Result<FsReadBlockResponse, JSONRPCErrorError> {
|
||||
validate_file_handle_id(¶ms.handle_id)?;
|
||||
let block = self
|
||||
.file_handles
|
||||
.read_block(¶ms.handle_id, params.offset, params.len)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsReadBlockResponse {
|
||||
chunk: block.bytes.into(),
|
||||
eof: block.eof,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn write_block(
|
||||
&self,
|
||||
params: FsWriteBlockParams,
|
||||
) -> Result<FsWriteBlockResponse, JSONRPCErrorError> {
|
||||
validate_file_handle_id(¶ms.handle_id)?;
|
||||
self.file_handles
|
||||
.write_block(¶ms.handle_id, params.offset, params.chunk.into_inner())
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsWriteBlockResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn close(
|
||||
&self,
|
||||
params: FsCloseParams,
|
||||
) -> Result<FsCloseResponse, JSONRPCErrorError> {
|
||||
validate_file_handle_id(¶ms.handle_id)?;
|
||||
self.file_handles.close(¶ms.handle_id);
|
||||
Ok(FsCloseResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn read_file(
|
||||
&self,
|
||||
params: FsReadFileParams,
|
||||
) -> Result<FsReadFileResponse, JSONRPCErrorError> {
|
||||
let bytes = self
|
||||
.file_system
|
||||
.read_file(
|
||||
¶ms.path,
|
||||
ReadFileOptions {
|
||||
follow_symlinks: params.follow_symlinks.unwrap_or(true),
|
||||
},
|
||||
params.sandbox.as_ref(),
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsReadFileResponse {
|
||||
data_base64: STANDARD.encode(bytes),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn write_file(
|
||||
&self,
|
||||
params: FsWriteFileParams,
|
||||
) -> Result<FsWriteFileResponse, JSONRPCErrorError> {
|
||||
let bytes = STANDARD.decode(params.data_base64).map_err(|err| {
|
||||
invalid_request(format!(
|
||||
"{FS_WRITE_FILE_METHOD} requires valid base64 dataBase64: {err}"
|
||||
))
|
||||
})?;
|
||||
self.file_system
|
||||
.write_file(
|
||||
¶ms.path,
|
||||
bytes,
|
||||
WriteFileOptions {
|
||||
follow_symlinks: params.follow_symlinks.unwrap_or(true),
|
||||
},
|
||||
params.sandbox.as_ref(),
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsWriteFileResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn create_directory(
|
||||
&self,
|
||||
params: FsCreateDirectoryParams,
|
||||
) -> Result<FsCreateDirectoryResponse, JSONRPCErrorError> {
|
||||
let recursive = params.recursive.unwrap_or(true);
|
||||
self.file_system
|
||||
.create_directory(
|
||||
¶ms.path,
|
||||
CreateDirectoryOptions {
|
||||
recursive,
|
||||
follow_symlinks: params.follow_symlinks.unwrap_or(true),
|
||||
},
|
||||
params.sandbox.as_ref(),
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsCreateDirectoryResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn get_metadata(
|
||||
&self,
|
||||
params: FsGetMetadataParams,
|
||||
) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
|
||||
let metadata = self
|
||||
.file_system
|
||||
.get_metadata(
|
||||
¶ms.path,
|
||||
GetMetadataOptions {
|
||||
follow_symlinks: params.follow_symlinks.unwrap_or(true),
|
||||
},
|
||||
params.sandbox.as_ref(),
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsGetMetadataResponse {
|
||||
is_directory: metadata.is_directory,
|
||||
is_file: metadata.is_file,
|
||||
is_symlink: metadata.is_symlink,
|
||||
size: metadata.size,
|
||||
created_at_ms: metadata.created_at_ms,
|
||||
modified_at_ms: metadata.modified_at_ms,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn canonicalize(
|
||||
&self,
|
||||
params: FsCanonicalizeParams,
|
||||
) -> Result<FsCanonicalizeResponse, JSONRPCErrorError> {
|
||||
let path = self
|
||||
.file_system
|
||||
.canonicalize(¶ms.path, params.sandbox.as_ref())
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsCanonicalizeResponse { path })
|
||||
}
|
||||
|
||||
pub(crate) async fn read_directory(
|
||||
&self,
|
||||
params: FsReadDirectoryParams,
|
||||
) -> Result<FsReadDirectoryResponse, JSONRPCErrorError> {
|
||||
let entries = self
|
||||
.file_system
|
||||
.read_directory(¶ms.path, params.sandbox.as_ref())
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
let entry_count = entries.len();
|
||||
if entry_count > MAX_READ_DIRECTORY_ENTRIES {
|
||||
return Err(internal_error(format!(
|
||||
"{FS_READ_DIRECTORY_METHOD} returned {entry_count} entries; limit is {MAX_READ_DIRECTORY_ENTRIES}"
|
||||
)));
|
||||
}
|
||||
let entries = entries
|
||||
.into_iter()
|
||||
.map(|entry| FsReadDirectoryEntry {
|
||||
file_name: entry.file_name,
|
||||
is_directory: entry.is_directory,
|
||||
is_file: entry.is_file,
|
||||
})
|
||||
.collect();
|
||||
Ok(FsReadDirectoryResponse { entries })
|
||||
}
|
||||
|
||||
pub(crate) async fn walk(
|
||||
&self,
|
||||
params: FsWalkParams,
|
||||
) -> Result<FsWalkResponse, JSONRPCErrorError> {
|
||||
self.file_system
|
||||
.walk(¶ms.path, params.options, params.sandbox.as_ref())
|
||||
.await
|
||||
.map_err(map_fs_error)
|
||||
}
|
||||
|
||||
pub(crate) async fn remove(
|
||||
&self,
|
||||
params: FsRemoveParams,
|
||||
) -> Result<FsRemoveResponse, JSONRPCErrorError> {
|
||||
let recursive = params.recursive.unwrap_or(true);
|
||||
let force = params.force.unwrap_or(true);
|
||||
self.file_system
|
||||
.remove(
|
||||
¶ms.path,
|
||||
RemoveOptions {
|
||||
recursive,
|
||||
force,
|
||||
follow_symlinks: params.follow_symlinks.unwrap_or(true),
|
||||
},
|
||||
params.sandbox.as_ref(),
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsRemoveResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn copy(
|
||||
&self,
|
||||
params: FsCopyParams,
|
||||
) -> Result<FsCopyResponse, JSONRPCErrorError> {
|
||||
self.file_system
|
||||
.copy(
|
||||
¶ms.source_path,
|
||||
¶ms.destination_path,
|
||||
CopyOptions {
|
||||
recursive: params.recursive,
|
||||
},
|
||||
params.sandbox.as_ref(),
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsCopyResponse {})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_file_handle_id(handle_id: &str) -> Result<(), JSONRPCErrorError> {
|
||||
if handle_id.len() > MAX_FILE_HANDLE_ID_BYTES {
|
||||
return Err(invalid_request(format!(
|
||||
"file handle ID must not exceed {MAX_FILE_HANDLE_ID_BYTES} bytes"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_fs_error(err: io::Error) -> JSONRPCErrorError {
|
||||
match err.kind() {
|
||||
io::ErrorKind::NotFound => not_found(err.to_string()),
|
||||
io::ErrorKind::InvalidInput | io::ErrorKind::PermissionDenied => {
|
||||
invalid_request(err.to_string())
|
||||
}
|
||||
_ => internal_error(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::permissions::NetworkSandboxPolicy;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
use crate::FileSystemSandboxContext;
|
||||
use crate::protocol::FsReadFileParams;
|
||||
use crate::protocol::FsWriteFileParams;
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_platform_sandbox_policies_do_not_require_configured_sandbox_helper() {
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let runtime_paths = ExecServerRuntimeOptions::new(
|
||||
std::env::current_exe().expect("current exe"),
|
||||
/*codex_linux_sandbox_exe*/ None,
|
||||
)
|
||||
.expect("runtime paths");
|
||||
let handler = FileSystemHandler::new(runtime_paths);
|
||||
let sandbox_cwd = PathUri::from_host_native_path(temp_dir.path()).expect("tempdir URI");
|
||||
let sandbox_context = |permissions| {
|
||||
FileSystemSandboxContext::from_permission_profile(permissions, sandbox_cwd.clone())
|
||||
};
|
||||
|
||||
for (file_name, permission_profile) in [
|
||||
("danger.txt", PermissionProfile::Disabled),
|
||||
(
|
||||
"external.txt",
|
||||
PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
},
|
||||
),
|
||||
] {
|
||||
let path =
|
||||
PathUri::from_host_native_path(temp_dir.path().join(file_name)).expect("path URI");
|
||||
|
||||
handler
|
||||
.write_file(FsWriteFileParams {
|
||||
path: path.clone(),
|
||||
follow_symlinks: None,
|
||||
data_base64: STANDARD.encode("ok"),
|
||||
sandbox: Some(sandbox_context(permission_profile.clone())),
|
||||
})
|
||||
.await
|
||||
.expect("write file");
|
||||
|
||||
let canonicalized = handler
|
||||
.canonicalize(FsCanonicalizeParams {
|
||||
path: path.clone(),
|
||||
sandbox: Some(sandbox_context(permission_profile.clone())),
|
||||
})
|
||||
.await
|
||||
.expect("canonicalize file");
|
||||
assert_eq!(
|
||||
canonicalized.path,
|
||||
PathUri::from_host_native_path(
|
||||
std::fs::canonicalize(temp_dir.path().join(file_name)).expect("canonical path"),
|
||||
)
|
||||
.expect("canonical path URI"),
|
||||
);
|
||||
|
||||
let response = handler
|
||||
.read_file(FsReadFileParams {
|
||||
path,
|
||||
follow_symlinks: None,
|
||||
sandbox: Some(sandbox_context(permission_profile)),
|
||||
})
|
||||
.await
|
||||
.expect("read file");
|
||||
|
||||
assert_eq!(response.data_base64, STANDARD.encode("ok"));
|
||||
}
|
||||
}
|
||||
}
|
||||
550
akode-rs/exec-server/src/server/handler.rs
Normal file
550
akode-rs/exec-server/src/server/handler.rs
Normal file
@@ -0,0 +1,550 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use akode_exec_server_protocol::JSONRPCErrorError;
|
||||
use akode_exec_server_protocol::RequestId;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
use opentelemetry::trace::SpanContext;
|
||||
use serde_json::to_value;
|
||||
use std::collections::HashSet;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
use crate::DiscoverV2CapabilitiesRequest;
|
||||
use crate::DiscoverV2CapabilitiesResponse;
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::client::http_client::PendingRouteAwareHttpBodyStream;
|
||||
use crate::client::http_client::RouteAwareHttpClient;
|
||||
use crate::client::http_client::RouteAwareHttpRequestRunner;
|
||||
use crate::discover_v2::capability_manager::CapabilityManager;
|
||||
use crate::environment_config::ReadEnvironmentConfigError;
|
||||
use crate::environment_config::read_environment_config;
|
||||
use crate::protocol::CapabilityRootsDiscoverParams;
|
||||
use crate::protocol::CapabilityRootsDiscoverResponse;
|
||||
use crate::protocol::EnvironmentConfigReadParams;
|
||||
use crate::protocol::EnvironmentConfigReadResponse;
|
||||
use crate::protocol::EnvironmentInfo;
|
||||
use crate::protocol::EnvironmentStatus;
|
||||
use crate::protocol::EnvironmentStatusKind;
|
||||
use crate::protocol::ExecParams;
|
||||
use crate::protocol::ExecResponse;
|
||||
use crate::protocol::FsCanonicalizeParams;
|
||||
use crate::protocol::FsCanonicalizeResponse;
|
||||
use crate::protocol::FsCloseParams;
|
||||
use crate::protocol::FsCloseResponse;
|
||||
use crate::protocol::FsCopyParams;
|
||||
use crate::protocol::FsCopyResponse;
|
||||
use crate::protocol::FsCreateDirectoryParams;
|
||||
use crate::protocol::FsCreateDirectoryResponse;
|
||||
use crate::protocol::FsGetMetadataParams;
|
||||
use crate::protocol::FsGetMetadataResponse;
|
||||
use crate::protocol::FsOpenParams;
|
||||
use crate::protocol::FsOpenResponse;
|
||||
use crate::protocol::FsReadBlockParams;
|
||||
use crate::protocol::FsReadBlockResponse;
|
||||
use crate::protocol::FsReadDirectoryParams;
|
||||
use crate::protocol::FsReadDirectoryResponse;
|
||||
use crate::protocol::FsReadFileParams;
|
||||
use crate::protocol::FsReadFileResponse;
|
||||
use crate::protocol::FsRemoveParams;
|
||||
use crate::protocol::FsRemoveResponse;
|
||||
use crate::protocol::FsWalkParams;
|
||||
use crate::protocol::FsWalkResponse;
|
||||
use crate::protocol::FsWriteBlockParams;
|
||||
use crate::protocol::FsWriteBlockResponse;
|
||||
use crate::protocol::FsWriteFileParams;
|
||||
use crate::protocol::FsWriteFileResponse;
|
||||
use crate::protocol::HTTP_REQUEST_METHOD;
|
||||
use crate::protocol::HttpRequestParams;
|
||||
use crate::protocol::InitializeParams;
|
||||
use crate::protocol::InitializeResponse;
|
||||
use crate::protocol::ReadParams;
|
||||
use crate::protocol::ReadResponse;
|
||||
use crate::protocol::SignalParams;
|
||||
use crate::protocol::SignalResponse;
|
||||
use crate::protocol::TerminateParams;
|
||||
use crate::protocol::TerminateResponse;
|
||||
use crate::protocol::WriteParams;
|
||||
use crate::protocol::WriteResponse;
|
||||
use crate::rpc::RpcNotificationSender;
|
||||
use crate::rpc::internal_error;
|
||||
use crate::rpc::invalid_params;
|
||||
use crate::rpc::invalid_request;
|
||||
use crate::server::build_identity::local_environment_info;
|
||||
use crate::server::file_system_handler::FileSystemHandler;
|
||||
use crate::server::session_registry::SessionHandle;
|
||||
use crate::server::session_registry::SessionRegistry;
|
||||
use crate::telemetry::ExecutorRegistration;
|
||||
|
||||
#[path = "missing_watch.rs"]
|
||||
mod missing_watch;
|
||||
|
||||
pub(crate) struct ExecServerHandler {
|
||||
pub(super) executor_registration: Option<Arc<ExecutorRegistration>>,
|
||||
session_registry: Arc<SessionRegistry>,
|
||||
capability_manager: Arc<CapabilityManager>,
|
||||
notifications: RpcNotificationSender,
|
||||
session: StdMutex<Option<SessionHandle>>,
|
||||
active_body_stream_ids: Mutex<HashSet<String>>,
|
||||
// Only the newest observation on this physical connection can be reused.
|
||||
missing_watch: Arc<StdMutex<missing_watch::MissingWatch>>,
|
||||
background_task_shutdown: CancellationToken,
|
||||
background_tasks: TaskTracker,
|
||||
file_system: FileSystemHandler,
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
http_client: RouteAwareHttpClient,
|
||||
initialize_requested: AtomicBool,
|
||||
initialized: AtomicBool,
|
||||
}
|
||||
|
||||
impl ExecServerHandler {
|
||||
pub(crate) fn new(
|
||||
session_registry: Arc<SessionRegistry>,
|
||||
capability_manager: Arc<CapabilityManager>,
|
||||
notifications: RpcNotificationSender,
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
http_client_factory: HttpClientFactory,
|
||||
) -> Self {
|
||||
Self {
|
||||
executor_registration: None,
|
||||
session_registry,
|
||||
capability_manager,
|
||||
notifications,
|
||||
session: StdMutex::new(None),
|
||||
active_body_stream_ids: Mutex::new(HashSet::new()),
|
||||
missing_watch: Arc::default(),
|
||||
background_task_shutdown: CancellationToken::new(),
|
||||
background_tasks: TaskTracker::new(),
|
||||
file_system: FileSystemHandler::new(runtime_paths.clone()),
|
||||
runtime_paths,
|
||||
http_client: RouteAwareHttpClient::new(http_client_factory),
|
||||
initialize_requested: AtomicBool::new(false),
|
||||
initialized: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
self.background_task_shutdown.cancel();
|
||||
self.background_tasks.close();
|
||||
self.background_tasks.wait().await;
|
||||
self.file_system.shutdown().await;
|
||||
if let Some(session) = self.session() {
|
||||
session.detach().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_session_attached(&self) -> bool {
|
||||
self.session()
|
||||
.is_none_or(|session| session.is_session_attached())
|
||||
}
|
||||
|
||||
pub(crate) async fn initialize(
|
||||
&self,
|
||||
params: InitializeParams,
|
||||
) -> Result<InitializeResponse, JSONRPCErrorError> {
|
||||
if self.initialize_requested.swap(true, Ordering::SeqCst) {
|
||||
return Err(invalid_request(
|
||||
"initialize may only be sent once per connection".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let session = match self
|
||||
.session_registry
|
||||
.attach(
|
||||
params.resume_session_id.clone(),
|
||||
self.notifications.clone(),
|
||||
self.runtime_paths.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(session) => session,
|
||||
Err(error) => {
|
||||
self.initialize_requested.store(false, Ordering::SeqCst);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let session_id = session.session_id().to_string();
|
||||
tracing::debug!(
|
||||
session_id,
|
||||
connection_id = %session.connection_id(),
|
||||
"exec-server session attached"
|
||||
);
|
||||
*self
|
||||
.session
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(session);
|
||||
Ok(InitializeResponse {
|
||||
session_id,
|
||||
environment_info: Some(local_environment_info()),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn initialized(&self) -> Result<(), String> {
|
||||
if !self.initialize_requested.load(Ordering::SeqCst) {
|
||||
return Err("received `initialized` notification before `initialize`".into());
|
||||
}
|
||||
self.require_session_attached()
|
||||
.map_err(|error| error.message)?;
|
||||
self.initialized.store(true, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn exec(
|
||||
&self,
|
||||
params: ExecParams,
|
||||
launch_context: Option<SpanContext>,
|
||||
) -> Result<ExecResponse, JSONRPCErrorError> {
|
||||
let session = self.require_initialized_for("exec")?;
|
||||
session
|
||||
.process()
|
||||
.exec(
|
||||
params,
|
||||
crate::process_telemetry::ProcessTelemetry {
|
||||
launch_context,
|
||||
executor_registration: self.executor_registration.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn environment_info(&self) -> Result<EnvironmentInfo, JSONRPCErrorError> {
|
||||
self.require_initialized_for("environment info")?;
|
||||
Ok(local_environment_info())
|
||||
}
|
||||
|
||||
pub(crate) async fn environment_config_read(
|
||||
&self,
|
||||
params: EnvironmentConfigReadParams,
|
||||
) -> Result<EnvironmentConfigReadResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("environment config")?;
|
||||
read_environment_config(
|
||||
crate::LOCAL_FS.as_ref(),
|
||||
params,
|
||||
self.runtime_paths.prefer_mxc,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
ReadEnvironmentConfigError::InvalidParams(message) => invalid_params(message),
|
||||
ReadEnvironmentConfigError::Internal(message) => internal_error(message),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn environment_status(&self) -> Result<EnvironmentStatus, JSONRPCErrorError> {
|
||||
self.require_initialized_for("environment status")?;
|
||||
Ok(EnvironmentStatus {
|
||||
status: EnvironmentStatusKind::Ready,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn exec_read(
|
||||
&self,
|
||||
params: ReadParams,
|
||||
) -> Result<ReadResponse, JSONRPCErrorError> {
|
||||
let session = self.require_initialized_for("exec")?;
|
||||
let response = session.process().exec_read(params).await?;
|
||||
self.require_session_attached()?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub(crate) async fn exec_write(
|
||||
&self,
|
||||
params: WriteParams,
|
||||
) -> Result<WriteResponse, JSONRPCErrorError> {
|
||||
let session = self.require_initialized_for("exec")?;
|
||||
session.process().exec_write(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn signal(
|
||||
&self,
|
||||
params: SignalParams,
|
||||
) -> Result<SignalResponse, JSONRPCErrorError> {
|
||||
let session = self.require_initialized_for("exec")?;
|
||||
session.process().signal(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn terminate(
|
||||
&self,
|
||||
params: TerminateParams,
|
||||
) -> Result<TerminateResponse, JSONRPCErrorError> {
|
||||
let session = self.require_initialized_for("exec")?;
|
||||
session.process().terminate(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn http_request(
|
||||
self: &Arc<Self>,
|
||||
request_id: RequestId,
|
||||
params: HttpRequestParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
self.require_initialized_for("http")?;
|
||||
let stream_response = params.stream_response;
|
||||
let http_request_id = params.request_id.clone();
|
||||
if stream_response {
|
||||
self.reserve_http_body_stream(&http_request_id).await?;
|
||||
}
|
||||
let response = self
|
||||
.http_client
|
||||
.runner(params.redirect_policy)
|
||||
.run(params)
|
||||
.await;
|
||||
if response.is_err() && stream_response {
|
||||
self.release_http_body_stream(&http_request_id).await;
|
||||
}
|
||||
let (response, mut pending_stream) = response?;
|
||||
let result = match to_value(response) {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
if let Some(pending_stream) = pending_stream.take() {
|
||||
self.release_http_body_stream(&pending_stream.request_id)
|
||||
.await;
|
||||
}
|
||||
return Err(internal_error(err.to_string()));
|
||||
}
|
||||
};
|
||||
if let Err(error) = self.notifications.response(request_id, result).await {
|
||||
if let Some(pending_stream) = pending_stream.take() {
|
||||
self.release_http_body_stream(&pending_stream.request_id)
|
||||
.await;
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
// This response bypasses the dispatcher; record it before body-stream setup.
|
||||
tracing::event!(
|
||||
name: "codex.exec_server.response_enqueued",
|
||||
target: "akode_otel.trace_safe",
|
||||
tracing::Level::INFO,
|
||||
event.name = "codex.exec_server.response_enqueued",
|
||||
rpc.method = HTTP_REQUEST_METHOD,
|
||||
outcome = "success",
|
||||
);
|
||||
if let Some(pending_stream) = pending_stream {
|
||||
self.start_http_body_stream(pending_stream).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_read_file(
|
||||
&self,
|
||||
params: FsReadFileParams,
|
||||
) -> Result<FsReadFileResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.read_file(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn discover_capability_roots(
|
||||
&self,
|
||||
params: CapabilityRootsDiscoverParams,
|
||||
) -> Result<CapabilityRootsDiscoverResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("capability discovery")?;
|
||||
self.file_system.discover_capability_roots(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn discover_capabilities_v2(
|
||||
&self,
|
||||
params: DiscoverV2CapabilitiesRequest,
|
||||
) -> Result<Arc<DiscoverV2CapabilitiesResponse>, JSONRPCErrorError> {
|
||||
self.require_initialized_for("capability discovery")?;
|
||||
self.capability_manager
|
||||
.get_or_refresh_discovery(params)
|
||||
.await
|
||||
.map_err(|error| internal_error(error.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_open(
|
||||
&self,
|
||||
params: FsOpenParams,
|
||||
) -> Result<FsOpenResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.open(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_read_block(
|
||||
&self,
|
||||
params: FsReadBlockParams,
|
||||
) -> Result<FsReadBlockResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.read_block(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_write_block(
|
||||
&self,
|
||||
params: FsWriteBlockParams,
|
||||
) -> Result<FsWriteBlockResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.write_block(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_close(
|
||||
&self,
|
||||
params: FsCloseParams,
|
||||
) -> Result<FsCloseResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.close(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_write_file(
|
||||
&self,
|
||||
params: FsWriteFileParams,
|
||||
) -> Result<FsWriteFileResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.write_file(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_create_directory(
|
||||
&self,
|
||||
params: FsCreateDirectoryParams,
|
||||
) -> Result<FsCreateDirectoryResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.create_directory(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_watch_missing(
|
||||
&self,
|
||||
params: crate::protocol::FsWatchMissingParams,
|
||||
) -> Result<crate::protocol::FsWatchMissingResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
let watch = Arc::clone(&self.missing_watch);
|
||||
let notifications = self.notifications.clone();
|
||||
let shutdown = self.background_task_shutdown.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let Ok(mut active) = watch.try_lock() else {
|
||||
return Ok(crate::protocol::FsWatchMissingResponse { watching: false });
|
||||
};
|
||||
active.register(params, notifications, shutdown)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| crate::rpc::internal_error(error.to_string()))?
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_get_metadata(
|
||||
&self,
|
||||
params: FsGetMetadataParams,
|
||||
) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.get_metadata(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_canonicalize(
|
||||
&self,
|
||||
params: FsCanonicalizeParams,
|
||||
) -> Result<FsCanonicalizeResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.canonicalize(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_read_directory(
|
||||
&self,
|
||||
params: FsReadDirectoryParams,
|
||||
) -> Result<FsReadDirectoryResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.read_directory(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_walk(
|
||||
&self,
|
||||
params: FsWalkParams,
|
||||
) -> Result<FsWalkResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.walk(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_remove(
|
||||
&self,
|
||||
params: FsRemoveParams,
|
||||
) -> Result<FsRemoveResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.remove(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn fs_copy(
|
||||
&self,
|
||||
params: FsCopyParams,
|
||||
) -> Result<FsCopyResponse, JSONRPCErrorError> {
|
||||
self.require_initialized_for("filesystem")?;
|
||||
self.file_system.copy(params).await
|
||||
}
|
||||
|
||||
fn require_initialized_for(
|
||||
&self,
|
||||
method_family: &str,
|
||||
) -> Result<SessionHandle, JSONRPCErrorError> {
|
||||
if !self.initialize_requested.load(Ordering::SeqCst) {
|
||||
return Err(invalid_request(format!(
|
||||
"client must call initialize before using {method_family} methods"
|
||||
)));
|
||||
}
|
||||
let session = self.require_session_attached()?;
|
||||
if !self.initialized.load(Ordering::SeqCst) {
|
||||
return Err(invalid_request(format!(
|
||||
"client must send initialized before using {method_family} methods"
|
||||
)));
|
||||
}
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn require_session_attached(&self) -> Result<SessionHandle, JSONRPCErrorError> {
|
||||
let Some(session) = self.session() else {
|
||||
return Err(invalid_request(
|
||||
"client must call initialize before using methods".to_string(),
|
||||
));
|
||||
};
|
||||
if session.is_session_attached() {
|
||||
return Ok(session);
|
||||
}
|
||||
|
||||
Err(invalid_request(
|
||||
"session has been resumed by another connection".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
fn session(&self) -> Option<SessionHandle> {
|
||||
self.session
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone()
|
||||
}
|
||||
|
||||
async fn start_http_body_stream(
|
||||
self: &Arc<Self>,
|
||||
pending_stream: PendingRouteAwareHttpBodyStream,
|
||||
) {
|
||||
let request_id = pending_stream.request_id.clone();
|
||||
if self.background_task_shutdown.is_cancelled() {
|
||||
self.release_http_body_stream(&request_id).await;
|
||||
return;
|
||||
}
|
||||
let finished_request_id = request_id.clone();
|
||||
let handler = Arc::clone(self);
|
||||
let notifications = self.notifications.clone();
|
||||
let shutdown = self.background_task_shutdown.clone();
|
||||
self.background_tasks.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => {}
|
||||
_ = RouteAwareHttpRequestRunner::stream_body(pending_stream, notifications) => {}
|
||||
}
|
||||
handler.release_http_body_stream(&finished_request_id).await;
|
||||
});
|
||||
}
|
||||
|
||||
async fn release_http_body_stream(&self, request_id: &str) {
|
||||
let mut active_body_stream_ids = self.active_body_stream_ids.lock().await;
|
||||
active_body_stream_ids.remove(request_id);
|
||||
}
|
||||
|
||||
async fn reserve_http_body_stream(&self, request_id: &str) -> Result<(), JSONRPCErrorError> {
|
||||
let mut active_body_stream_ids = self.active_body_stream_ids.lock().await;
|
||||
if active_body_stream_ids.contains(request_id) {
|
||||
return Err(invalid_params(format!(
|
||||
"http/request streamResponse requestId `{request_id}` is already active"
|
||||
)));
|
||||
}
|
||||
active_body_stream_ids.insert(request_id.to_string());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
387
akode-rs/exec-server/src/server/handler/tests.rs
Normal file
387
akode-rs/exec-server/src/server/handler/tests.rs
Normal file
@@ -0,0 +1,387 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_http_client::HttpClientFactory;
|
||||
use akode_http_client::OutboundProxyPolicy;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::mpsc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::ExecServerHandler;
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::ProcessId;
|
||||
use crate::discover_v2::capability_manager::CapabilityManager;
|
||||
use crate::protocol::ExecParams;
|
||||
use crate::protocol::InitializeParams;
|
||||
use crate::protocol::ReadParams;
|
||||
use crate::protocol::ReadResponse;
|
||||
use crate::protocol::TerminateParams;
|
||||
use crate::protocol::TerminateResponse;
|
||||
use crate::rpc::RpcNotificationSender;
|
||||
use crate::server::session_registry::SessionRegistry;
|
||||
|
||||
fn exec_params(process_id: &str) -> ExecParams {
|
||||
exec_params_with_argv(process_id, sleep_argv())
|
||||
}
|
||||
|
||||
fn exec_params_with_argv(process_id: &str, argv: Vec<String>) -> ExecParams {
|
||||
ExecParams {
|
||||
metadata: Default::default(),
|
||||
process_id: ProcessId::from(process_id),
|
||||
argv,
|
||||
cwd: PathUri::from_host_native_path(std::env::current_dir().expect("cwd"))
|
||||
.expect("cwd URI"),
|
||||
shell_snapshot: None,
|
||||
env_policy: None,
|
||||
env: inherited_path_env(),
|
||||
tty: false,
|
||||
pipe_stdin: false,
|
||||
arg0: None,
|
||||
sandbox: None,
|
||||
enforce_managed_network: false,
|
||||
managed_network: None,
|
||||
network_proxy: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn inherited_path_env() -> HashMap<String, String> {
|
||||
let mut env = HashMap::new();
|
||||
if let Some(path) = std::env::var_os("PATH") {
|
||||
env.insert("PATH".to_string(), path.to_string_lossy().into_owned());
|
||||
}
|
||||
env
|
||||
}
|
||||
|
||||
fn sleep_argv() -> Vec<String> {
|
||||
shell_argv("sleep 0.1", "ping -n 2 127.0.0.1 >NUL")
|
||||
}
|
||||
|
||||
fn shell_argv(unix_script: &str, windows_script: &str) -> Vec<String> {
|
||||
if cfg!(windows) {
|
||||
vec![
|
||||
windows_command_processor(),
|
||||
"/C".to_string(),
|
||||
windows_script.to_string(),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
"/bin/sh".to_string(),
|
||||
"-c".to_string(),
|
||||
unix_script.to_string(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
fn windows_command_processor() -> String {
|
||||
std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string())
|
||||
}
|
||||
|
||||
fn test_runtime_paths() -> ExecServerRuntimeOptions {
|
||||
ExecServerRuntimeOptions::new(
|
||||
std::env::current_exe().expect("current exe"),
|
||||
/*codex_linux_sandbox_exe*/ None,
|
||||
)
|
||||
.expect("runtime paths")
|
||||
}
|
||||
|
||||
fn test_http_client_factory() -> HttpClientFactory {
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
}
|
||||
|
||||
async fn initialized_handler() -> Arc<ExecServerHandler> {
|
||||
let (outgoing_tx, _outgoing_rx) = mpsc::channel(16);
|
||||
let registry = SessionRegistry::new(crate::ExecServerTelemetry::default());
|
||||
let handler = Arc::new(ExecServerHandler::new(
|
||||
registry,
|
||||
CapabilityManager::new(crate::LocalFileSystem::default()),
|
||||
RpcNotificationSender::new(outgoing_tx),
|
||||
test_runtime_paths(),
|
||||
test_http_client_factory(),
|
||||
));
|
||||
let initialize_response = handler
|
||||
.initialize(InitializeParams {
|
||||
client_name: "exec-server-test".to_string(),
|
||||
resume_session_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("initialize");
|
||||
Uuid::parse_str(&initialize_response.session_id).expect("session id should be a UUID");
|
||||
handler.initialized().expect("initialized");
|
||||
handler
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicate_process_ids_allow_only_one_successful_start() {
|
||||
let handler = initialized_handler().await;
|
||||
let first_handler = Arc::clone(&handler);
|
||||
let second_handler = Arc::clone(&handler);
|
||||
|
||||
let (first, second) = tokio::join!(
|
||||
first_handler.exec(exec_params("proc-1"), /*launch_context*/ None),
|
||||
second_handler.exec(exec_params("proc-1"), /*launch_context*/ None),
|
||||
);
|
||||
|
||||
let (successes, failures): (Vec<_>, Vec<_>) =
|
||||
[first, second].into_iter().partition(Result::is_ok);
|
||||
assert_eq!(successes.len(), 1);
|
||||
assert_eq!(failures.len(), 1);
|
||||
|
||||
let error = failures
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("one failed request")
|
||||
.expect_err("expected duplicate process error");
|
||||
assert_eq!(error.code, -32600);
|
||||
assert_eq!(error.message, "process proc-1 already exists");
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(150)).await;
|
||||
handler.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminate_reports_false_after_process_exit() {
|
||||
let handler = initialized_handler().await;
|
||||
handler
|
||||
.exec(exec_params("proc-1"), /*launch_context*/ None)
|
||||
.await
|
||||
.expect("start process");
|
||||
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
loop {
|
||||
let response = handler
|
||||
.terminate(TerminateParams {
|
||||
process_id: ProcessId::from("proc-1"),
|
||||
})
|
||||
.await
|
||||
.expect("terminate response");
|
||||
if response == (TerminateResponse { running: false }) {
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
tokio::time::Instant::now() < deadline,
|
||||
"process should have exited within 1s"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
|
||||
handler.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn long_poll_read_fails_after_session_resume() {
|
||||
let (first_tx, _first_rx) = mpsc::channel(16);
|
||||
let registry = SessionRegistry::new(crate::ExecServerTelemetry::default());
|
||||
let first_handler = Arc::new(ExecServerHandler::new(
|
||||
Arc::clone(®istry),
|
||||
CapabilityManager::new(crate::LocalFileSystem::default()),
|
||||
RpcNotificationSender::new(first_tx),
|
||||
test_runtime_paths(),
|
||||
test_http_client_factory(),
|
||||
));
|
||||
let initialize_response = first_handler
|
||||
.initialize(InitializeParams {
|
||||
client_name: "exec-server-test".to_string(),
|
||||
resume_session_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("initialize");
|
||||
first_handler.initialized().expect("initialized");
|
||||
|
||||
// Keep the process quiet and alive so the pending read can only complete
|
||||
// after session resume, not because the process produced output or exited.
|
||||
first_handler
|
||||
.exec(
|
||||
exec_params_with_argv(
|
||||
"proc-long-poll",
|
||||
shell_argv("sleep 5", "ping -n 6 127.0.0.1 >NUL"),
|
||||
),
|
||||
/*launch_context*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("start process");
|
||||
|
||||
let first_read_handler = Arc::clone(&first_handler);
|
||||
let read_task = tokio::spawn(async move {
|
||||
first_read_handler
|
||||
.exec_read(ReadParams {
|
||||
process_id: ProcessId::from("proc-long-poll"),
|
||||
after_seq: None,
|
||||
max_bytes: None,
|
||||
wait_ms: Some(500),
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
first_handler.shutdown().await;
|
||||
|
||||
let (second_tx, _second_rx) = mpsc::channel(16);
|
||||
let second_handler = Arc::new(ExecServerHandler::new(
|
||||
registry,
|
||||
CapabilityManager::new(crate::LocalFileSystem::default()),
|
||||
RpcNotificationSender::new(second_tx),
|
||||
test_runtime_paths(),
|
||||
test_http_client_factory(),
|
||||
));
|
||||
second_handler
|
||||
.initialize(InitializeParams {
|
||||
client_name: "exec-server-test".to_string(),
|
||||
resume_session_id: Some(initialize_response.session_id),
|
||||
})
|
||||
.await
|
||||
.expect("initialize second connection");
|
||||
second_handler
|
||||
.initialized()
|
||||
.expect("initialized second connection");
|
||||
|
||||
let err = read_task
|
||||
.await
|
||||
.expect("read task should join")
|
||||
.expect_err("evicted long-poll read should fail");
|
||||
assert_eq!(err.code, -32600);
|
||||
assert_eq!(
|
||||
err.message,
|
||||
"session has been resumed by another connection"
|
||||
);
|
||||
|
||||
second_handler.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_session_resume_is_rejected() {
|
||||
let (first_tx, _first_rx) = mpsc::channel(16);
|
||||
let registry = SessionRegistry::new(crate::ExecServerTelemetry::default());
|
||||
let first_handler = Arc::new(ExecServerHandler::new(
|
||||
Arc::clone(®istry),
|
||||
CapabilityManager::new(crate::LocalFileSystem::default()),
|
||||
RpcNotificationSender::new(first_tx),
|
||||
test_runtime_paths(),
|
||||
test_http_client_factory(),
|
||||
));
|
||||
let initialize_response = first_handler
|
||||
.initialize(InitializeParams {
|
||||
client_name: "exec-server-test".to_string(),
|
||||
resume_session_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("initialize");
|
||||
|
||||
let (second_tx, _second_rx) = mpsc::channel(16);
|
||||
let second_handler = Arc::new(ExecServerHandler::new(
|
||||
registry,
|
||||
CapabilityManager::new(crate::LocalFileSystem::default()),
|
||||
RpcNotificationSender::new(second_tx),
|
||||
test_runtime_paths(),
|
||||
test_http_client_factory(),
|
||||
));
|
||||
let err = second_handler
|
||||
.initialize(InitializeParams {
|
||||
client_name: "exec-server-test".to_string(),
|
||||
resume_session_id: Some(initialize_response.session_id.clone()),
|
||||
})
|
||||
.await
|
||||
.expect_err("active session resume should fail");
|
||||
|
||||
assert_eq!(err.code, crate::rpc::SESSION_ALREADY_ATTACHED_ERROR_CODE);
|
||||
assert_eq!(
|
||||
err.message,
|
||||
format!(
|
||||
"session {} is already attached to another connection",
|
||||
initialize_response.session_id
|
||||
)
|
||||
);
|
||||
|
||||
first_handler.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn output_and_exit_are_retained_after_notification_receiver_closes() {
|
||||
let (outgoing_tx, outgoing_rx) = mpsc::channel(16);
|
||||
let handler = Arc::new(ExecServerHandler::new(
|
||||
SessionRegistry::new(crate::ExecServerTelemetry::default()),
|
||||
CapabilityManager::new(crate::LocalFileSystem::default()),
|
||||
RpcNotificationSender::new(outgoing_tx),
|
||||
test_runtime_paths(),
|
||||
test_http_client_factory(),
|
||||
));
|
||||
handler
|
||||
.initialize(InitializeParams {
|
||||
client_name: "exec-server-test".to_string(),
|
||||
resume_session_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("initialize");
|
||||
handler.initialized().expect("initialized");
|
||||
|
||||
let process_id = ProcessId::from("proc-notification-fail");
|
||||
handler
|
||||
.exec(
|
||||
exec_params_with_argv(
|
||||
process_id.as_str(),
|
||||
shell_argv(
|
||||
"sleep 0.05; printf 'first\\n'; sleep 0.05; printf 'second\\n'",
|
||||
"echo first&& ping -n 2 127.0.0.1 >NUL&& echo second",
|
||||
),
|
||||
),
|
||||
/*launch_context*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("start process");
|
||||
|
||||
drop(outgoing_rx);
|
||||
|
||||
let (output, exit_code) = read_process_until_closed(&handler, process_id.clone()).await;
|
||||
assert_eq!(output.replace("\r\n", "\n"), "first\nsecond\n");
|
||||
assert_eq!(exit_code, Some(0));
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
handler
|
||||
.exec(
|
||||
exec_params(process_id.as_str()),
|
||||
/*launch_context*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("process id should be reusable after exit retention");
|
||||
|
||||
handler.shutdown().await;
|
||||
}
|
||||
|
||||
async fn read_process_until_closed(
|
||||
handler: &ExecServerHandler,
|
||||
process_id: ProcessId,
|
||||
) -> (String, Option<i32>) {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
let mut output = String::new();
|
||||
let mut exit_code = None;
|
||||
let mut after_seq = None;
|
||||
|
||||
loop {
|
||||
let response: ReadResponse = handler
|
||||
.exec_read(ReadParams {
|
||||
process_id: process_id.clone(),
|
||||
after_seq,
|
||||
max_bytes: None,
|
||||
wait_ms: Some(500),
|
||||
})
|
||||
.await
|
||||
.expect("read process");
|
||||
|
||||
for chunk in response.chunks {
|
||||
output.push_str(&String::from_utf8_lossy(&chunk.chunk.into_inner()));
|
||||
after_seq = Some(chunk.seq);
|
||||
}
|
||||
if response.exited {
|
||||
exit_code = response.exit_code;
|
||||
}
|
||||
if response.closed {
|
||||
return (output, exit_code);
|
||||
}
|
||||
after_seq = response.next_seq.checked_sub(1).or(after_seq);
|
||||
assert!(
|
||||
tokio::time::Instant::now() < deadline,
|
||||
"process should close within 5s"
|
||||
);
|
||||
}
|
||||
}
|
||||
207
akode-rs/exec-server/src/server/missing_watch.rs
Normal file
207
akode-rs/exec-server/src/server/missing_watch.rs
Normal file
@@ -0,0 +1,207 @@
|
||||
//! Watches one missing-path observation per physical executor connection. Changes,
|
||||
//! supersession and transport loss invalidate the observation without a clock deadline.
|
||||
|
||||
use akode_exec_server_protocol::JSONRPCErrorError;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::collections::BTreeSet;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::os::unix::fs::OpenOptionsExt as _;
|
||||
use std::path::Path;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
use crate::protocol::FS_MISSING_CHANGED_METHOD;
|
||||
use crate::protocol::FsMissingChangedNotification;
|
||||
use crate::protocol::FsWatchMissingParams;
|
||||
use crate::protocol::FsWatchMissingResponse;
|
||||
use crate::rpc::RpcNotificationSender;
|
||||
|
||||
use notify::Event;
|
||||
use notify::EventKind;
|
||||
use notify::RecursiveMode;
|
||||
use notify::Watcher;
|
||||
#[cfg(target_os = "linux")]
|
||||
use tokio::io::Interest;
|
||||
#[cfg(target_os = "linux")]
|
||||
use tokio::io::unix::AsyncFd;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
const MAX_WATCH_PATHS: usize = 64;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct MissingWatch {
|
||||
id: u64,
|
||||
listener: Option<AbortOnDropHandle<()>>,
|
||||
}
|
||||
|
||||
impl MissingWatch {
|
||||
pub(super) fn register(
|
||||
&mut self,
|
||||
params: FsWatchMissingParams,
|
||||
notifications: RpcNotificationSender,
|
||||
shutdown: CancellationToken,
|
||||
) -> Result<FsWatchMissingResponse, JSONRPCErrorError> {
|
||||
let not_watching = FsWatchMissingResponse { watching: false };
|
||||
if params.watch_id <= self.id {
|
||||
return Ok(not_watching);
|
||||
}
|
||||
self.id = params.watch_id;
|
||||
self.listener.take();
|
||||
if !cfg!(target_os = "linux")
|
||||
|| params.missing.is_empty()
|
||||
|| params.missing.len() > MAX_WATCH_PATHS
|
||||
{
|
||||
return Ok(not_watching);
|
||||
}
|
||||
let watch_id = params.watch_id;
|
||||
let watch = match watch_missing(params) {
|
||||
Ok(Some(watch)) => watch,
|
||||
Ok(None) => return Ok(not_watching),
|
||||
Err(error) => {
|
||||
tracing::debug!(%error, "metadata watch unavailable; retaining live discovery");
|
||||
return Ok(not_watching);
|
||||
}
|
||||
};
|
||||
let changed = FsMissingChangedNotification { watch_id };
|
||||
self.listener = Some(AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => return,
|
||||
() = watch => {}
|
||||
}
|
||||
tracing::debug!(
|
||||
watch_id = changed.watch_id,
|
||||
"invalidating watched missing paths"
|
||||
);
|
||||
let _ = notifications
|
||||
.notify(FS_MISSING_CHANGED_METHOD, &changed)
|
||||
.await;
|
||||
})));
|
||||
Ok(FsWatchMissingResponse { watching: true })
|
||||
}
|
||||
}
|
||||
|
||||
/// Observe directory and mount changes before verifying the paths. Ancestor changes,
|
||||
/// mount changes, watcher errors and queue overflows invalidate the observation.
|
||||
fn watch_missing(
|
||||
params: FsWatchMissingParams,
|
||||
) -> io::Result<Option<impl Future<Output = ()> + Send>> {
|
||||
let missing = params
|
||||
.missing
|
||||
.iter()
|
||||
.map(|path| path.to_abs_path().map(AbsolutePathBuf::into_path_buf))
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
let present = params
|
||||
.present
|
||||
.map(|path| path.to_abs_path().map(AbsolutePathBuf::into_path_buf))
|
||||
.transpose()?;
|
||||
let mut parents = BTreeSet::new();
|
||||
let targets: Vec<_> = missing.iter().chain(&present).cloned().collect();
|
||||
for target in &targets {
|
||||
for parent in target.ancestors().skip(1) {
|
||||
parents.insert(parent.to_owned());
|
||||
if parents.len() > MAX_WATCH_PATHS {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
// inotify stays attached to a covered directory. Arm mount-table notifications
|
||||
// before installing directory watches and verifying the observed paths.
|
||||
#[cfg(target_os = "linux")]
|
||||
let mounts = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(libc::O_NONBLOCK)
|
||||
.open("/proc/self/mounts")
|
||||
.and_then(|file| AsyncFd::with_interest(file, Interest::PRIORITY))
|
||||
.inspect_err(
|
||||
|error| tracing::debug!(%error, "mount changes unavailable for missing-path watch"),
|
||||
)
|
||||
.ok();
|
||||
let (changed, invalidated) = oneshot::channel();
|
||||
let mut changed = Some(changed);
|
||||
let mut watcher = notify::recommended_watcher(move |event: notify::Result<Event>| {
|
||||
if event.as_ref().map_or(true, |event| {
|
||||
event.need_rescan()
|
||||
|| (!matches!(event.kind, EventKind::Access(_))
|
||||
&& (event.paths.is_empty()
|
||||
|| event.paths.iter().any(|path| {
|
||||
targets
|
||||
.iter()
|
||||
.any(|target| event_may_affect_target(path, target))
|
||||
})))
|
||||
}) && let Some(changed) = changed.take()
|
||||
{
|
||||
let _ = changed.send(());
|
||||
}
|
||||
})
|
||||
.map_err(io::Error::other)?;
|
||||
|
||||
// Ancestors sort before their descendants. If a missing parent is created during
|
||||
// setup its already-watched parent invalidates the observation. Reject symlinks:
|
||||
// their targets can change outside any of these directories.
|
||||
for parent in parents {
|
||||
match std::fs::symlink_metadata(&parent) {
|
||||
Ok(metadata) if metadata.is_dir() => {
|
||||
// inotify can accept a watch on a network mount yet never see changes
|
||||
// made by another host. Only reuse observations on local Linux filesystems.
|
||||
#[cfg(target_os = "linux")]
|
||||
if !matches!(
|
||||
rustix::fs::statfs(&parent)?.f_type as _,
|
||||
libc::EXT4_SUPER_MAGIC
|
||||
| 0x5846_5342 /* XFS_SUPER_MAGIC from linux/magic.h; absent in libc on musl */
|
||||
| libc::BTRFS_SUPER_MAGIC
|
||||
| libc::TMPFS_MAGIC
|
||||
| libc::OVERLAYFS_SUPER_MAGIC
|
||||
) {
|
||||
return Ok(None);
|
||||
}
|
||||
watcher
|
||||
.watch(&parent, RecursiveMode::NonRecursive)
|
||||
.map_err(io::Error::other)?;
|
||||
}
|
||||
Ok(_) => return Ok(None),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
for path in missing {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(_) => return Ok(None),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if let Some(path) = present {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if !metadata.is_symlink() => {}
|
||||
Ok(_) => return Ok(None),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Ok(Some(async move {
|
||||
let _directory_watcher = watcher;
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(mounts) = mounts {
|
||||
tokio::select! {
|
||||
_ = invalidated => {}
|
||||
_ = mounts.ready(Interest::PRIORITY) => {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let _ = invalidated.await;
|
||||
}))
|
||||
}
|
||||
|
||||
/// Events preserve the spelling that was written, even in casefolded directories.
|
||||
/// When either component is non-ASCII, let the next scan resolve Unicode aliases
|
||||
/// using the filesystem's own rules.
|
||||
fn event_may_affect_target(path: &Path, target: &Path) -> bool {
|
||||
let mut components = target.iter();
|
||||
path.iter().all(|name| {
|
||||
components.next().is_some_and(|expected| {
|
||||
name.eq_ignore_ascii_case(expected) || !name.is_ascii() || !expected.is_ascii()
|
||||
})
|
||||
})
|
||||
}
|
||||
81
akode-rs/exec-server/src/server/process_handler.rs
Normal file
81
akode-rs/exec-server/src/server/process_handler.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::process_telemetry::ProcessTelemetry;
|
||||
use akode_exec_server_protocol::JSONRPCErrorError;
|
||||
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::local_process::LocalProcess;
|
||||
use crate::protocol::ExecParams;
|
||||
use crate::protocol::ExecResponse;
|
||||
use crate::protocol::ReadParams;
|
||||
use crate::protocol::ReadResponse;
|
||||
use crate::protocol::SignalParams;
|
||||
use crate::protocol::SignalResponse;
|
||||
use crate::protocol::TerminateParams;
|
||||
use crate::protocol::TerminateResponse;
|
||||
use crate::protocol::WriteParams;
|
||||
use crate::protocol::WriteResponse;
|
||||
use crate::rpc::RpcNotificationSender;
|
||||
use crate::telemetry::ExecServerTelemetry;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ProcessHandler {
|
||||
process: LocalProcess,
|
||||
}
|
||||
|
||||
impl ProcessHandler {
|
||||
pub(crate) fn new(
|
||||
notifications: RpcNotificationSender,
|
||||
telemetry: ExecServerTelemetry,
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
output_retention: Duration,
|
||||
) -> Self {
|
||||
Self {
|
||||
process: LocalProcess::new(notifications, telemetry, runtime_paths, output_retention),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
self.process.shutdown().await;
|
||||
}
|
||||
|
||||
pub(crate) fn set_notification_sender(&self, notifications: Option<RpcNotificationSender>) {
|
||||
self.process.set_notification_sender(notifications);
|
||||
}
|
||||
|
||||
pub(crate) async fn exec(
|
||||
&self,
|
||||
params: ExecParams,
|
||||
telemetry: ProcessTelemetry,
|
||||
) -> Result<ExecResponse, JSONRPCErrorError> {
|
||||
self.process.exec(params, telemetry).await
|
||||
}
|
||||
|
||||
pub(crate) async fn exec_read(
|
||||
&self,
|
||||
params: ReadParams,
|
||||
) -> Result<ReadResponse, JSONRPCErrorError> {
|
||||
self.process.exec_read(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn exec_write(
|
||||
&self,
|
||||
params: WriteParams,
|
||||
) -> Result<WriteResponse, JSONRPCErrorError> {
|
||||
self.process.exec_write(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn signal(
|
||||
&self,
|
||||
params: SignalParams,
|
||||
) -> Result<SignalResponse, JSONRPCErrorError> {
|
||||
self.process.signal_process(params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn terminate(
|
||||
&self,
|
||||
params: TerminateParams,
|
||||
) -> Result<TerminateResponse, JSONRPCErrorError> {
|
||||
self.process.terminate_process(params).await
|
||||
}
|
||||
}
|
||||
666
akode-rs/exec-server/src/server/processor.rs
Normal file
666
akode-rs/exec-server/src/server/processor.rs
Normal file
@@ -0,0 +1,666 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_build_info::BuildInfo;
|
||||
use akode_exec_server_protocol::JSONRPCMessage;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use tracing::debug;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::LocalFileSystem;
|
||||
use crate::connection::CHANNEL_CAPACITY;
|
||||
use crate::connection::JsonRpcConnection;
|
||||
use crate::connection::JsonRpcConnectionEvent;
|
||||
use crate::discover_v2::capability_manager::CapabilityManager;
|
||||
use crate::rpc::RpcCallError;
|
||||
use crate::rpc::RpcNotificationSender;
|
||||
use crate::rpc::RpcServerOutboundMessage;
|
||||
use crate::rpc::encode_server_message;
|
||||
use crate::rpc_server_requests::RpcServerRequestSender;
|
||||
use crate::server::ExecServerHandler;
|
||||
use crate::server::RequestDispatchMode;
|
||||
use crate::server::registry::build_router;
|
||||
use crate::server::request_dispatcher::RequestDispatcher;
|
||||
use crate::server::request_dispatcher::RequestTaskResult;
|
||||
use crate::server::session_registry::SessionRegistry;
|
||||
use crate::telemetry::ConnectionTransport;
|
||||
use crate::telemetry::ExecServerTelemetry;
|
||||
use crate::telemetry::ExecutorRegistration;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ConnectionProcessor {
|
||||
capability_manager: Arc<CapabilityManager>,
|
||||
capability_prewarm: Arc<AbortOnDropHandle<()>>,
|
||||
session_registry: Arc<SessionRegistry>,
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
}
|
||||
|
||||
impl ConnectionProcessor {
|
||||
pub(crate) fn new_with_telemetry(
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
) -> Self {
|
||||
// Library callers may bypass CLI startup. Capture the version before serving clients.
|
||||
let _ = BuildInfo::get();
|
||||
let capability_manager =
|
||||
CapabilityManager::new(LocalFileSystem::with_runtime_paths(runtime_paths.clone()));
|
||||
let manager = Arc::clone(&capability_manager);
|
||||
// Start before any client connects; all sessions share these inert global locations.
|
||||
let prewarm = tokio::spawn(async move {
|
||||
// Home resolution failures are nonfatal, just like scan failures.
|
||||
if let Err(error) = manager.prewarm_locations().await {
|
||||
tracing::warn!(error_kind = ?error.kind(), "capability location prewarming unavailable");
|
||||
}
|
||||
});
|
||||
Self {
|
||||
session_registry: SessionRegistry::new(telemetry.clone()),
|
||||
capability_manager,
|
||||
capability_prewarm: Arc::new(AbortOnDropHandle::new(prewarm)),
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn run_connection(
|
||||
&self,
|
||||
connection: JsonRpcConnection,
|
||||
transport: ConnectionTransport,
|
||||
) {
|
||||
run_connection(
|
||||
connection,
|
||||
self.clone(),
|
||||
transport,
|
||||
/*executor_registration*/ None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(crate) async fn run_registered_connection(
|
||||
&self,
|
||||
connection: JsonRpcConnection,
|
||||
executor_registration: Option<Arc<ExecutorRegistration>>,
|
||||
) {
|
||||
run_connection(
|
||||
connection,
|
||||
self.clone(),
|
||||
ConnectionTransport::Relay,
|
||||
executor_registration,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
self.capability_prewarm.abort();
|
||||
self.session_registry.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_connection(
|
||||
connection: JsonRpcConnection,
|
||||
processor: ConnectionProcessor,
|
||||
transport: ConnectionTransport,
|
||||
executor_registration: Option<Arc<ExecutorRegistration>>,
|
||||
) {
|
||||
let ConnectionProcessor {
|
||||
capability_manager,
|
||||
capability_prewarm: _capability_prewarm,
|
||||
session_registry,
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
} = processor;
|
||||
let _connection_metrics = telemetry.connection_started(transport);
|
||||
let JsonRpcConnection {
|
||||
outgoing_tx: json_outgoing_tx,
|
||||
mut incoming_rx,
|
||||
mut disconnected_rx,
|
||||
task_handles: connection_tasks,
|
||||
transport: _transport,
|
||||
} = connection;
|
||||
let (outgoing_tx, mut outgoing_rx) =
|
||||
mpsc::channel::<RpcServerOutboundMessage>(CHANNEL_CAPACITY);
|
||||
let notifications = RpcNotificationSender::new(outgoing_tx.clone());
|
||||
let requests = notifications.request_sender();
|
||||
let mut handler = ExecServerHandler::new(
|
||||
session_registry,
|
||||
capability_manager,
|
||||
notifications,
|
||||
runtime_paths,
|
||||
http_client_factory,
|
||||
);
|
||||
handler.executor_registration = executor_registration;
|
||||
let handler = Arc::new(handler);
|
||||
|
||||
let outbound_task = tokio::spawn(async move {
|
||||
while let Some(message) = outgoing_rx.recv().await {
|
||||
let json_message = match encode_server_message(message) {
|
||||
Ok(json_message) => json_message,
|
||||
Err(err) => {
|
||||
warn!("failed to serialize exec-server outbound message: {err}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
if json_outgoing_tx.send(json_message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let mut dispatcher = RequestDispatcher::new(
|
||||
Arc::new(build_router()),
|
||||
Arc::clone(&handler),
|
||||
outgoing_tx.clone(),
|
||||
disconnected_rx.clone(),
|
||||
requests.clone(),
|
||||
telemetry,
|
||||
request_dispatch_mode,
|
||||
);
|
||||
|
||||
loop {
|
||||
let has_request_tasks = dispatcher.has_tasks();
|
||||
let event = tokio::select! {
|
||||
result = dispatcher.join_next(), if has_request_tasks => {
|
||||
if result == RequestTaskResult::ConnectionClosed {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ = disconnected_rx.changed() => {
|
||||
debug!("exec-server transport disconnected");
|
||||
break;
|
||||
}
|
||||
event = incoming_rx.recv() => {
|
||||
let Some(event) = event else {
|
||||
break;
|
||||
};
|
||||
event
|
||||
}
|
||||
};
|
||||
|
||||
if !handler.is_session_attached() {
|
||||
debug!("exec-server connection evicted after session resume");
|
||||
break;
|
||||
}
|
||||
|
||||
let result = match event {
|
||||
JsonRpcConnectionEvent::MalformedMessage { reason } => {
|
||||
dispatcher.handle_malformed_message(reason).await
|
||||
}
|
||||
JsonRpcConnectionEvent::Message(message) => match message {
|
||||
JSONRPCMessage::Request(request) => {
|
||||
dispatcher
|
||||
.dispatch_request(request, tracing::Span::none(), Instant::now())
|
||||
.await
|
||||
}
|
||||
JSONRPCMessage::Notification(notification) => {
|
||||
dispatcher.handle_notification(notification).await
|
||||
}
|
||||
JSONRPCMessage::Response(response) => dispatcher.handle_response(response),
|
||||
JSONRPCMessage::Error(error) => dispatcher.handle_error(error),
|
||||
},
|
||||
JsonRpcConnectionEvent::QueuedRequest {
|
||||
request,
|
||||
request_span,
|
||||
queued_at,
|
||||
} => {
|
||||
dispatcher
|
||||
.dispatch_request(request, request_span, queued_at)
|
||||
.await
|
||||
}
|
||||
JsonRpcConnectionEvent::Disconnected { reason } => {
|
||||
if let Some(reason) = reason {
|
||||
debug!("exec-server connection disconnected: {reason}");
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
if result == RequestTaskResult::ConnectionClosed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if *disconnected_rx.borrow() {
|
||||
complete_queued_client_responses(&requests, &mut incoming_rx);
|
||||
}
|
||||
requests.close();
|
||||
dispatcher.shutdown().await;
|
||||
handler.shutdown().await;
|
||||
drop(handler);
|
||||
drop(requests);
|
||||
drop(outgoing_tx);
|
||||
for task in connection_tasks {
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
let _ = outbound_task.await;
|
||||
}
|
||||
|
||||
fn complete_queued_client_responses(
|
||||
requests: &RpcServerRequestSender,
|
||||
incoming_rx: &mut mpsc::Receiver<JsonRpcConnectionEvent>,
|
||||
) {
|
||||
while let Ok(event) = incoming_rx.try_recv() {
|
||||
let (request_id, response) = match event {
|
||||
JsonRpcConnectionEvent::Message(JSONRPCMessage::Response(response)) => {
|
||||
(response.id, Ok(response.result))
|
||||
}
|
||||
JsonRpcConnectionEvent::Message(JSONRPCMessage::Error(error)) => {
|
||||
(error.id, Err(RpcCallError::Server(error.error)))
|
||||
}
|
||||
JsonRpcConnectionEvent::Message(
|
||||
JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_),
|
||||
)
|
||||
| JsonRpcConnectionEvent::QueuedRequest { .. }
|
||||
| JsonRpcConnectionEvent::MalformedMessage { .. }
|
||||
| JsonRpcConnectionEvent::Disconnected { .. } => continue,
|
||||
};
|
||||
if !requests.complete(request_id.clone(), response) {
|
||||
warn!("ignoring unexpected client response while disconnecting: {request_id:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_exec_server_protocol::JSONRPCMessage;
|
||||
use akode_exec_server_protocol::JSONRPCNotification;
|
||||
use akode_exec_server_protocol::JSONRPCRequest;
|
||||
use akode_exec_server_protocol::JSONRPCResponse;
|
||||
use akode_exec_server_protocol::RequestId;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::io::DuplexStream;
|
||||
use tokio::io::Lines;
|
||||
use tokio::io::duplex;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::complete_queued_client_responses;
|
||||
use super::run_connection;
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::ProcessId;
|
||||
use crate::connection::JsonRpcConnection;
|
||||
use crate::connection::JsonRpcConnectionEvent;
|
||||
use crate::protocol::ENVIRONMENT_INFO_METHOD;
|
||||
use crate::protocol::ENVIRONMENT_STATUS_METHOD;
|
||||
use crate::protocol::EXEC_METHOD;
|
||||
use crate::protocol::EXEC_READ_METHOD;
|
||||
use crate::protocol::EXEC_TERMINATE_METHOD;
|
||||
use crate::protocol::EnvironmentInfo;
|
||||
use crate::protocol::EnvironmentStatus;
|
||||
use crate::protocol::EnvironmentStatusKind;
|
||||
use crate::protocol::ExecParams;
|
||||
use crate::protocol::ExecResponse;
|
||||
use crate::protocol::ExecServerNetworkPolicyDecision;
|
||||
use crate::protocol::INITIALIZE_METHOD;
|
||||
use crate::protocol::INITIALIZED_METHOD;
|
||||
use crate::protocol::InitializeParams;
|
||||
use crate::protocol::InitializeResponse;
|
||||
use crate::protocol::NETWORK_POLICY_REQUEST_METHOD;
|
||||
use crate::protocol::NetworkPolicyRequestResponse;
|
||||
use crate::protocol::ReadParams;
|
||||
use crate::protocol::TerminateParams;
|
||||
use crate::protocol::TerminateResponse;
|
||||
use crate::rpc::RpcServerOutboundMessage;
|
||||
use crate::rpc_server_requests::RpcServerRequestSender;
|
||||
use crate::server::session_registry::SessionRegistry;
|
||||
|
||||
impl super::ConnectionProcessor {
|
||||
// Discovery tests supply fixture homes without changing the process environment.
|
||||
pub(crate) async fn seed_capability_locations(
|
||||
&self,
|
||||
request: crate::discover_v2::capability_locations::CapabilityLocationRequest,
|
||||
) -> std::io::Result<()> {
|
||||
self.capability_manager
|
||||
.seed_prewarmed_locations(request)
|
||||
.await
|
||||
}
|
||||
|
||||
// Connection-only tests do not prewarm or scan the real user home.
|
||||
pub(crate) fn new(runtime_paths: ExecServerRuntimeOptions) -> Self {
|
||||
let telemetry = crate::ExecServerTelemetry::default();
|
||||
Self {
|
||||
capability_manager: crate::discover_v2::capability_manager::CapabilityManager::new(
|
||||
crate::LocalFileSystem::with_runtime_paths(runtime_paths.clone()),
|
||||
),
|
||||
capability_prewarm: Arc::new(tokio_util::task::AbortOnDropHandle::new(
|
||||
tokio::spawn(async {}),
|
||||
)),
|
||||
session_registry: SessionRegistry::new(telemetry.clone()),
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory: akode_http_client::HttpClientFactory::new(
|
||||
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
request_dispatch_mode: crate::server::RequestDispatchMode::Inline,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_accepts_pipelined_scalar_requests() {
|
||||
let registry = SessionRegistry::new(crate::ExecServerTelemetry::default());
|
||||
let (mut writer, mut lines, task) = spawn_test_connection(registry, "pipelined-scalar");
|
||||
|
||||
send_request(
|
||||
&mut writer,
|
||||
/*id*/ 1,
|
||||
INITIALIZE_METHOD,
|
||||
&InitializeParams {
|
||||
client_name: "exec-server-test".to_string(),
|
||||
resume_session_id: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let _: InitializeResponse = read_response(&mut lines, /*expected_id*/ 1).await;
|
||||
send_notification(&mut writer, INITIALIZED_METHOD, &()).await;
|
||||
|
||||
send_request(&mut writer, /*id*/ 2, ENVIRONMENT_INFO_METHOD, &()).await;
|
||||
send_request(&mut writer, /*id*/ 3, ENVIRONMENT_INFO_METHOD, &()).await;
|
||||
send_request(&mut writer, /*id*/ 4, ENVIRONMENT_STATUS_METHOD, &()).await;
|
||||
|
||||
let _: EnvironmentInfo = read_response(&mut lines, /*expected_id*/ 2).await;
|
||||
let _: EnvironmentInfo = read_response(&mut lines, /*expected_id*/ 3).await;
|
||||
assert_eq!(
|
||||
read_response::<EnvironmentStatus>(&mut lines, /*expected_id*/ 4).await,
|
||||
EnvironmentStatus {
|
||||
status: EnvironmentStatusKind::Ready,
|
||||
}
|
||||
);
|
||||
|
||||
drop(writer);
|
||||
drop(lines);
|
||||
timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.expect("processor should exit")
|
||||
.expect("processor should join");
|
||||
}
|
||||
|
||||
/// A callback response received before EOF must survive transport shutdown.
|
||||
#[tokio::test]
|
||||
async fn disconnect_completes_queued_network_policy_response() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*buffer*/ 1);
|
||||
let requests = RpcServerRequestSender::new(outgoing_tx);
|
||||
let pending_request = {
|
||||
let requests = requests.clone();
|
||||
tokio::spawn(async move {
|
||||
requests
|
||||
.call_with_timeout::<_, NetworkPolicyRequestResponse>(
|
||||
NETWORK_POLICY_REQUEST_METHOD,
|
||||
&(),
|
||||
Duration::from_secs(1),
|
||||
)
|
||||
.await
|
||||
})
|
||||
};
|
||||
let RpcServerOutboundMessage::Request(request) = outgoing_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("network policy request should be queued")
|
||||
else {
|
||||
panic!("expected outbound network policy request");
|
||||
};
|
||||
|
||||
let (incoming_tx, mut incoming_rx) = mpsc::channel(/*buffer*/ 2);
|
||||
incoming_tx
|
||||
.try_send(JsonRpcConnectionEvent::Message(JSONRPCMessage::Response(
|
||||
JSONRPCResponse {
|
||||
id: request.id,
|
||||
result: serde_json::to_value(NetworkPolicyRequestResponse {
|
||||
decision: ExecServerNetworkPolicyDecision::Allow,
|
||||
})
|
||||
.expect("serialize network policy response"),
|
||||
},
|
||||
)))
|
||||
.expect("queue network policy response");
|
||||
incoming_tx
|
||||
.try_send(JsonRpcConnectionEvent::Disconnected { reason: None })
|
||||
.expect("queue transport disconnect");
|
||||
|
||||
complete_queued_client_responses(&requests, &mut incoming_rx);
|
||||
requests.close();
|
||||
|
||||
assert_eq!(
|
||||
pending_request
|
||||
.await
|
||||
.expect("network policy request should join")
|
||||
.expect("network policy request should complete"),
|
||||
NetworkPolicyRequestResponse {
|
||||
decision: ExecServerNetworkPolicyDecision::Allow,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transport_disconnect_detaches_session_during_in_flight_read() {
|
||||
let registry = SessionRegistry::new(crate::ExecServerTelemetry::default());
|
||||
let (mut first_writer, mut first_lines, first_task) =
|
||||
spawn_test_connection(Arc::clone(®istry), "first");
|
||||
|
||||
send_request(
|
||||
&mut first_writer,
|
||||
/*id*/ 1,
|
||||
INITIALIZE_METHOD,
|
||||
&InitializeParams {
|
||||
client_name: "exec-server-test".to_string(),
|
||||
resume_session_id: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let initialize_response: InitializeResponse =
|
||||
read_response(&mut first_lines, /*expected_id*/ 1).await;
|
||||
send_notification(&mut first_writer, INITIALIZED_METHOD, &()).await;
|
||||
|
||||
let process_id = ProcessId::from("proc-long-poll");
|
||||
send_request(
|
||||
&mut first_writer,
|
||||
/*id*/ 2,
|
||||
EXEC_METHOD,
|
||||
&exec_params(process_id.clone()),
|
||||
)
|
||||
.await;
|
||||
let _: ExecResponse = read_response(&mut first_lines, /*expected_id*/ 2).await;
|
||||
|
||||
send_request(
|
||||
&mut first_writer,
|
||||
/*id*/ 3,
|
||||
EXEC_READ_METHOD,
|
||||
&ReadParams {
|
||||
process_id: process_id.clone(),
|
||||
after_seq: None,
|
||||
max_bytes: None,
|
||||
wait_ms: Some(5_000),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
drop(first_writer);
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
|
||||
let (mut second_writer, mut second_lines, second_task) =
|
||||
spawn_test_connection(Arc::clone(®istry), "second");
|
||||
send_request(
|
||||
&mut second_writer,
|
||||
/*id*/ 1,
|
||||
INITIALIZE_METHOD,
|
||||
&InitializeParams {
|
||||
client_name: "exec-server-test".to_string(),
|
||||
resume_session_id: Some(initialize_response.session_id.clone()),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let second_initialize_response = timeout(
|
||||
Duration::from_secs(1),
|
||||
read_response::<InitializeResponse>(&mut second_lines, /*expected_id*/ 1),
|
||||
)
|
||||
.await
|
||||
.expect("resume initialize should not wait for the old read to finish");
|
||||
assert_eq!(
|
||||
second_initialize_response.session_id,
|
||||
initialize_response.session_id
|
||||
);
|
||||
timeout(Duration::from_secs(1), first_task)
|
||||
.await
|
||||
.expect("first processor should exit")
|
||||
.expect("first processor should join");
|
||||
send_notification(&mut second_writer, INITIALIZED_METHOD, &()).await;
|
||||
|
||||
send_request(
|
||||
&mut second_writer,
|
||||
/*id*/ 2,
|
||||
EXEC_TERMINATE_METHOD,
|
||||
&TerminateParams { process_id },
|
||||
)
|
||||
.await;
|
||||
let _: TerminateResponse = read_response(&mut second_lines, /*expected_id*/ 2).await;
|
||||
|
||||
drop(second_writer);
|
||||
drop(second_lines);
|
||||
timeout(Duration::from_secs(1), second_task)
|
||||
.await
|
||||
.expect("second processor should exit")
|
||||
.expect("second processor should join");
|
||||
}
|
||||
|
||||
fn spawn_test_connection(
|
||||
registry: Arc<SessionRegistry>,
|
||||
label: &str,
|
||||
) -> (DuplexStream, Lines<BufReader<DuplexStream>>, JoinHandle<()>) {
|
||||
let (client_writer, server_reader) = duplex(1 << 20);
|
||||
let (server_writer, client_reader) = duplex(1 << 20);
|
||||
let connection =
|
||||
JsonRpcConnection::from_stdio(server_reader, server_writer, label.to_string());
|
||||
let task = tokio::spawn(run_connection(
|
||||
connection,
|
||||
super::ConnectionProcessor {
|
||||
session_registry: registry,
|
||||
..super::ConnectionProcessor::new(test_runtime_paths())
|
||||
},
|
||||
crate::telemetry::ConnectionTransport::Stdio,
|
||||
/*executor_registration*/ None,
|
||||
));
|
||||
(client_writer, BufReader::new(client_reader).lines(), task)
|
||||
}
|
||||
|
||||
fn test_runtime_paths() -> ExecServerRuntimeOptions {
|
||||
ExecServerRuntimeOptions::new(
|
||||
std::env::current_exe().expect("current exe"),
|
||||
/*codex_linux_sandbox_exe*/ None,
|
||||
)
|
||||
.expect("runtime paths")
|
||||
}
|
||||
|
||||
async fn send_request<P: Serialize>(
|
||||
writer: &mut DuplexStream,
|
||||
id: i64,
|
||||
method: &str,
|
||||
params: &P,
|
||||
) {
|
||||
write_message(
|
||||
writer,
|
||||
&JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: RequestId::Integer(id),
|
||||
method: method.to_string(),
|
||||
params: Some(serde_json::to_value(params).expect("serialize params")),
|
||||
trace: None,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn send_notification<P: Serialize>(writer: &mut DuplexStream, method: &str, params: &P) {
|
||||
write_message(
|
||||
writer,
|
||||
&JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: method.to_string(),
|
||||
params: Some(serde_json::to_value(params).expect("serialize params")),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn write_message(writer: &mut DuplexStream, message: &JSONRPCMessage) {
|
||||
let encoded = serde_json::to_vec(message).expect("serialize JSON-RPC message");
|
||||
writer.write_all(&encoded).await.expect("write request");
|
||||
writer.write_all(b"\n").await.expect("write newline");
|
||||
}
|
||||
|
||||
async fn read_response<T: DeserializeOwned>(
|
||||
lines: &mut Lines<BufReader<DuplexStream>>,
|
||||
expected_id: i64,
|
||||
) -> T {
|
||||
let line = lines
|
||||
.next_line()
|
||||
.await
|
||||
.expect("read response")
|
||||
.expect("response line");
|
||||
match serde_json::from_str::<JSONRPCMessage>(&line).expect("decode JSON-RPC response") {
|
||||
JSONRPCMessage::Response(JSONRPCResponse { id, result }) => {
|
||||
assert_eq!(id, RequestId::Integer(expected_id));
|
||||
serde_json::from_value(result).expect("decode response result")
|
||||
}
|
||||
JSONRPCMessage::Error(error) => panic!("unexpected JSON-RPC error: {error:?}"),
|
||||
other => panic!("expected JSON-RPC response, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn exec_params(process_id: ProcessId) -> ExecParams {
|
||||
let mut env = HashMap::new();
|
||||
if let Some(path) = std::env::var_os("PATH") {
|
||||
env.insert("PATH".to_string(), path.to_string_lossy().into_owned());
|
||||
}
|
||||
ExecParams {
|
||||
metadata: Default::default(),
|
||||
process_id,
|
||||
argv: sleep_then_print_argv(),
|
||||
cwd: PathUri::from_host_native_path(std::env::current_dir().expect("cwd"))
|
||||
.expect("cwd URI"),
|
||||
shell_snapshot: None,
|
||||
env_policy: None,
|
||||
env,
|
||||
tty: false,
|
||||
pipe_stdin: false,
|
||||
arg0: None,
|
||||
sandbox: None,
|
||||
enforce_managed_network: false,
|
||||
managed_network: None,
|
||||
network_proxy: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn sleep_then_print_argv() -> Vec<String> {
|
||||
if cfg!(windows) {
|
||||
vec![
|
||||
std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string()),
|
||||
"/C".to_string(),
|
||||
"ping -n 3 127.0.0.1 >NUL && echo late".to_string(),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
"/bin/sh".to_string(),
|
||||
"-c".to_string(),
|
||||
"sleep 1; printf late".to_string(),
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
260
akode-rs/exec-server/src/server/registry.rs
Normal file
260
akode-rs/exec-server/src/server/registry.rs
Normal file
@@ -0,0 +1,260 @@
|
||||
use akode_file_system::FileSystemSandboxContext;
|
||||
use akode_file_system::WireFileSystemSandboxContext;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use opentelemetry::trace::TraceContextExt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::local_file_system::resolve_existing_path;
|
||||
use crate::protocol::CAPABILITIES_DISCOVER_V2_METHOD;
|
||||
use crate::protocol::CAPABILITY_ROOTS_DISCOVER_METHOD;
|
||||
use crate::protocol::DiscoverV2CapabilitiesRequest;
|
||||
use crate::protocol::ENVIRONMENT_CONFIG_READ_METHOD;
|
||||
use crate::protocol::ENVIRONMENT_INFO_METHOD;
|
||||
use crate::protocol::ENVIRONMENT_STATUS_METHOD;
|
||||
use crate::protocol::EXEC_METHOD;
|
||||
use crate::protocol::EXEC_READ_METHOD;
|
||||
use crate::protocol::EXEC_SIGNAL_METHOD;
|
||||
use crate::protocol::EXEC_TERMINATE_METHOD;
|
||||
use crate::protocol::EXEC_WRITE_METHOD;
|
||||
use crate::protocol::EnvironmentConfigReadParams;
|
||||
use crate::protocol::FS_CANONICALIZE_METHOD;
|
||||
use crate::protocol::FS_CLOSE_METHOD;
|
||||
use crate::protocol::FS_COPY_METHOD;
|
||||
use crate::protocol::FS_CREATE_DIRECTORY_METHOD;
|
||||
use crate::protocol::FS_GET_METADATA_METHOD;
|
||||
use crate::protocol::FS_OPEN_METHOD;
|
||||
use crate::protocol::FS_READ_BLOCK_METHOD;
|
||||
use crate::protocol::FS_READ_DIRECTORY_METHOD;
|
||||
use crate::protocol::FS_READ_FILE_METHOD;
|
||||
use crate::protocol::FS_REMOVE_METHOD;
|
||||
use crate::protocol::FS_WALK_METHOD;
|
||||
use crate::protocol::FS_WRITE_BLOCK_METHOD;
|
||||
use crate::protocol::FS_WRITE_FILE_METHOD;
|
||||
use crate::protocol::FsCloseParams;
|
||||
use crate::protocol::FsReadBlockParams;
|
||||
use crate::protocol::FsWriteBlockParams;
|
||||
use crate::protocol::HTTP_REQUEST_METHOD;
|
||||
use crate::protocol::HttpRequestParams;
|
||||
use crate::protocol::INITIALIZE_METHOD;
|
||||
use crate::protocol::INITIALIZED_METHOD;
|
||||
use crate::protocol::InitializeParams;
|
||||
use crate::protocol::JSONRPCErrorError;
|
||||
use crate::protocol::ReadParams;
|
||||
use crate::protocol::SignalParams;
|
||||
use crate::protocol::TerminateParams;
|
||||
use crate::protocol::WireCapabilityRootsDiscoverParams;
|
||||
use crate::protocol::WireExecParams;
|
||||
use crate::protocol::WireFsCanonicalizeParams;
|
||||
use crate::protocol::WireFsCopyParams;
|
||||
use crate::protocol::WireFsCreateDirectoryParams;
|
||||
use crate::protocol::WireFsGetMetadataParams;
|
||||
use crate::protocol::WireFsOpenParams;
|
||||
use crate::protocol::WireFsReadDirectoryParams;
|
||||
use crate::protocol::WireFsReadFileParams;
|
||||
use crate::protocol::WireFsRemoveParams;
|
||||
use crate::protocol::WireFsWalkParams;
|
||||
use crate::protocol::WireFsWriteFileParams;
|
||||
use crate::protocol::WriteParams;
|
||||
use crate::rpc::RpcRouter;
|
||||
use crate::rpc::internal_error;
|
||||
use crate::rpc::invalid_params;
|
||||
use crate::server::ExecServerHandler;
|
||||
|
||||
pub(crate) fn build_router() -> RpcRouter<ExecServerHandler> {
|
||||
let mut router = RpcRouter::new();
|
||||
router.notification(
|
||||
INITIALIZED_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, _params: serde_json::Value| async move {
|
||||
handler.initialized()
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
INITIALIZE_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: InitializeParams| async move {
|
||||
handler.initialize(params).await
|
||||
},
|
||||
);
|
||||
router.request_with_id(
|
||||
HTTP_REQUEST_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, request_id, params: HttpRequestParams| async move {
|
||||
handler.http_request(request_id, params).await
|
||||
},
|
||||
);
|
||||
router.request_with_trace(
|
||||
EXEC_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireExecParams, trace| async move {
|
||||
let launch_context = trace
|
||||
.as_ref()
|
||||
.and_then(akode_otel::context_from_w3c_trace_context)
|
||||
.map(|context| context.span().span_context().clone());
|
||||
handler.exec(params.into(), launch_context).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
ENVIRONMENT_INFO_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, _params: ()| async move { handler.environment_info() },
|
||||
);
|
||||
router.request(
|
||||
ENVIRONMENT_CONFIG_READ_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: EnvironmentConfigReadParams| async move {
|
||||
handler.environment_config_read(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
ENVIRONMENT_STATUS_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, _params: ()| async move { handler.environment_status() },
|
||||
);
|
||||
router.request(
|
||||
CAPABILITY_ROOTS_DISCOVER_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireCapabilityRootsDiscoverParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.discover_capability_roots(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
CAPABILITIES_DISCOVER_V2_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: DiscoverV2CapabilitiesRequest| async move {
|
||||
handler.discover_capabilities_v2(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
EXEC_READ_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: ReadParams| async move {
|
||||
handler.exec_read(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
EXEC_WRITE_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WriteParams| async move {
|
||||
handler.exec_write(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
EXEC_SIGNAL_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: SignalParams| async move {
|
||||
handler.signal(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
EXEC_TERMINATE_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: TerminateParams| async move {
|
||||
handler.terminate(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_READ_FILE_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsReadFileParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_read_file(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_OPEN_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsOpenParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_open(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_READ_BLOCK_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: FsReadBlockParams| async move {
|
||||
handler.fs_read_block(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_WRITE_BLOCK_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: FsWriteBlockParams| async move {
|
||||
handler.fs_write_block(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_CLOSE_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: FsCloseParams| async move {
|
||||
handler.fs_close(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_WRITE_FILE_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsWriteFileParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_write_file(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_CREATE_DIRECTORY_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsCreateDirectoryParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_create_directory(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
crate::protocol::FS_WATCH_MISSING_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: crate::protocol::FsWatchMissingParams| async move {
|
||||
handler.fs_watch_missing(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_GET_METADATA_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsGetMetadataParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_get_metadata(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_CANONICALIZE_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsCanonicalizeParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_canonicalize(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_READ_DIRECTORY_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsReadDirectoryParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_read_directory(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_WALK_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsWalkParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_walk(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_REMOVE_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsRemoveParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_remove(params).await
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
FS_COPY_METHOD,
|
||||
|handler: Arc<ExecServerHandler>, params: WireFsCopyParams| async move {
|
||||
let params = params.try_into_request(resolve_filesystem_sandbox)?;
|
||||
handler.fs_copy(params).await
|
||||
},
|
||||
);
|
||||
router
|
||||
}
|
||||
|
||||
fn resolve_filesystem_sandbox(
|
||||
sandbox: WireFileSystemSandboxContext,
|
||||
) -> Result<FileSystemSandboxContext, JSONRPCErrorError> {
|
||||
let cwd = if let Some(cwd) = sandbox.cwd() {
|
||||
cwd.clone()
|
||||
} else {
|
||||
if sandbox.requires_cwd() {
|
||||
return Err(invalid_params(
|
||||
"file system sandbox context with dynamic permissions requires cwd".to_string(),
|
||||
));
|
||||
}
|
||||
// Legacy filesystem clients omitted cwd only for these policies. Preserve the executor's
|
||||
// own default (and Windows drive/share), rather than using the requested path.
|
||||
std::env::current_dir()
|
||||
.and_then(|cwd| resolve_existing_path(&cwd))
|
||||
.and_then(PathUri::from_host_native_path)
|
||||
.map_err(|err| internal_error(err.to_string()))?
|
||||
};
|
||||
Ok(sandbox.into_context(cwd))
|
||||
}
|
||||
12
akode-rs/exec-server/src/server/release_version.rs
Normal file
12
akode-rs/exec-server/src/server/release_version.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
//! Include the startup-cached package release version in executor metadata.
|
||||
|
||||
use akode_build_info::BuildInfo;
|
||||
|
||||
use crate::protocol::EnvironmentInfo;
|
||||
|
||||
pub(super) fn local_environment_info() -> EnvironmentInfo {
|
||||
EnvironmentInfo {
|
||||
executor_version: BuildInfo::get().version().to_string(),
|
||||
..EnvironmentInfo::local()
|
||||
}
|
||||
}
|
||||
395
akode-rs/exec-server/src/server/request_dispatcher.rs
Normal file
395
akode-rs/exec-server/src/server/request_dispatcher.rs
Normal file
@@ -0,0 +1,395 @@
|
||||
use std::num::NonZeroUsize;
|
||||
use std::num::ParseIntError;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_exec_server_protocol::JSONRPCError;
|
||||
use akode_exec_server_protocol::JSONRPCNotification;
|
||||
use akode_exec_server_protocol::JSONRPCRequest;
|
||||
use akode_exec_server_protocol::JSONRPCResponse;
|
||||
use akode_exec_server_protocol::RequestId;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinSet;
|
||||
use tracing::Instrument;
|
||||
use tracing::debug;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::protocol::ENVIRONMENT_INFO_METHOD;
|
||||
use crate::protocol::ENVIRONMENT_STATUS_METHOD;
|
||||
use crate::protocol::EXEC_SIGNAL_METHOD;
|
||||
use crate::protocol::EXEC_TERMINATE_METHOD;
|
||||
use crate::protocol::FS_CLOSE_METHOD;
|
||||
use crate::protocol::INITIALIZE_METHOD;
|
||||
use crate::protocol::INITIALIZED_METHOD;
|
||||
use crate::rpc::RpcCallError;
|
||||
use crate::rpc::RpcRouter;
|
||||
use crate::rpc::RpcServerOutboundMessage;
|
||||
use crate::rpc::invalid_request;
|
||||
use crate::rpc::method_not_found;
|
||||
use crate::rpc_server_requests::RpcServerRequestSender;
|
||||
use crate::server::ExecServerHandler;
|
||||
use crate::telemetry::ExecServerTelemetry;
|
||||
|
||||
pub(super) struct RequestDispatcher {
|
||||
router: Arc<RpcRouter<ExecServerHandler>>,
|
||||
handler: Arc<ExecServerHandler>,
|
||||
outgoing_tx: mpsc::Sender<RpcServerOutboundMessage>,
|
||||
disconnected_rx: watch::Receiver<bool>,
|
||||
requests: RpcServerRequestSender,
|
||||
telemetry: ExecServerTelemetry,
|
||||
lanes: Option<RequestLanes>,
|
||||
tasks: JoinSet<RequestTaskResult>,
|
||||
initialized: bool,
|
||||
}
|
||||
|
||||
impl RequestDispatcher {
|
||||
pub(super) fn new(
|
||||
router: Arc<RpcRouter<ExecServerHandler>>,
|
||||
handler: Arc<ExecServerHandler>,
|
||||
outgoing_tx: mpsc::Sender<RpcServerOutboundMessage>,
|
||||
disconnected_rx: watch::Receiver<bool>,
|
||||
requests: RpcServerRequestSender,
|
||||
telemetry: ExecServerTelemetry,
|
||||
mode: RequestDispatchMode,
|
||||
) -> Self {
|
||||
let lanes = match mode {
|
||||
RequestDispatchMode::Inline => None,
|
||||
RequestDispatchMode::Concurrent {
|
||||
max_concurrent_requests,
|
||||
} => Some(RequestLanes {
|
||||
ordinary: Arc::new(Semaphore::new(max_concurrent_requests.get())),
|
||||
control: Arc::new(Semaphore::new(max_concurrent_requests.get())),
|
||||
}),
|
||||
};
|
||||
|
||||
Self {
|
||||
router,
|
||||
handler,
|
||||
outgoing_tx,
|
||||
disconnected_rx,
|
||||
requests,
|
||||
telemetry,
|
||||
lanes,
|
||||
tasks: JoinSet::new(),
|
||||
initialized: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn has_tasks(&self) -> bool {
|
||||
!self.tasks.is_empty()
|
||||
}
|
||||
|
||||
pub(super) async fn join_next(&mut self) -> RequestTaskResult {
|
||||
match self.tasks.join_next().await {
|
||||
Some(Ok(result)) => result,
|
||||
Some(Err(error)) => {
|
||||
warn!("exec-server request task failed: {error}");
|
||||
RequestTaskResult::ConnectionClosed
|
||||
}
|
||||
None => RequestTaskResult::Completed,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn handle_malformed_message(&self, reason: String) -> RequestTaskResult {
|
||||
warn!("ignoring malformed exec-server message: {reason}");
|
||||
if self
|
||||
.outgoing_tx
|
||||
.send(RpcServerOutboundMessage::Error {
|
||||
request_id: RequestId::Integer(-1),
|
||||
error: invalid_request(reason),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
}
|
||||
|
||||
RequestTaskResult::Completed
|
||||
}
|
||||
|
||||
pub(super) async fn handle_notification(
|
||||
&mut self,
|
||||
notification: JSONRPCNotification,
|
||||
) -> RequestTaskResult {
|
||||
let is_initialized = notification.method == INITIALIZED_METHOD;
|
||||
let Some(route) = self.router.notification_route(notification.method.as_str()) else {
|
||||
warn!(
|
||||
"closing exec-server connection after unexpected notification: {}",
|
||||
notification.method
|
||||
);
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
};
|
||||
let result = tokio::select! {
|
||||
result = route(Arc::clone(&self.handler), notification) => result,
|
||||
_ = self.disconnected_rx.changed() => {
|
||||
debug!("exec-server transport disconnected while handling notification");
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
}
|
||||
};
|
||||
if let Err(error) = result {
|
||||
warn!("closing exec-server connection after protocol error: {error}");
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
}
|
||||
if is_initialized {
|
||||
self.initialized = true;
|
||||
}
|
||||
|
||||
RequestTaskResult::Completed
|
||||
}
|
||||
|
||||
pub(super) fn handle_response(&self, response: JSONRPCResponse) -> RequestTaskResult {
|
||||
if !self
|
||||
.requests
|
||||
.complete(response.id.clone(), Ok(response.result))
|
||||
{
|
||||
warn!(
|
||||
"closing exec-server connection after unexpected client response: {:?}",
|
||||
response.id
|
||||
);
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
}
|
||||
|
||||
RequestTaskResult::Completed
|
||||
}
|
||||
|
||||
pub(super) fn handle_error(&self, error: JSONRPCError) -> RequestTaskResult {
|
||||
if !self
|
||||
.requests
|
||||
.complete(error.id.clone(), Err(RpcCallError::Server(error.error)))
|
||||
{
|
||||
warn!(
|
||||
"closing exec-server connection after unexpected client error: {:?}",
|
||||
error.id
|
||||
);
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
}
|
||||
|
||||
RequestTaskResult::Completed
|
||||
}
|
||||
|
||||
pub(super) async fn dispatch_request(
|
||||
&mut self,
|
||||
request: JSONRPCRequest,
|
||||
request_span: tracing::Span,
|
||||
queued_at: Instant,
|
||||
) -> RequestTaskResult {
|
||||
let started_at = Instant::now();
|
||||
let Some((method, route)) = self.router.request_route(request.method.as_str()) else {
|
||||
let method = "unknown";
|
||||
self.telemetry
|
||||
.request_queue_completed(method, queued_at.elapsed());
|
||||
request_span.record("otel.name", method);
|
||||
request_span.record(
|
||||
"rpc.dispatch_offset_ns",
|
||||
i64::try_from(queued_at.elapsed().as_nanos()).unwrap_or(i64::MAX),
|
||||
);
|
||||
if self
|
||||
.outgoing_tx
|
||||
.send(RpcServerOutboundMessage::Error {
|
||||
request_id: request.id,
|
||||
error: method_not_found(format!(
|
||||
"exec-server stub does not implement `{}` yet",
|
||||
request.method
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
request_span.record("result", "disconnected");
|
||||
self.telemetry.request_completed(
|
||||
method,
|
||||
"disconnected",
|
||||
started_at.elapsed(),
|
||||
queued_at.elapsed(),
|
||||
);
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
}
|
||||
request_span.record(
|
||||
"rpc.response_enqueue_offset_ns",
|
||||
i64::try_from(queued_at.elapsed().as_nanos()).unwrap_or(i64::MAX),
|
||||
);
|
||||
request_span.record("result", "error");
|
||||
self.telemetry.request_completed(
|
||||
method,
|
||||
"error",
|
||||
started_at.elapsed(),
|
||||
queued_at.elapsed(),
|
||||
);
|
||||
return RequestTaskResult::Completed;
|
||||
};
|
||||
|
||||
request_span.record("otel.name", method);
|
||||
let route_setup_started_at = Instant::now();
|
||||
let route = route(Arc::clone(&self.handler), request);
|
||||
let route_setup_duration = route_setup_started_at.elapsed();
|
||||
let outgoing_tx = self.outgoing_tx.clone();
|
||||
let mut disconnected_rx = self.disconnected_rx.clone();
|
||||
let telemetry = self.telemetry.clone();
|
||||
let task = async move {
|
||||
request_span.record(
|
||||
"rpc.dispatch_offset_ns",
|
||||
i64::try_from(queued_at.elapsed().as_nanos()).unwrap_or(i64::MAX),
|
||||
);
|
||||
telemetry.request_queue_completed(
|
||||
method,
|
||||
queued_at.elapsed().saturating_sub(route_setup_duration),
|
||||
);
|
||||
let message = tokio::select! {
|
||||
message = route.instrument(request_span.clone()) => message,
|
||||
_ = disconnected_rx.changed() => {
|
||||
request_span.record("result", "disconnected");
|
||||
telemetry.request_completed(
|
||||
method,
|
||||
"disconnected",
|
||||
started_at.elapsed(),
|
||||
queued_at.elapsed(),
|
||||
);
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
}
|
||||
};
|
||||
let result = request_result(&message);
|
||||
let response_sent = match message {
|
||||
Some(message) => {
|
||||
let response_sent = tokio::select! {
|
||||
result = outgoing_tx.send(message) => result.is_ok(),
|
||||
_ = disconnected_rx.changed() => false,
|
||||
};
|
||||
if response_sent {
|
||||
request_span.record(
|
||||
"rpc.response_enqueue_offset_ns",
|
||||
i64::try_from(queued_at.elapsed().as_nanos()).unwrap_or(i64::MAX),
|
||||
);
|
||||
}
|
||||
response_sent
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if !response_sent {
|
||||
request_span.record("result", "disconnected");
|
||||
telemetry.request_completed(
|
||||
method,
|
||||
"disconnected",
|
||||
started_at.elapsed(),
|
||||
queued_at.elapsed(),
|
||||
);
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
}
|
||||
request_span.record("result", result);
|
||||
telemetry.request_completed(method, result, started_at.elapsed(), queued_at.elapsed());
|
||||
RequestTaskResult::Completed
|
||||
};
|
||||
|
||||
let Some(RequestLanes { ordinary, control }) = &self.lanes else {
|
||||
// Keep requests ordered when concurrent dispatch is not enabled.
|
||||
return task.await;
|
||||
};
|
||||
// Finish the handshake before concurrent requests can observe session state.
|
||||
if method == INITIALIZE_METHOD || !self.initialized {
|
||||
return task.await;
|
||||
}
|
||||
|
||||
// Reserve capacity for health checks and cleanup while ordinary requests are blocked.
|
||||
let admission = if matches!(
|
||||
method,
|
||||
ENVIRONMENT_INFO_METHOD
|
||||
| ENVIRONMENT_STATUS_METHOD
|
||||
| EXEC_SIGNAL_METHOD
|
||||
| EXEC_TERMINATE_METHOD
|
||||
| FS_CLOSE_METHOD
|
||||
) {
|
||||
Arc::clone(control)
|
||||
} else {
|
||||
Arc::clone(ordinary)
|
||||
};
|
||||
|
||||
// TODO(anp) bound queued request bytes without blocking later responses or cleanup.
|
||||
self.tasks.spawn(async move {
|
||||
let Ok(_permit) = admission.acquire_owned().await else {
|
||||
return RequestTaskResult::ConnectionClosed;
|
||||
};
|
||||
task.await
|
||||
});
|
||||
RequestTaskResult::Completed
|
||||
}
|
||||
|
||||
pub(super) async fn shutdown(mut self) {
|
||||
self.tasks.abort_all();
|
||||
while self.tasks.join_next().await.is_some() {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-connection request dispatch policy for local and remote exec-servers.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum RequestDispatchMode {
|
||||
Inline,
|
||||
Concurrent {
|
||||
max_concurrent_requests: ConcurrentRequestLimit,
|
||||
},
|
||||
}
|
||||
|
||||
/// A valid request concurrency limit accepted by Tokio's semaphore.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct ConcurrentRequestLimit(usize);
|
||||
|
||||
impl ConcurrentRequestLimit {
|
||||
/// Returns a limit when it enables concurrency and fits Tokio's semaphore.
|
||||
pub fn new(max_concurrent_requests: usize) -> Option<Self> {
|
||||
if !(2..=Semaphore::MAX_PERMITS).contains(&max_concurrent_requests) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Self(max_concurrent_requests))
|
||||
}
|
||||
|
||||
/// Returns the validated number of concurrent requests.
|
||||
pub fn get(self) -> usize {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for RequestDispatchMode {
|
||||
type Err = ParseIntError;
|
||||
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
let max_concurrent_requests = value.parse::<NonZeroUsize>()?.get();
|
||||
if max_concurrent_requests == 1 {
|
||||
Ok(Self::Inline)
|
||||
} else {
|
||||
Ok(Self::Concurrent {
|
||||
max_concurrent_requests: ConcurrentRequestLimit(
|
||||
max_concurrent_requests.min(Semaphore::MAX_PERMITS),
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RequestLanes {
|
||||
ordinary: Arc<Semaphore>,
|
||||
control: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq)]
|
||||
pub(super) enum RequestTaskResult {
|
||||
Completed,
|
||||
ConnectionClosed,
|
||||
}
|
||||
|
||||
fn request_result(message: &Option<RpcServerOutboundMessage>) -> &'static str {
|
||||
match message {
|
||||
Some(RpcServerOutboundMessage::Error { .. }) => "error",
|
||||
Some(
|
||||
RpcServerOutboundMessage::Request(_)
|
||||
| RpcServerOutboundMessage::Response { .. }
|
||||
| RpcServerOutboundMessage::Notification(_),
|
||||
)
|
||||
| None => "success",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "request_dispatcher_tests.rs"]
|
||||
mod tests;
|
||||
569
akode-rs/exec-server/src/server/request_dispatcher_tests.rs
Normal file
569
akode-rs/exec-server/src/server/request_dispatcher_tests.rs
Normal file
@@ -0,0 +1,569 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_exec_server_protocol::JSONRPCMessage;
|
||||
use akode_exec_server_protocol::JSONRPCRequest;
|
||||
use akode_exec_server_protocol::RequestId;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
use akode_http_client::OutboundProxyPolicy;
|
||||
use akode_otel::MetricsClient;
|
||||
use akode_otel::MetricsConfig;
|
||||
use opentelemetry::trace::SpanId;
|
||||
use opentelemetry::trace::TraceId;
|
||||
use opentelemetry::trace::TracerProvider as _;
|
||||
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::trace::InMemorySpanExporter;
|
||||
use opentelemetry_sdk::trace::SdkTracerProvider;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::watch;
|
||||
use tokio::time::timeout;
|
||||
use tracing_subscriber::filter::filter_fn;
|
||||
use tracing_subscriber::prelude::*;
|
||||
|
||||
use super::ConcurrentRequestLimit;
|
||||
use super::RequestDispatchMode;
|
||||
use super::RequestDispatcher;
|
||||
use super::RequestTaskResult;
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::connection::JsonRpcConnectionEvent;
|
||||
use crate::discover_v2::capability_manager::CapabilityManager;
|
||||
use crate::rpc::RpcNotificationSender;
|
||||
use crate::rpc::RpcRouter;
|
||||
use crate::rpc::RpcServerOutboundMessage;
|
||||
use crate::rpc::invalid_request;
|
||||
use crate::server::ExecServerHandler;
|
||||
use crate::server::session_registry::SessionRegistry;
|
||||
use crate::telemetry::ExecServerTelemetry;
|
||||
|
||||
/// Public limits reject values that cannot safely enable semaphore-backed concurrency.
|
||||
#[test]
|
||||
fn concurrent_request_limit_rejects_invalid_values() {
|
||||
assert_eq!(
|
||||
ConcurrentRequestLimit::new(/*max_concurrent_requests*/ 0),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
ConcurrentRequestLimit::new(/*max_concurrent_requests*/ 1),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
ConcurrentRequestLimit::new(Semaphore::MAX_PERMITS.saturating_add(1)),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
ConcurrentRequestLimit::new(/*max_concurrent_requests*/ 2).map(ConcurrentRequestLimit::get),
|
||||
Some(2)
|
||||
);
|
||||
}
|
||||
|
||||
/// CLI parsing keeps one request inline and bounds larger positive concurrency limits.
|
||||
#[test]
|
||||
fn request_dispatch_mode_parses_bounded_concurrency() {
|
||||
assert!(matches!("1".parse(), Ok(RequestDispatchMode::Inline)));
|
||||
assert!("0".parse::<RequestDispatchMode>().is_err());
|
||||
|
||||
let oversized_limit = Semaphore::MAX_PERMITS.saturating_add(1).to_string();
|
||||
let mode = oversized_limit
|
||||
.parse::<RequestDispatchMode>()
|
||||
.expect("parse oversized concurrent request limit");
|
||||
let RequestDispatchMode::Concurrent {
|
||||
max_concurrent_requests,
|
||||
} = mode
|
||||
else {
|
||||
panic!("expected concurrent request dispatch");
|
||||
};
|
||||
assert_eq!(max_concurrent_requests.get(), Semaphore::MAX_PERMITS);
|
||||
}
|
||||
|
||||
/// End-to-end request spans retain the wire method and inbound trace with bounded names.
|
||||
#[test]
|
||||
fn request_span_uses_bounded_name_wire_method_and_inbound_trace_parent() {
|
||||
let span_exporter = InMemorySpanExporter::default();
|
||||
let tracer_provider = SdkTracerProvider::builder()
|
||||
.with_simple_exporter(span_exporter.clone())
|
||||
.build();
|
||||
let tracer = tracer_provider.tracer("exec-server-test");
|
||||
let subscriber = tracing_subscriber::registry().with(
|
||||
tracing_opentelemetry::layer()
|
||||
.with_tracer(tracer)
|
||||
.with_filter(filter_fn(akode_otel::trace_export_filter)),
|
||||
);
|
||||
let trace_id = TraceId::from_hex("00000000000000000000000000000001").expect("trace id");
|
||||
let parent_span_id = SpanId::from_hex("0000000000000002").expect("span id");
|
||||
let trace = akode_protocol::protocol::W3cTraceContext {
|
||||
traceparent: Some(format!("00-{trace_id}-{parent_span_id}-01")),
|
||||
tracestate: None,
|
||||
};
|
||||
|
||||
let method = "custom/method";
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
tracing::callsite::rebuild_interest_cache();
|
||||
let request = JSONRPCRequest {
|
||||
id: RequestId::Integer(1),
|
||||
method: method.to_string(),
|
||||
params: None,
|
||||
trace: Some(trace),
|
||||
};
|
||||
let JsonRpcConnectionEvent::QueuedRequest { request_span, .. } =
|
||||
JsonRpcConnectionEvent::message(JSONRPCMessage::Request(request))
|
||||
else {
|
||||
panic!("requests should start a server span before dispatch");
|
||||
};
|
||||
assert!(
|
||||
span_exporter
|
||||
.get_finished_spans()
|
||||
.expect("request span export")
|
||||
.is_empty(),
|
||||
"the request span must remain open while the request is waiting"
|
||||
);
|
||||
request_span.record("otel.name", "unknown");
|
||||
request_span.in_scope(|| {});
|
||||
drop(request_span);
|
||||
});
|
||||
|
||||
tracer_provider.force_flush().expect("flush traces");
|
||||
let spans = span_exporter.get_finished_spans().expect("span export");
|
||||
assert_eq!(spans.len(), 1);
|
||||
let request_span = spans
|
||||
.iter()
|
||||
.find(|span| span.name.as_ref() == "unknown")
|
||||
.expect("unknown method span");
|
||||
assert_eq!(
|
||||
request_span
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|attribute| attribute.key.as_str() == "method")
|
||||
.map(|attribute| attribute.value.clone()),
|
||||
Some(opentelemetry::Value::String(method.into()))
|
||||
);
|
||||
assert_eq!(request_span.span_context.trace_id(), trace_id);
|
||||
assert_eq!(request_span.parent_span_id, parent_span_id);
|
||||
}
|
||||
|
||||
/// Total request timing includes queueing without changing dispatch or queue timing.
|
||||
#[tokio::test]
|
||||
async fn request_queue_waits_for_dispatcher_admission_before_recording_telemetry() {
|
||||
let span_exporter = InMemorySpanExporter::default();
|
||||
let tracer_provider = SdkTracerProvider::builder()
|
||||
.with_simple_exporter(span_exporter.clone())
|
||||
.build();
|
||||
let subscriber = tracing_subscriber::registry().with(
|
||||
tracing_opentelemetry::layer()
|
||||
.with_tracer(tracer_provider.tracer("exec-server-test"))
|
||||
.with_filter(filter_fn(akode_otel::trace_export_filter)),
|
||||
);
|
||||
let _subscriber = tracing::subscriber::set_default(subscriber);
|
||||
tracing::callsite::rebuild_interest_cache();
|
||||
|
||||
let metrics = MetricsClient::new(
|
||||
MetricsConfig::in_memory(
|
||||
"test",
|
||||
"akode-exec-server",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
InMemoryMetricExporter::default(),
|
||||
)
|
||||
.with_runtime_reader(),
|
||||
)
|
||||
.expect("metrics client");
|
||||
let telemetry = ExecServerTelemetry::new(metrics.clone());
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*buffer*/ 1);
|
||||
let notifications = RpcNotificationSender::new(outgoing_tx.clone());
|
||||
let requests = notifications.request_sender();
|
||||
let handler = Arc::new(ExecServerHandler::new(
|
||||
SessionRegistry::new(telemetry.clone()),
|
||||
CapabilityManager::new(crate::LocalFileSystem::default()),
|
||||
notifications,
|
||||
ExecServerRuntimeOptions::new(
|
||||
std::env::current_exe().expect("current executable"),
|
||||
/*codex_linux_sandbox_exe*/ None,
|
||||
)
|
||||
.expect("runtime paths"),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
));
|
||||
let mut router = RpcRouter::new();
|
||||
let execution_started = Arc::new(Notify::new());
|
||||
let release_execution = Arc::new(Notify::new());
|
||||
let notify_execution_started = Arc::clone(&execution_started);
|
||||
let wait_for_execution_release = Arc::clone(&release_execution);
|
||||
let route_setup_duration = Duration::from_millis(200);
|
||||
router.request(
|
||||
"test/queued",
|
||||
move |_handler: Arc<ExecServerHandler>, _params: ()| {
|
||||
let execution_started = Arc::clone(¬ify_execution_started);
|
||||
let release_execution = Arc::clone(&wait_for_execution_release);
|
||||
std::thread::sleep(route_setup_duration);
|
||||
async move {
|
||||
execution_started.notify_one();
|
||||
release_execution.notified().await;
|
||||
Ok::<_, akode_exec_server_protocol::JSONRPCErrorError>(())
|
||||
}
|
||||
},
|
||||
);
|
||||
let (_disconnected_tx, disconnected_rx) = watch::channel(/*init*/ false);
|
||||
let mut dispatcher = RequestDispatcher::new(
|
||||
Arc::new(router),
|
||||
handler,
|
||||
outgoing_tx,
|
||||
disconnected_rx,
|
||||
requests,
|
||||
telemetry,
|
||||
RequestDispatchMode::Concurrent {
|
||||
max_concurrent_requests: ConcurrentRequestLimit::new(
|
||||
/*max_concurrent_requests*/ 2,
|
||||
)
|
||||
.expect("valid request limit"),
|
||||
},
|
||||
);
|
||||
dispatcher.initialized = true;
|
||||
let admission = Arc::clone(
|
||||
&dispatcher
|
||||
.lanes
|
||||
.as_ref()
|
||||
.expect("concurrent request lanes")
|
||||
.ordinary,
|
||||
);
|
||||
let occupied_permits = admission
|
||||
.acquire_many_owned(/*n*/ 2)
|
||||
.await
|
||||
.expect("occupy the request admission lane");
|
||||
let JsonRpcConnectionEvent::QueuedRequest {
|
||||
request,
|
||||
request_span,
|
||||
queued_at,
|
||||
} = JsonRpcConnectionEvent::message(JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: RequestId::Integer(1),
|
||||
method: "test/queued".to_string(),
|
||||
params: None,
|
||||
trace: None,
|
||||
}))
|
||||
else {
|
||||
panic!("requests should start a server span before dispatch");
|
||||
};
|
||||
|
||||
assert!(matches!(
|
||||
dispatcher
|
||||
.dispatch_request(request, request_span, queued_at)
|
||||
.await,
|
||||
RequestTaskResult::Completed
|
||||
));
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
|
||||
assert!(
|
||||
span_exporter
|
||||
.get_finished_spans()
|
||||
.expect("request span export")
|
||||
.is_empty(),
|
||||
"the end-to-end request span must remain open before admission"
|
||||
);
|
||||
let queued_snapshot = metrics.snapshot().expect("queued metrics snapshot");
|
||||
assert!(
|
||||
!queued_snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
.any(|metric| metric.name() == "exec_server_request_queue_duration_seconds"),
|
||||
"queue latency must not be recorded before request admission"
|
||||
);
|
||||
|
||||
drop(occupied_permits);
|
||||
timeout(Duration::from_secs(1), execution_started.notified())
|
||||
.await
|
||||
.expect("queued request should execute after admission");
|
||||
assert!(
|
||||
span_exporter
|
||||
.get_finished_spans()
|
||||
.expect("executing span export")
|
||||
.is_empty(),
|
||||
"the same request span must remain open during execution"
|
||||
);
|
||||
|
||||
let snapshot = metrics.snapshot().expect("metrics snapshot");
|
||||
let queue_metric = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
.find(|metric| metric.name() == "exec_server_request_queue_duration_seconds")
|
||||
.expect("request queue duration metric");
|
||||
let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = queue_metric.data() else {
|
||||
panic!("request queue duration should be an f64 histogram");
|
||||
};
|
||||
let data_point = histogram
|
||||
.data_points()
|
||||
.next()
|
||||
.expect("request queue duration data point");
|
||||
let queue_duration = Duration::from_secs_f64(data_point.sum());
|
||||
|
||||
assert_eq!(data_point.count(), 1);
|
||||
assert!(
|
||||
queue_duration >= Duration::from_millis(25),
|
||||
"queue latency should include the occupied admission lane"
|
||||
);
|
||||
assert_eq!(
|
||||
data_point
|
||||
.attributes()
|
||||
.find(|attribute| attribute.key.as_str() == "method")
|
||||
.map(|attribute| attribute.value.as_str().into_owned()),
|
||||
Some("test/queued".to_string())
|
||||
);
|
||||
|
||||
release_execution.notify_one();
|
||||
let response = timeout(Duration::from_secs(1), outgoing_rx.recv())
|
||||
.await
|
||||
.expect("queued request should send its response")
|
||||
.expect("queued request response");
|
||||
assert!(matches!(
|
||||
response,
|
||||
RpcServerOutboundMessage::Response {
|
||||
request_id: RequestId::Integer(1),
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(matches!(
|
||||
dispatcher.join_next().await,
|
||||
RequestTaskResult::Completed
|
||||
));
|
||||
|
||||
tracer_provider.force_flush().expect("flush traces");
|
||||
let spans = span_exporter.get_finished_spans().expect("span export");
|
||||
assert_eq!(spans.len(), 1);
|
||||
let request_span = spans.first().expect("end-to-end request span");
|
||||
assert_eq!(request_span.name.as_ref(), "test/queued");
|
||||
let request_duration = request_span
|
||||
.end_time
|
||||
.duration_since(request_span.start_time)
|
||||
.expect("request span should have a valid interval");
|
||||
assert!(
|
||||
request_duration >= Duration::from_millis(25),
|
||||
"the end-to-end request span should include the admission wait"
|
||||
);
|
||||
assert!(
|
||||
queue_duration
|
||||
<= request_duration.saturating_sub(route_setup_duration) + Duration::from_millis(5),
|
||||
"queue latency must exclude synchronous request decoding and route setup"
|
||||
);
|
||||
|
||||
let [dispatch_duration, total_duration] =
|
||||
assert_request_completion(&metrics, "test/queued", "success");
|
||||
assert!(dispatch_duration >= route_setup_duration + Duration::from_millis(25));
|
||||
assert!(total_duration >= dispatch_duration);
|
||||
assert!(
|
||||
total_duration <= request_duration + Duration::from_millis(5),
|
||||
"total request timing must not add admission wait twice"
|
||||
);
|
||||
assert!(
|
||||
total_duration >= queue_duration + route_setup_duration - Duration::from_millis(5),
|
||||
"total request timing must include admission and route setup exactly once"
|
||||
);
|
||||
|
||||
metrics.shutdown().expect("shutdown metrics");
|
||||
}
|
||||
|
||||
struct RequestTelemetryFixture {
|
||||
metrics: MetricsClient,
|
||||
dispatcher: RequestDispatcher,
|
||||
outgoing_rx: mpsc::Receiver<RpcServerOutboundMessage>,
|
||||
disconnected_tx: watch::Sender<bool>,
|
||||
}
|
||||
|
||||
fn request_telemetry_fixture(router: RpcRouter<ExecServerHandler>) -> RequestTelemetryFixture {
|
||||
let metrics = MetricsClient::new(
|
||||
MetricsConfig::in_memory(
|
||||
"test",
|
||||
"akode-exec-server",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
InMemoryMetricExporter::default(),
|
||||
)
|
||||
.with_runtime_reader(),
|
||||
)
|
||||
.expect("metrics client");
|
||||
let telemetry = ExecServerTelemetry::new(metrics.clone());
|
||||
let (outgoing_tx, outgoing_rx) = mpsc::channel(/*buffer*/ 1);
|
||||
let notifications = RpcNotificationSender::new(outgoing_tx.clone());
|
||||
let requests = notifications.request_sender();
|
||||
let handler = Arc::new(ExecServerHandler::new(
|
||||
SessionRegistry::new(telemetry.clone()),
|
||||
CapabilityManager::new(crate::LocalFileSystem::default()),
|
||||
notifications,
|
||||
ExecServerRuntimeOptions::new(
|
||||
std::env::current_exe().expect("current executable"),
|
||||
/*codex_linux_sandbox_exe*/ None,
|
||||
)
|
||||
.expect("runtime paths"),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
));
|
||||
let (disconnected_tx, disconnected_rx) = watch::channel(/*init*/ false);
|
||||
let dispatcher = RequestDispatcher::new(
|
||||
Arc::new(router),
|
||||
handler,
|
||||
outgoing_tx,
|
||||
disconnected_rx,
|
||||
requests,
|
||||
telemetry,
|
||||
RequestDispatchMode::Inline,
|
||||
);
|
||||
RequestTelemetryFixture {
|
||||
metrics,
|
||||
dispatcher,
|
||||
outgoing_rx,
|
||||
disconnected_tx,
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_request_completion(metrics: &MetricsClient, method: &str, result: &str) -> [Duration; 2] {
|
||||
let snapshot = metrics.snapshot().expect("completed request metrics");
|
||||
let metric = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
.find(|metric| metric.name() == "exec_server_requests_total")
|
||||
.expect("request counter");
|
||||
let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else {
|
||||
panic!("request counter should be a u64 sum");
|
||||
};
|
||||
let points: Vec<_> = sum.data_points().collect();
|
||||
assert_eq!(points.len(), 1);
|
||||
assert_eq!(points[0].value(), 1, "record the completion only once");
|
||||
|
||||
[
|
||||
"exec_server_request_duration_seconds",
|
||||
"exec_server_request_total_duration_seconds",
|
||||
]
|
||||
.map(|name| {
|
||||
let metric = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
.find(|metric| metric.name() == name)
|
||||
.expect("request duration histogram");
|
||||
let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = metric.data() else {
|
||||
panic!("request duration should be an f64 histogram");
|
||||
};
|
||||
let points: Vec<_> = histogram.data_points().collect();
|
||||
assert_eq!(points.len(), 1);
|
||||
let point = points[0];
|
||||
let attributes: BTreeMap<_, _> = point
|
||||
.attributes()
|
||||
.map(|attribute| {
|
||||
(
|
||||
attribute.key.as_str().to_string(),
|
||||
attribute.value.as_str().into_owned(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
attributes,
|
||||
BTreeMap::from([
|
||||
("method".to_string(), method.to_string()),
|
||||
("result".to_string(), result.to_string()),
|
||||
])
|
||||
);
|
||||
assert_eq!(point.count(), 1, "record each duration only once");
|
||||
Duration::from_secs_f64(point.sum())
|
||||
})
|
||||
}
|
||||
|
||||
/// A synthetic receipt timestamp makes the pre-dispatch boundary deterministic for every result.
|
||||
#[tokio::test]
|
||||
async fn total_duration_preserves_dispatch_duration_and_completion_results() {
|
||||
for (method, expected_method, expected_result, close_response) in [
|
||||
("test/success", "test/success", "success", false),
|
||||
("test/error", "test/error", "error", false),
|
||||
("test/unknown", "unknown", "error", false),
|
||||
("test/success", "test/success", "disconnected", true),
|
||||
("test/unknown", "unknown", "disconnected", true),
|
||||
] {
|
||||
let mut router = RpcRouter::new();
|
||||
router.request(
|
||||
"test/success",
|
||||
|_handler: Arc<ExecServerHandler>, _params: ()| async {
|
||||
Ok::<_, akode_exec_server_protocol::JSONRPCErrorError>(())
|
||||
},
|
||||
);
|
||||
router.request(
|
||||
"test/error",
|
||||
|_handler: Arc<ExecServerHandler>, _params: ()| async {
|
||||
Err::<(), _>(invalid_request("synthetic route error".to_string()))
|
||||
},
|
||||
);
|
||||
let mut fixture = request_telemetry_fixture(router);
|
||||
if close_response {
|
||||
fixture.outgoing_rx.close();
|
||||
}
|
||||
let pre_dispatch_wait = Duration::from_secs(5);
|
||||
let received_at = Instant::now() - pre_dispatch_wait;
|
||||
let result = fixture
|
||||
.dispatcher
|
||||
.dispatch_request(
|
||||
JSONRPCRequest {
|
||||
id: RequestId::Integer(1),
|
||||
method: method.to_string(),
|
||||
params: None,
|
||||
trace: None,
|
||||
},
|
||||
tracing::Span::none(),
|
||||
received_at,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
matches!(result, RequestTaskResult::ConnectionClosed),
|
||||
close_response
|
||||
);
|
||||
let [dispatch_duration, total_duration] =
|
||||
assert_request_completion(&fixture.metrics, expected_method, expected_result);
|
||||
assert!(total_duration >= dispatch_duration + pre_dispatch_wait);
|
||||
fixture.metrics.shutdown().expect("shutdown metrics");
|
||||
}
|
||||
}
|
||||
|
||||
/// Disconnecting a running request emits the same result and count for both duration definitions.
|
||||
#[tokio::test]
|
||||
async fn total_duration_records_disconnection_during_execution() {
|
||||
let execution_started = Arc::new(Notify::new());
|
||||
let notify_execution_started = Arc::clone(&execution_started);
|
||||
let mut router = RpcRouter::new();
|
||||
router.request(
|
||||
"test/pending",
|
||||
move |_handler: Arc<ExecServerHandler>, _params: ()| {
|
||||
let execution_started = Arc::clone(¬ify_execution_started);
|
||||
async move {
|
||||
execution_started.notify_one();
|
||||
std::future::pending::<Result<(), akode_exec_server_protocol::JSONRPCErrorError>>()
|
||||
.await
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut fixture = request_telemetry_fixture(router);
|
||||
let pre_dispatch_wait = Duration::from_secs(5);
|
||||
let received_at = Instant::now() - pre_dispatch_wait;
|
||||
let dispatch = fixture.dispatcher.dispatch_request(
|
||||
JSONRPCRequest {
|
||||
id: RequestId::Integer(1),
|
||||
method: "test/pending".to_string(),
|
||||
params: None,
|
||||
trace: None,
|
||||
},
|
||||
tracing::Span::none(),
|
||||
received_at,
|
||||
);
|
||||
let disconnect = async {
|
||||
execution_started.notified().await;
|
||||
fixture
|
||||
.disconnected_tx
|
||||
.send(/*value*/ true)
|
||||
.expect("disconnect request");
|
||||
};
|
||||
let (result, ()) = timeout(Duration::from_secs(1), async {
|
||||
tokio::join!(dispatch, disconnect)
|
||||
})
|
||||
.await
|
||||
.expect("disconnected request should finish");
|
||||
assert!(matches!(result, RequestTaskResult::ConnectionClosed));
|
||||
let [dispatch_duration, total_duration] =
|
||||
assert_request_completion(&fixture.metrics, "test/pending", "disconnected");
|
||||
assert!(total_duration >= dispatch_duration + pre_dispatch_wait);
|
||||
fixture.metrics.shutdown().expect("shutdown metrics");
|
||||
}
|
||||
279
akode-rs/exec-server/src/server/session_registry.rs
Normal file
279
akode-rs/exec-server/src/server/session_registry.rs
Normal file
@@ -0,0 +1,279 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_exec_server_protocol::JSONRPCErrorError;
|
||||
use tokio::sync::Mutex;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::rpc::RpcNotificationSender;
|
||||
use crate::rpc::invalid_request;
|
||||
use crate::rpc::session_already_attached;
|
||||
use crate::server::process_handler::ProcessHandler;
|
||||
use crate::telemetry::ExecServerTelemetry;
|
||||
use crate::telemetry::record_recovery_retention_expired;
|
||||
|
||||
// Allow the 50s client window, up to 25s of disconnect detection skew, and 5s of margin.
|
||||
#[cfg(not(test))]
|
||||
const RECOVERY_RETENTION: Duration = Duration::from_secs(80);
|
||||
#[cfg(test)]
|
||||
const DETACHED_SESSION_TTL: Duration = Duration::from_millis(200);
|
||||
#[cfg(not(test))]
|
||||
const DETACHED_SESSION_TTL: Duration = RECOVERY_RETENTION;
|
||||
#[cfg(test)]
|
||||
const RPC_OUTPUT_RETENTION: Duration = Duration::from_millis(25);
|
||||
#[cfg(not(test))]
|
||||
const RPC_OUTPUT_RETENTION: Duration = RECOVERY_RETENTION;
|
||||
|
||||
pub(crate) struct SessionRegistry {
|
||||
sessions: Mutex<HashMap<String, Arc<SessionEntry>>>,
|
||||
telemetry: ExecServerTelemetry,
|
||||
}
|
||||
|
||||
struct SessionEntry {
|
||||
session_id: String,
|
||||
process: ProcessHandler,
|
||||
attachment: StdMutex<AttachmentState>,
|
||||
}
|
||||
|
||||
enum AttachmentState {
|
||||
Attached {
|
||||
connection_id: ConnectionId,
|
||||
},
|
||||
Detached {
|
||||
connection_id: ConnectionId,
|
||||
expires_at: tokio::time::Instant,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
struct ConnectionId(Uuid);
|
||||
|
||||
impl std::fmt::Display for ConnectionId {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SessionHandle {
|
||||
registry: Arc<SessionRegistry>,
|
||||
entry: Arc<SessionEntry>,
|
||||
connection_id: ConnectionId,
|
||||
}
|
||||
|
||||
impl SessionRegistry {
|
||||
pub(crate) fn new(telemetry: ExecServerTelemetry) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
telemetry,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn attach(
|
||||
self: &Arc<Self>,
|
||||
resume_session_id: Option<String>,
|
||||
notifications: RpcNotificationSender,
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
) -> Result<SessionHandle, JSONRPCErrorError> {
|
||||
enum AttachOutcome {
|
||||
Attached(Arc<SessionEntry>),
|
||||
Expired {
|
||||
session_id: String,
|
||||
entry: Arc<SessionEntry>,
|
||||
},
|
||||
}
|
||||
|
||||
let connection_id = ConnectionId(Uuid::new_v4());
|
||||
let outcome = {
|
||||
let mut sessions = self.sessions.lock().await;
|
||||
if let Some(session_id) = resume_session_id {
|
||||
let entry = sessions
|
||||
.get(&session_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| invalid_request(format!("unknown session id {session_id}")))?;
|
||||
if entry.is_expired(tokio::time::Instant::now()) {
|
||||
let entry = sessions.remove(&session_id).ok_or_else(|| {
|
||||
invalid_request(format!("unknown session id {session_id}"))
|
||||
})?;
|
||||
Ok(AttachOutcome::Expired { session_id, entry })
|
||||
} else if entry.has_active_connection() {
|
||||
Err(session_already_attached(format!(
|
||||
"session {session_id} is already attached to another connection"
|
||||
)))
|
||||
} else {
|
||||
entry.process.set_notification_sender(Some(notifications));
|
||||
entry.attach(connection_id);
|
||||
Ok(AttachOutcome::Attached(entry))
|
||||
}
|
||||
} else {
|
||||
let session_id = Uuid::new_v4().to_string();
|
||||
let entry = Arc::new(SessionEntry::new(
|
||||
session_id.clone(),
|
||||
ProcessHandler::new(
|
||||
notifications,
|
||||
self.telemetry.clone(),
|
||||
runtime_paths,
|
||||
RPC_OUTPUT_RETENTION,
|
||||
),
|
||||
connection_id,
|
||||
));
|
||||
sessions.insert(session_id, Arc::clone(&entry));
|
||||
Ok(AttachOutcome::Attached(entry))
|
||||
}
|
||||
};
|
||||
let entry = match outcome? {
|
||||
AttachOutcome::Attached(entry) => entry,
|
||||
AttachOutcome::Expired { session_id, entry } => {
|
||||
record_recovery_retention_expired("detached_session_resume", DETACHED_SESSION_TTL);
|
||||
entry.process.shutdown().await;
|
||||
return Err(invalid_request(format!("unknown session id {session_id}")));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(SessionHandle {
|
||||
registry: Arc::clone(self),
|
||||
entry,
|
||||
connection_id,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
let sessions = std::mem::take(&mut *self.sessions.lock().await);
|
||||
for entry in sessions.into_values() {
|
||||
entry.process.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn expire_if_detached(&self, session_id: String, connection_id: ConnectionId) {
|
||||
tokio::time::sleep(DETACHED_SESSION_TTL).await;
|
||||
|
||||
let removed = {
|
||||
let mut sessions = self.sessions.lock().await;
|
||||
let Some(entry) = sessions.get(&session_id) else {
|
||||
return;
|
||||
};
|
||||
if !entry.is_detached_connection_expired(connection_id, tokio::time::Instant::now()) {
|
||||
return;
|
||||
}
|
||||
sessions.remove(&session_id)
|
||||
};
|
||||
|
||||
if let Some(entry) = removed {
|
||||
record_recovery_retention_expired("detached_session_timer", DETACHED_SESSION_TTL);
|
||||
entry.process.shutdown().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SessionRegistry {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
telemetry: ExecServerTelemetry::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionEntry {
|
||||
fn new(session_id: String, process: ProcessHandler, connection_id: ConnectionId) -> Self {
|
||||
Self {
|
||||
session_id,
|
||||
process,
|
||||
attachment: StdMutex::new(AttachmentState::Attached { connection_id }),
|
||||
}
|
||||
}
|
||||
|
||||
fn attach(&self, connection_id: ConnectionId) {
|
||||
let mut attachment = self
|
||||
.attachment
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
*attachment = AttachmentState::Attached { connection_id };
|
||||
}
|
||||
|
||||
fn detach(&self, connection_id: ConnectionId) -> bool {
|
||||
let mut attachment = self
|
||||
.attachment
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if !matches!(*attachment, AttachmentState::Attached { connection_id: current } if current == connection_id)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
self.process.set_notification_sender(/*notifications*/ None);
|
||||
*attachment = AttachmentState::Detached {
|
||||
connection_id,
|
||||
expires_at: tokio::time::Instant::now() + DETACHED_SESSION_TTL,
|
||||
};
|
||||
true
|
||||
}
|
||||
|
||||
fn has_active_connection(&self) -> bool {
|
||||
matches!(
|
||||
*self
|
||||
.attachment
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
AttachmentState::Attached { .. }
|
||||
)
|
||||
}
|
||||
|
||||
fn is_attached_to(&self, connection_id: ConnectionId) -> bool {
|
||||
matches!(*self.attachment
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner), AttachmentState::Attached { connection_id: current } if current == connection_id)
|
||||
}
|
||||
|
||||
fn is_expired(&self, now: tokio::time::Instant) -> bool {
|
||||
matches!(*self.attachment
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner), AttachmentState::Detached { expires_at, .. } if now >= expires_at)
|
||||
}
|
||||
|
||||
fn is_detached_connection_expired(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
now: tokio::time::Instant,
|
||||
) -> bool {
|
||||
let attachment = self
|
||||
.attachment
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
matches!(*attachment, AttachmentState::Detached { connection_id: detached, expires_at } if detached == connection_id && now >= expires_at)
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionHandle {
|
||||
pub(crate) fn session_id(&self) -> &str {
|
||||
&self.entry.session_id
|
||||
}
|
||||
|
||||
pub(crate) fn connection_id(&self) -> String {
|
||||
self.connection_id.to_string()
|
||||
}
|
||||
|
||||
pub(crate) fn is_session_attached(&self) -> bool {
|
||||
self.entry.is_attached_to(self.connection_id)
|
||||
}
|
||||
|
||||
pub(crate) fn process(&self) -> &ProcessHandler {
|
||||
&self.entry.process
|
||||
}
|
||||
|
||||
pub(crate) async fn detach(&self) {
|
||||
if !self.entry.detach(self.connection_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
let registry = Arc::clone(&self.registry);
|
||||
let session_id = self.entry.session_id.clone();
|
||||
let connection_id = self.connection_id;
|
||||
tokio::spawn(async move {
|
||||
registry.expire_if_detached(session_id, connection_id).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
274
akode-rs/exec-server/src/server/transport.rs
Normal file
274
akode-rs/exec-server/src/server/transport.rs
Normal file
@@ -0,0 +1,274 @@
|
||||
//! Exec-server stdio and WebSocket listeners. Configured authentication gates
|
||||
//! WebSocket upgrades; unauthenticated listeners remain supported for compatibility.
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Body;
|
||||
use axum::extract::ConnectInfo;
|
||||
use axum::extract::State;
|
||||
use axum::extract::ws::WebSocketUpgrade;
|
||||
use axum::http::HeaderMap;
|
||||
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_http_client::HttpClientFactory;
|
||||
use akode_websocket_auth::WebsocketAuthPolicy;
|
||||
use akode_websocket_auth::WebsocketAuthSettings;
|
||||
use akode_websocket_auth::authorize_upgrade;
|
||||
use akode_websocket_auth::policy_from_settings;
|
||||
use std::io::Write as _;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::io;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::net::TcpListener;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::ExecServerTelemetry;
|
||||
use crate::connection::JsonRpcConnection;
|
||||
use crate::server::RequestDispatchMode;
|
||||
use crate::server::processor::ConnectionProcessor;
|
||||
use crate::telemetry::ConnectionTransport;
|
||||
|
||||
pub const DEFAULT_LISTEN_URL: &str = "ws://127.0.0.1:0";
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub(crate) enum ExecServerListenTransport {
|
||||
WebSocket(SocketAddr),
|
||||
Stdio,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub enum ExecServerListenUrlParseError {
|
||||
UnsupportedListenUrl(String),
|
||||
InvalidWebSocketListenUrl(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ExecServerListenUrlParseError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ExecServerListenUrlParseError::UnsupportedListenUrl(listen_url) => write!(
|
||||
f,
|
||||
"unsupported --listen URL `{listen_url}`; expected `ws://IP:PORT` or `stdio`"
|
||||
),
|
||||
ExecServerListenUrlParseError::InvalidWebSocketListenUrl(listen_url) => write!(
|
||||
f,
|
||||
"invalid websocket --listen URL `{listen_url}`; expected `ws://IP:PORT`"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ExecServerListenUrlParseError {}
|
||||
|
||||
pub(crate) fn parse_listen_url(
|
||||
listen_url: &str,
|
||||
) -> Result<ExecServerListenTransport, ExecServerListenUrlParseError> {
|
||||
if matches!(listen_url, "stdio" | "stdio://") {
|
||||
return Ok(ExecServerListenTransport::Stdio);
|
||||
}
|
||||
|
||||
if let Some(socket_addr) = listen_url.strip_prefix("ws://") {
|
||||
return socket_addr
|
||||
.parse::<SocketAddr>()
|
||||
.map(ExecServerListenTransport::WebSocket)
|
||||
.map_err(|_| {
|
||||
ExecServerListenUrlParseError::InvalidWebSocketListenUrl(listen_url.to_string())
|
||||
});
|
||||
}
|
||||
|
||||
Err(ExecServerListenUrlParseError::UnsupportedListenUrl(
|
||||
listen_url.to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn run_transport(
|
||||
listen_url: &str,
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
websocket_auth: WebsocketAuthSettings,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
match parse_listen_url(listen_url)? {
|
||||
ExecServerListenTransport::WebSocket(bind_address) => {
|
||||
run_websocket_listener(
|
||||
bind_address,
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
policy_from_settings(&websocket_auth)?,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ExecServerListenTransport::Stdio => {
|
||||
if websocket_auth.config.is_some() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"WebSocket auth requires a WebSocket listener, not stdio",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
run_stdio_connection(
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_stdio_connection(
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
run_stdio_connection_with_io(
|
||||
io::stdin(),
|
||||
io::stdout(),
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn run_stdio_connection_with_io<R, W>(
|
||||
reader: R,
|
||||
writer: W,
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
|
||||
where
|
||||
R: AsyncRead + Unpin + Send + 'static,
|
||||
W: AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
let processor = ConnectionProcessor::new_with_telemetry(
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
);
|
||||
tracing::info!("akode-exec-server listening on stdio");
|
||||
processor
|
||||
.run_connection(
|
||||
JsonRpcConnection::from_stdio(reader, writer, "exec-server stdio".to_string()),
|
||||
ConnectionTransport::Stdio,
|
||||
)
|
||||
.await;
|
||||
// Stdio serves exactly one connection, so detached sessions cannot be resumed.
|
||||
processor.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_websocket_listener(
|
||||
bind_address: SocketAddr,
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
auth_policy: WebsocketAuthPolicy,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let listener = TcpListener::bind(bind_address).await?;
|
||||
let local_addr = listener.local_addr()?;
|
||||
let processor = ConnectionProcessor::new_with_telemetry(
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
);
|
||||
info!("akode-exec-server listening on ws://{local_addr}");
|
||||
println!("ws://{local_addr}");
|
||||
std::io::stdout().flush()?;
|
||||
|
||||
let router = Router::new()
|
||||
.route("/", any(websocket_upgrade_handler))
|
||||
.route("/readyz", get(readiness_handler))
|
||||
.layer(middleware::from_fn(reject_requests_with_origin_header))
|
||||
.with_state(ExecServerWebSocketState {
|
||||
processor,
|
||||
auth_policy,
|
||||
});
|
||||
axum::serve(
|
||||
listener,
|
||||
router.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ExecServerWebSocketState {
|
||||
processor: ConnectionProcessor,
|
||||
auth_policy: WebsocketAuthPolicy,
|
||||
}
|
||||
|
||||
async fn readiness_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 exec-server 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<ExecServerWebSocketState>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(err) = authorize_upgrade(&headers, &state.auth_policy) {
|
||||
return (err.status_code(), err.message()).into_response();
|
||||
}
|
||||
info!(%peer_addr, "exec-server websocket client connected");
|
||||
let mut response = websocket
|
||||
.on_upgrade(move |stream| async move {
|
||||
state
|
||||
.processor
|
||||
.run_connection(
|
||||
JsonRpcConnection::from_axum_websocket(
|
||||
stream,
|
||||
format!("exec-server websocket {peer_addr}"),
|
||||
),
|
||||
ConnectionTransport::WebSocket,
|
||||
)
|
||||
.await;
|
||||
})
|
||||
.into_response();
|
||||
if let Some(request_id) = headers.get("x-request-id") {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-request-id", request_id.clone());
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "transport_tests.rs"]
|
||||
mod transport_tests;
|
||||
172
akode-rs/exec-server/src/server/transport_tests.rs
Normal file
172
akode-rs/exec-server/src/server/transport_tests.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_exec_server_protocol::JSONRPCMessage;
|
||||
use akode_exec_server_protocol::JSONRPCNotification;
|
||||
use akode_exec_server_protocol::JSONRPCRequest;
|
||||
use akode_exec_server_protocol::JSONRPCResponse;
|
||||
use akode_exec_server_protocol::RequestId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::io::duplex;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::DEFAULT_LISTEN_URL;
|
||||
use super::ExecServerListenTransport;
|
||||
use super::parse_listen_url;
|
||||
use super::run_stdio_connection_with_io;
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::protocol::INITIALIZE_METHOD;
|
||||
use crate::protocol::INITIALIZED_METHOD;
|
||||
use crate::protocol::InitializeParams;
|
||||
use crate::protocol::InitializeResponse;
|
||||
use crate::server::RequestDispatchMode;
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_accepts_default_websocket_url() {
|
||||
let transport = parse_listen_url(DEFAULT_LISTEN_URL).expect("default listen URL should parse");
|
||||
assert_eq!(
|
||||
transport,
|
||||
ExecServerListenTransport::WebSocket(
|
||||
"127.0.0.1:0"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("valid socket address")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_accepts_stdio() {
|
||||
let transport = parse_listen_url("stdio").expect("stdio listen URL should parse");
|
||||
assert_eq!(transport, ExecServerListenTransport::Stdio);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_accepts_stdio_url() {
|
||||
let transport = parse_listen_url("stdio://").expect("stdio listen URL should parse");
|
||||
assert_eq!(transport, ExecServerListenTransport::Stdio);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stdio_listen_transport_serves_initialize() {
|
||||
let transport = parse_listen_url("stdio").expect("stdio listen URL should parse");
|
||||
let ExecServerListenTransport::Stdio = transport else {
|
||||
panic!("expected stdio listen transport, got {transport:?}");
|
||||
};
|
||||
|
||||
let (mut client_writer, server_reader) = duplex(1 << 20);
|
||||
let (server_writer, client_reader) = duplex(1 << 20);
|
||||
let server_task = tokio::spawn(run_stdio_connection_with_io(
|
||||
server_reader,
|
||||
server_writer,
|
||||
test_runtime_paths(),
|
||||
crate::ExecServerTelemetry::default(),
|
||||
akode_http_client::HttpClientFactory::new(
|
||||
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
RequestDispatchMode::Inline,
|
||||
));
|
||||
let mut client_lines = BufReader::new(client_reader).lines();
|
||||
|
||||
let initialize = JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: RequestId::Integer(1),
|
||||
method: INITIALIZE_METHOD.to_string(),
|
||||
params: Some(
|
||||
serde_json::to_value(InitializeParams {
|
||||
client_name: "exec-server-transport-test".to_string(),
|
||||
resume_session_id: None,
|
||||
})
|
||||
.expect("initialize params should serialize"),
|
||||
),
|
||||
trace: None,
|
||||
});
|
||||
write_jsonrpc_line(&mut client_writer, &initialize).await;
|
||||
|
||||
let response = timeout(Duration::from_secs(1), client_lines.next_line())
|
||||
.await
|
||||
.expect("initialize response should arrive")
|
||||
.expect("initialize response read should succeed")
|
||||
.expect("initialize response should be present");
|
||||
let response: JSONRPCMessage =
|
||||
serde_json::from_str(&response).expect("initialize response should parse");
|
||||
let JSONRPCMessage::Response(JSONRPCResponse { id, result }) = response else {
|
||||
panic!("expected initialize response, got {response:?}");
|
||||
};
|
||||
assert_eq!(id, RequestId::Integer(1));
|
||||
let initialize_response: InitializeResponse =
|
||||
serde_json::from_value(result).expect("initialize response should decode");
|
||||
assert!(
|
||||
!initialize_response.session_id.is_empty(),
|
||||
"initialize should return a session id"
|
||||
);
|
||||
|
||||
let initialized = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: INITIALIZED_METHOD.to_string(),
|
||||
params: Some(serde_json::to_value(()).expect("initialized params should serialize")),
|
||||
});
|
||||
write_jsonrpc_line(&mut client_writer, &initialized).await;
|
||||
|
||||
drop(client_writer);
|
||||
drop(client_lines);
|
||||
timeout(Duration::from_secs(1), server_task)
|
||||
.await
|
||||
.expect("stdio transport should finish after client disconnect")
|
||||
.expect("stdio transport task should join")
|
||||
.expect("stdio transport should not fail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_accepts_websocket_url() {
|
||||
let transport =
|
||||
parse_listen_url("ws://127.0.0.1:1234").expect("websocket listen URL should parse");
|
||||
assert_eq!(
|
||||
transport,
|
||||
ExecServerListenTransport::WebSocket(
|
||||
"127.0.0.1:1234"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("valid socket address")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_rejects_invalid_websocket_url() {
|
||||
let err = parse_listen_url("ws://localhost:1234")
|
||||
.expect_err("hostname bind address should be rejected");
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid websocket --listen URL `ws://localhost:1234`; expected `ws://IP:PORT`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_rejects_unsupported_url() {
|
||||
let err =
|
||||
parse_listen_url("http://127.0.0.1:1234").expect_err("unsupported scheme should fail");
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"unsupported --listen URL `http://127.0.0.1:1234`; expected `ws://IP:PORT` or `stdio`"
|
||||
);
|
||||
}
|
||||
|
||||
async fn write_jsonrpc_line(writer: &mut tokio::io::DuplexStream, message: &JSONRPCMessage) {
|
||||
let encoded = serde_json::to_vec(message).expect("JSON-RPC message should serialize");
|
||||
writer
|
||||
.write_all(&encoded)
|
||||
.await
|
||||
.expect("JSON-RPC message should write");
|
||||
writer
|
||||
.write_all(b"\n")
|
||||
.await
|
||||
.expect("JSON-RPC newline should write");
|
||||
}
|
||||
|
||||
fn test_runtime_paths() -> ExecServerRuntimeOptions {
|
||||
ExecServerRuntimeOptions::new(
|
||||
std::env::current_exe().expect("current exe"),
|
||||
/*codex_linux_sandbox_exe*/ None,
|
||||
)
|
||||
.expect("runtime paths")
|
||||
}
|
||||
Reference in New Issue
Block a user