1use std::sync::Arc;
2
3use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
4use axum::extract::{Query, State};
5use axum::http::{HeaderMap, StatusCode};
6use axum::response::{IntoResponse, Response};
7use axum::routing::get;
8use axum::{Json, Router};
9use futures_util::{SinkExt, StreamExt};
10use serde::Deserialize;
11use serde_json::{Value, json};
12use tracing::{info, warn};
13
14use crate::bridge_protocol::{
15 ApiError, ClientEnvelope, RuntimeStatusSnapshot, RuntimeSummary, ServerEnvelope,
16 error_response, event_envelope, ok_response,
17};
18use crate::state::BridgeState;
19
20#[derive(Debug, Deserialize, Default)]
21struct WsQuery {
22 token: Option<String>,
23}
24
25pub fn build_router(state: Arc<BridgeState>) -> Router {
26 Router::new()
27 .route("/health", get(health_handler))
28 .route("/ws", get(ws_handler))
29 .with_state(state)
30}
31
32async fn health_handler(State(state): State<Arc<BridgeState>>) -> Json<Value> {
33 let runtime = state.runtime_snapshot_for_client().await;
34 let runtimes = state.runtime_summaries_for_client().await;
35 Json(build_health_payload(&runtime, &runtimes))
36}
37
38fn build_health_payload(runtime: &RuntimeStatusSnapshot, runtimes: &[RuntimeSummary]) -> Value {
39 let primary_runtime_id = runtimes
40 .iter()
41 .find(|item| item.is_primary)
42 .map(|item| item.runtime_id.clone());
43
44 json!({
45 "ok": true,
46 "bridgeVersion": crate::BRIDGE_VERSION,
47 "buildHash": crate::BRIDGE_BUILD_HASH,
48 "protocolVersion": crate::BRIDGE_PROTOCOL_VERSION,
49 "runtimeCount": runtimes.len(),
50 "primaryRuntimeId": primary_runtime_id,
51 "runtime": runtime,
52 })
53}
54
55async fn ws_handler(
56 State(state): State<Arc<BridgeState>>,
57 Query(query): Query<WsQuery>,
58 headers: HeaderMap,
59 ws: WebSocketUpgrade,
60) -> Response {
61 match authorize(&state, &query, &headers) {
62 Ok(()) => ws
63 .on_upgrade(move |socket| handle_socket(state, socket))
64 .into_response(),
65 Err(error) => (StatusCode::UNAUTHORIZED, error).into_response(),
66 }
67}
68
69fn authorize(
70 state: &BridgeState,
71 query: &WsQuery,
72 headers: &HeaderMap,
73) -> Result<(), &'static str> {
74 let token = query
75 .token
76 .clone()
77 .or_else(|| {
78 headers
79 .get(axum::http::header::AUTHORIZATION)
80 .and_then(|value| value.to_str().ok())
81 .and_then(|value| value.strip_prefix("Bearer "))
82 .map(ToOwned::to_owned)
83 })
84 .ok_or("missing token")?;
85
86 if token == state.config_token() {
87 Ok(())
88 } else {
89 Err("invalid token")
90 }
91}
92
93async fn handle_socket(state: Arc<BridgeState>, socket: WebSocket) {
94 let (mut sender, mut receiver) = socket.split();
95 let mut event_rx = state.subscribe_events();
96 let mut device_id: Option<String> = None;
97
98 loop {
99 tokio::select! {
100 incoming = receiver.next() => {
101 let Some(incoming) = incoming else {
102 info!(
103 "bridge ws 对端已断开 device_id={}",
104 device_id.as_deref().unwrap_or("<pending>")
105 );
106 break;
107 };
108
109 let Ok(message) = incoming else {
110 warn!(
111 "bridge ws 接收失败 device_id={}: {:?}",
112 device_id.as_deref().unwrap_or("<pending>"),
113 incoming.err()
114 );
115 break;
116 };
117
118 match handle_incoming_message(&state, &mut sender, &mut device_id, message).await {
119 Ok(should_continue) if should_continue => {}
120 Ok(_) => break,
121 Err(error) => {
122 warn!(
123 "bridge ws 处理消息失败 device_id={}: {error}",
124 device_id.as_deref().unwrap_or("<pending>")
125 );
126 break;
127 }
128 }
129 }
130 broadcast_result = event_rx.recv(), if device_id.is_some() => {
131 match broadcast_result {
132 Ok(event) => {
133 if send_json(&mut sender, &event_envelope(event)).await.is_err() {
134 break;
135 }
136 }
137 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
138 let envelope = ServerEnvelope::Response {
139 request_id: "system".to_string(),
140 success: false,
141 data: None,
142 error: Some(ApiError::new("lagged", "事件流丢失,请重新连接")),
143 };
144 let _ = send_json(&mut sender, &envelope).await;
145 break;
146 }
147 Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
148 }
149 }
150 }
151 }
152}
153
154async fn handle_incoming_message(
155 state: &BridgeState,
156 sender: &mut futures_util::stream::SplitSink<WebSocket, Message>,
157 device_id: &mut Option<String>,
158 message: Message,
159) -> anyhow::Result<bool> {
160 let text = match message {
161 Message::Text(text) => text,
162 Message::Close(frame) => {
163 let detail = frame
164 .as_ref()
165 .map(|close| format!("code={} reason={}", close.code, close.reason))
166 .unwrap_or_else(|| "no close frame".to_string());
167 info!(
168 "bridge ws 收到 close 帧 device_id={}: {detail}",
169 device_id.as_deref().unwrap_or("<pending>")
170 );
171 return Ok(false);
172 }
173 _ => return Ok(true),
174 };
175
176 let envelope = parse_client_envelope(&text).map_err(|error| {
177 anyhow::anyhow!(
178 "解析客户端消息失败: {error}; payload={}",
179 truncate_text(&text, 240)
180 )
181 })?;
182 match envelope {
183 ClientEnvelope::Hello {
184 device_id: next_device_id,
185 last_ack_seq,
186 } => {
187 info!(
188 "bridge ws 收到 hello device_id={} last_ack_seq={last_ack_seq:?}",
189 next_device_id
190 );
191 let (runtime, runtimes, workspaces, pending_requests, replay_events) =
192 state.hello_payload(&next_device_id, last_ack_seq).await?;
193 *device_id = Some(next_device_id);
194 let connected_device_id = device_id.as_deref().unwrap_or("<pending>");
195
196 send_json(
197 sender,
198 &ServerEnvelope::Hello {
199 runtime,
200 runtimes,
201 workspaces,
202 pending_requests,
203 },
204 )
205 .await?;
206
207 info!(
208 "bridge ws hello 已完成 device_id={} replay_events={}",
209 connected_device_id,
210 replay_events.len()
211 );
212 for event in replay_events {
213 send_json(sender, &event_envelope(event)).await?;
214 }
215 }
216 ClientEnvelope::Request {
217 request_id,
218 action,
219 payload,
220 } => {
221 if device_id.is_none() {
222 send_json(
223 sender,
224 &error_response(
225 request_id,
226 ApiError::new("handshake_required", "请先发送 hello"),
227 ),
228 )
229 .await?;
230 return Ok(true);
231 }
232
233 let response = match state.handle_request(&action, payload).await {
234 Ok(data) => ok_response(request_id, data),
235 Err(error) => error_response(
236 request_id,
237 ApiError::new("request_failed", error.to_string()),
238 ),
239 };
240 send_json(sender, &response).await?;
241 }
242 ClientEnvelope::AckEvents { last_seq } => {
243 if let Some(device_id) = device_id.as_deref() {
244 state.ack_events(device_id, last_seq)?;
245 }
246 }
247 ClientEnvelope::Ping => {
248 send_json(
249 sender,
250 &ServerEnvelope::Pong {
251 server_time_ms: crate::bridge_protocol::now_millis(),
252 },
253 )
254 .await?;
255 }
256 }
257
258 Ok(true)
259}
260
261fn parse_client_envelope(text: &str) -> anyhow::Result<ClientEnvelope> {
262 match serde_json::from_str::<ClientEnvelope>(text) {
263 Ok(envelope) => Ok(envelope),
264 Err(primary_error) => {
265 let nested_payload = serde_json::from_str::<String>(text).map_err(|_| primary_error)?;
266 serde_json::from_str::<ClientEnvelope>(&nested_payload).map_err(Into::into)
267 }
268 }
269}
270
271fn truncate_text(text: &str, max_chars: usize) -> String {
272 let mut truncated = String::new();
273 for (index, character) in text.chars().enumerate() {
274 if index >= max_chars {
275 truncated.push('…');
276 return truncated;
277 }
278 truncated.push(character);
279 }
280 truncated
281}
282
283async fn send_json(
284 sender: &mut futures_util::stream::SplitSink<WebSocket, Message>,
285 envelope: &ServerEnvelope,
286) -> anyhow::Result<()> {
287 let text = serde_json::to_string(envelope)?;
288 sender.send(Message::Text(text.into())).await?;
289 Ok(())
290}
291
292#[cfg(test)]
293mod tests {
294 use std::env;
295 use std::fs;
296 use std::path::PathBuf;
297 use std::sync::Arc;
298
299 use axum::extract::State;
300 use serde_json::{Value, json};
301 use tokio::time::{Duration, timeout};
302 use uuid::Uuid;
303
304 use super::build_health_payload;
305 use super::health_handler;
306 use super::parse_client_envelope;
307 use crate::bridge_protocol::{
308 ClientEnvelope, RuntimeRecord, RuntimeStatusSnapshot, RuntimeSummary,
309 };
310 use crate::config::Config;
311 use crate::state::BridgeState;
312
313 #[test]
314 fn build_health_payload_contains_bridge_metadata_and_primary_runtime() {
315 let runtime = RuntimeStatusSnapshot {
316 runtime_id: "primary".to_string(),
317 status: "running".to_string(),
318 codex_home: Some("/srv/codex-home".to_string()),
319 user_agent: Some("codex-mobile".to_string()),
320 platform_family: Some("linux".to_string()),
321 platform_os: Some("ubuntu".to_string()),
322 last_error: None,
323 pid: Some(4242),
324 updated_at_ms: 1234,
325 };
326 let runtime_record = RuntimeRecord {
327 runtime_id: "primary".to_string(),
328 display_name: "Primary".to_string(),
329 codex_home: Some("/srv/codex-home".to_string()),
330 codex_binary: "codex".to_string(),
331 is_primary: true,
332 auto_start: true,
333 created_at_ms: 1000,
334 updated_at_ms: 1000,
335 };
336 let runtimes = vec![RuntimeSummary::from_parts(&runtime_record, runtime.clone())];
337
338 let payload = build_health_payload(&runtime, &runtimes);
339
340 assert_eq!(payload["ok"], Value::Bool(true));
341 assert_eq!(
342 payload["bridgeVersion"],
343 Value::String(crate::BRIDGE_VERSION.to_string())
344 );
345 assert_eq!(
346 payload["buildHash"],
347 Value::String(crate::BRIDGE_BUILD_HASH.to_string())
348 );
349 assert_eq!(
350 payload["protocolVersion"],
351 Value::Number(crate::BRIDGE_PROTOCOL_VERSION.into())
352 );
353 assert_eq!(payload["runtimeCount"], Value::Number(1.into()));
354 assert_eq!(
355 payload["primaryRuntimeId"],
356 Value::String("primary".to_string())
357 );
358 assert_eq!(
359 payload["runtime"]["runtimeId"],
360 Value::String("primary".to_string())
361 );
362 assert_eq!(
363 payload["runtime"]["status"],
364 Value::String("running".to_string())
365 );
366 }
367
368 #[test]
369 fn parse_client_envelope_accepts_plain_hello_payload() {
370 let envelope = parse_client_envelope(
371 r#"{"kind":"hello","device_id":"device-alpha","last_ack_seq":7}"#,
372 )
373 .expect("hello payload 应可解析");
374
375 match envelope {
376 ClientEnvelope::Hello {
377 device_id,
378 last_ack_seq,
379 } => {
380 assert_eq!(device_id, "device-alpha");
381 assert_eq!(last_ack_seq, Some(7));
382 }
383 _ => panic!("应解析为 hello"),
384 }
385 }
386
387 #[test]
388 fn parse_client_envelope_accepts_double_encoded_hello_payload() {
389 let envelope = parse_client_envelope(
390 r#""{\"kind\":\"hello\",\"device_id\":\"device-beta\",\"last_ack_seq\":9}""#,
391 )
392 .expect("双重编码 hello payload 应可解析");
393
394 match envelope {
395 ClientEnvelope::Hello {
396 device_id,
397 last_ack_seq,
398 } => {
399 assert_eq!(device_id, "device-beta");
400 assert_eq!(last_ack_seq, Some(9));
401 }
402 _ => panic!("应解析为 hello"),
403 }
404 }
405
406 #[tokio::test]
407 async fn runtime_snapshot_returns_without_hanging() {
408 let state = bootstrap_test_state().await;
409
410 let snapshot = timeout(Duration::from_secs(2), state.runtime_snapshot())
411 .await
412 .expect("runtime_snapshot 超时");
413
414 assert_eq!(snapshot.runtime_id, "primary");
415 }
416
417 #[tokio::test]
418 async fn runtime_summaries_return_without_hanging() {
419 let state = bootstrap_test_state().await;
420
421 let summaries = timeout(Duration::from_secs(2), state.runtime_summaries())
422 .await
423 .expect("runtime_summaries 超时");
424
425 assert!(!summaries.is_empty());
426 assert_eq!(summaries[0].runtime_id, "primary");
427 }
428
429 #[tokio::test]
430 async fn health_handler_returns_without_hanging() {
431 let state = bootstrap_test_state().await;
432
433 let _ = timeout(
434 Duration::from_secs(2),
435 health_handler(State(Arc::clone(&state))),
436 )
437 .await
438 .expect("/health handler 超时");
439 }
440
441 #[tokio::test]
442 async fn hello_payload_returns_without_hanging() {
443 let state = bootstrap_test_state().await;
444
445 let (runtime, runtimes, ..) = timeout(
446 Duration::from_secs(2),
447 state.hello_payload("device-test", None),
448 )
449 .await
450 .expect("hello_payload 超时")
451 .expect("hello_payload 返回错误");
452
453 assert_eq!(runtime.runtime_id, "primary");
454 assert!(!runtimes.is_empty());
455 assert_eq!(runtimes[0].runtime_id, "primary");
456 }
457
458 #[tokio::test]
459 async fn list_runtimes_request_returns_without_hanging() {
460 let state = bootstrap_test_state().await;
461
462 let response = timeout(
463 Duration::from_secs(2),
464 state.handle_request("list_runtimes", json!({})),
465 )
466 .await
467 .expect("list_runtimes 超时")
468 .expect("list_runtimes 返回错误");
469
470 let runtimes = response["runtimes"].as_array().expect("runtimes 应为数组");
471 assert!(!runtimes.is_empty());
472 assert_eq!(
473 runtimes[0]["runtimeId"],
474 Value::String("primary".to_string())
475 );
476 }
477
478 #[tokio::test]
479 async fn get_runtime_status_request_returns_without_hanging() {
480 let state = bootstrap_test_state().await;
481
482 let response = timeout(
483 Duration::from_secs(2),
484 state.handle_request("get_runtime_status", json!({ "runtimeId": "primary" })),
485 )
486 .await
487 .expect("get_runtime_status 超时")
488 .expect("get_runtime_status 返回错误");
489
490 assert_eq!(
491 response["runtime"]["runtimeId"],
492 Value::String("primary".to_string())
493 );
494 }
495
496 async fn bootstrap_test_state() -> Arc<BridgeState> {
497 let base_dir = env::temp_dir().join(format!("codex-mobile-bridge-test-{}", Uuid::new_v4()));
498 fs::create_dir_all(&base_dir).expect("创建测试目录失败");
499 let db_path = base_dir.join("bridge.db");
500
501 let config = Config {
502 listen_addr: "127.0.0.1:0".to_string(),
503 token: "test-token".to_string(),
504 runtime_limit: 4,
505 db_path,
506 codex_home: None,
507 codex_binary: resolve_true_binary(),
508 workspace_roots: Vec::new(),
509 };
510
511 BridgeState::bootstrap(config)
512 .await
513 .expect("bootstrap 测试 BridgeState 失败")
514 }
515
516 fn resolve_true_binary() -> String {
517 for candidate in ["/usr/bin/true", "/bin/true"] {
518 if PathBuf::from(candidate).exists() {
519 return candidate.to_string();
520 }
521 }
522 "true".to_string()
523 }
524}