240 行
8.5 KiB
Rust
240 行
8.5 KiB
Rust
mod config;
|
|
mod routes;
|
|
mod state;
|
|
|
|
use std::{io, net::SocketAddr, sync::Arc};
|
|
|
|
pub use config::{AuthMode, MockGatewayConfig, MockInstanceKind, MockScenario};
|
|
use desktop_protocol::{
|
|
GatewayEvent, GatewayEventBody, HeartbeatPayload, ProactiveMessagePayload, RiskLevel,
|
|
ToolProposal,
|
|
};
|
|
use state::AppState;
|
|
use thiserror::Error;
|
|
use tokio::{net::TcpListener, sync::Mutex, task::JoinHandle};
|
|
use tokio_util::sync::CancellationToken;
|
|
|
|
#[derive(Clone)]
|
|
pub struct MockGatewayHandle {
|
|
inner: Arc<HandleInner>,
|
|
}
|
|
|
|
struct HandleInner {
|
|
state: Arc<AppState>,
|
|
address: SocketAddr,
|
|
shutdown: CancellationToken,
|
|
server_task: Mutex<Option<JoinHandle<Result<(), io::Error>>>>,
|
|
scenario_task: Mutex<Option<JoinHandle<()>>>,
|
|
}
|
|
|
|
impl MockGatewayHandle {
|
|
pub fn base_url(&self) -> String {
|
|
format!("http://{}", self.inner.address)
|
|
}
|
|
|
|
pub fn server_instance_id(&self) -> &str {
|
|
&self.inner.state.server_instance_id
|
|
}
|
|
|
|
pub async fn emit_event(&self, event: GatewayEvent) -> Result<(), MockGatewayError> {
|
|
if event.metadata.server_instance_id != self.server_instance_id() {
|
|
return Err(MockGatewayError::EventServerInstanceMismatch {
|
|
expected: self.server_instance_id().to_owned(),
|
|
received: event.metadata.server_instance_id,
|
|
});
|
|
}
|
|
self.inner.state.publish(event).await;
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn emit_body(&self, body: GatewayEventBody) -> GatewayEvent {
|
|
let event = self.inner.state.create_event(body, None, None, None);
|
|
self.inner.state.publish(event.clone()).await;
|
|
event
|
|
}
|
|
|
|
pub async fn emit_proactive_message(&self) -> GatewayEvent {
|
|
self.emit_body(GatewayEventBody::ProactiveMessage(
|
|
ProactiveMessagePayload {
|
|
content: "Deterministic proactive mock message".to_owned(),
|
|
notification_title: Some(self.inner.state.instance.display_name().to_owned()),
|
|
},
|
|
))
|
|
.await
|
|
}
|
|
|
|
pub async fn emit_tool_proposal(&self) -> GatewayEvent {
|
|
self.emit_body(GatewayEventBody::ToolProposal(ToolProposal {
|
|
action_id: "mock-action-event-log-1".to_owned(),
|
|
tool_name: "query_recent_event_logs".to_owned(),
|
|
reason: "Inspect a bounded set of recent Application events".to_owned(),
|
|
risk_level: RiskLevel::Read,
|
|
arguments: serde_json::json!({
|
|
"provider": "Application",
|
|
"sinceMinutes": 15,
|
|
"maxEntries": 20
|
|
}),
|
|
requested_at: state::FIXED_TIMESTAMP.to_owned(),
|
|
expires_at: "2030-01-01T00:05:00Z".to_owned(),
|
|
requires_approval: true,
|
|
}))
|
|
.await
|
|
}
|
|
|
|
pub fn disconnect_streams(&self) {
|
|
self.inner.state.disconnect_streams();
|
|
}
|
|
|
|
pub async fn replay_event(&self, event_id: &str) -> bool {
|
|
self.inner.state.replay_event(event_id).await
|
|
}
|
|
|
|
pub fn set_auth_mode(&self, mode: AuthMode) {
|
|
self.inner.state.set_auth_mode(mode);
|
|
}
|
|
|
|
pub async fn acknowledged_event_ids(&self) -> Vec<String> {
|
|
self.inner.state.acknowledged_event_ids().await
|
|
}
|
|
|
|
pub async fn shutdown(&self) -> Result<(), MockGatewayError> {
|
|
self.inner.shutdown.cancel();
|
|
|
|
if let Some(task) = self.inner.scenario_task.lock().await.take() {
|
|
task.await?;
|
|
}
|
|
if let Some(task) = self.inner.server_task.lock().await.take() {
|
|
task.await??;
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
pub async fn spawn_mock_gateway(
|
|
config: MockGatewayConfig,
|
|
) -> Result<MockGatewayHandle, MockGatewayError> {
|
|
if !config.bind_addr.ip().is_loopback() {
|
|
return Err(MockGatewayError::NonLoopbackBind(config.bind_addr));
|
|
}
|
|
|
|
let listener = TcpListener::bind(config.bind_addr).await?;
|
|
let address = listener.local_addr()?;
|
|
let state = Arc::new(AppState::new(&config));
|
|
let router = routes::router(state.clone());
|
|
let shutdown = CancellationToken::new();
|
|
let server_shutdown = shutdown.clone();
|
|
let server_task = tokio::spawn(async move {
|
|
axum::serve(listener, router)
|
|
.with_graceful_shutdown(server_shutdown.cancelled_owned())
|
|
.await
|
|
});
|
|
|
|
let scenario_task = config.heartbeat_interval.map(|interval| {
|
|
let task_state = state.clone();
|
|
let task_shutdown = shutdown.clone();
|
|
let scenario = config.scenario;
|
|
tokio::spawn(async move {
|
|
run_scenario(task_state, scenario, interval, task_shutdown).await;
|
|
})
|
|
});
|
|
|
|
Ok(MockGatewayHandle {
|
|
inner: Arc::new(HandleInner {
|
|
state,
|
|
address,
|
|
shutdown,
|
|
server_task: Mutex::new(Some(server_task)),
|
|
scenario_task: Mutex::new(scenario_task),
|
|
}),
|
|
})
|
|
}
|
|
|
|
async fn run_scenario(
|
|
state: Arc<AppState>,
|
|
scenario: MockScenario,
|
|
interval: std::time::Duration,
|
|
shutdown: CancellationToken,
|
|
) {
|
|
if scenario == MockScenario::AuthReject {
|
|
state.set_auth_mode(AuthMode::Reject);
|
|
}
|
|
|
|
let mut ticker = tokio::time::interval(interval);
|
|
let mut ticks = 0_u64;
|
|
loop {
|
|
tokio::select! {
|
|
_ = shutdown.cancelled() => break,
|
|
_ = ticker.tick() => {
|
|
ticks += 1;
|
|
let heartbeat = state.create_event(
|
|
GatewayEventBody::Heartbeat(HeartbeatPayload {
|
|
interval_ms: interval.as_millis().try_into().unwrap_or(u64::MAX),
|
|
}),
|
|
None,
|
|
None,
|
|
None,
|
|
);
|
|
state.publish(heartbeat.clone()).await;
|
|
|
|
if ticks == 2 {
|
|
match state.instance {
|
|
MockInstanceKind::Companion => {
|
|
let event = state.create_event(
|
|
GatewayEventBody::ProactiveMessage(ProactiveMessagePayload {
|
|
content: "Deterministic proactive mock message".to_owned(),
|
|
notification_title: Some("Mock Companion".to_owned()),
|
|
}),
|
|
None,
|
|
Some("mock-companion-conversation".to_owned()),
|
|
None,
|
|
);
|
|
state.publish(event).await;
|
|
}
|
|
MockInstanceKind::Operations => {
|
|
let event = state.create_event(
|
|
GatewayEventBody::ToolProposal(ToolProposal {
|
|
action_id: "mock-action-event-log-1".to_owned(),
|
|
tool_name: "query_recent_event_logs".to_owned(),
|
|
reason: "Inspect a bounded set of recent Application events".to_owned(),
|
|
risk_level: RiskLevel::Read,
|
|
arguments: serde_json::json!({
|
|
"provider": "Application",
|
|
"sinceMinutes": 15,
|
|
"maxEntries": 20
|
|
}),
|
|
requested_at: state::FIXED_TIMESTAMP.to_owned(),
|
|
expires_at: "2030-01-01T00:05:00Z".to_owned(),
|
|
requires_approval: true,
|
|
}),
|
|
None,
|
|
Some("mock-operations-conversation".to_owned()),
|
|
None,
|
|
);
|
|
state.publish(event).await;
|
|
}
|
|
}
|
|
}
|
|
|
|
match scenario {
|
|
MockScenario::DisconnectOnce if ticks == 3 => state.disconnect_streams(),
|
|
MockScenario::DuplicateEvents if ticks.is_multiple_of(3) => {
|
|
state.broadcast_duplicate(&heartbeat);
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum MockGatewayError {
|
|
#[error("mock gateway refuses non-loopback bind address {0}")]
|
|
NonLoopbackBind(SocketAddr),
|
|
#[error("event server instance mismatch: expected {expected}, received {received}")]
|
|
EventServerInstanceMismatch { expected: String, received: String },
|
|
#[error(transparent)]
|
|
Io(#[from] io::Error),
|
|
#[error(transparent)]
|
|
Join(#[from] tokio::task::JoinError),
|
|
}
|