Skip to main content

codex_mobile_bridge/
server.rs

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                    bridge_version: crate::BRIDGE_VERSION.to_string(),
200                    protocol_version: crate::BRIDGE_PROTOCOL_VERSION,
201                    runtime,
202                    runtimes,
203                    workspaces,
204                    pending_requests,
205                },
206            )
207            .await?;
208
209            info!(
210                "bridge ws hello 已完成 device_id={} replay_events={}",
211                connected_device_id,
212                replay_events.len()
213            );
214            for event in replay_events {
215                send_json(sender, &event_envelope(event)).await?;
216            }
217        }
218        ClientEnvelope::Request {
219            request_id,
220            action,
221            payload,
222        } => {
223            if device_id.is_none() {
224                send_json(
225                    sender,
226                    &error_response(
227                        request_id,
228                        ApiError::new("handshake_required", "请先发送 hello"),
229                    ),
230                )
231                .await?;
232                return Ok(true);
233            }
234
235            let response = match state.handle_request(&action, payload).await {
236                Ok(data) => ok_response(request_id, data),
237                Err(error) => error_response(
238                    request_id,
239                    ApiError::new("request_failed", error.to_string()),
240                ),
241            };
242            send_json(sender, &response).await?;
243        }
244        ClientEnvelope::AckEvents { last_seq } => {
245            if let Some(device_id) = device_id.as_deref() {
246                state.ack_events(device_id, last_seq)?;
247            }
248        }
249        ClientEnvelope::Ping => {
250            send_json(
251                sender,
252                &ServerEnvelope::Pong {
253                    server_time_ms: crate::bridge_protocol::now_millis(),
254                },
255            )
256            .await?;
257        }
258    }
259
260    Ok(true)
261}
262
263fn parse_client_envelope(text: &str) -> anyhow::Result<ClientEnvelope> {
264    match serde_json::from_str::<ClientEnvelope>(text) {
265        Ok(envelope) => Ok(envelope),
266        Err(primary_error) => {
267            let nested_payload = serde_json::from_str::<String>(text).map_err(|_| primary_error)?;
268            serde_json::from_str::<ClientEnvelope>(&nested_payload).map_err(Into::into)
269        }
270    }
271}
272
273fn truncate_text(text: &str, max_chars: usize) -> String {
274    let mut truncated = String::new();
275    for (index, character) in text.chars().enumerate() {
276        if index >= max_chars {
277            truncated.push('…');
278            return truncated;
279        }
280        truncated.push(character);
281    }
282    truncated
283}
284
285async fn send_json(
286    sender: &mut futures_util::stream::SplitSink<WebSocket, Message>,
287    envelope: &ServerEnvelope,
288) -> anyhow::Result<()> {
289    let text = serde_json::to_string(envelope)?;
290    sender.send(Message::Text(text.into())).await?;
291    Ok(())
292}
293
294#[cfg(test)]
295mod tests {
296    use std::env;
297    use std::fs;
298    use std::path::PathBuf;
299    use std::sync::Arc;
300
301    use axum::extract::State;
302    use serde_json::{Value, json};
303    use tokio::time::{Duration, timeout};
304    use uuid::Uuid;
305
306    use super::build_health_payload;
307    use super::health_handler;
308    use super::parse_client_envelope;
309    use crate::bridge_protocol::{
310        ClientEnvelope, RuntimeRecord, RuntimeStatusSnapshot, RuntimeSummary,
311    };
312    use crate::config::Config;
313    use crate::state::BridgeState;
314
315    #[test]
316    fn build_health_payload_contains_bridge_metadata_and_primary_runtime() {
317        let runtime = RuntimeStatusSnapshot {
318            runtime_id: "primary".to_string(),
319            status: "running".to_string(),
320            codex_home: Some("/srv/codex-home".to_string()),
321            user_agent: Some("codex-mobile".to_string()),
322            platform_family: Some("linux".to_string()),
323            platform_os: Some("ubuntu".to_string()),
324            last_error: None,
325            pid: Some(4242),
326            updated_at_ms: 1234,
327        };
328        let runtime_record = RuntimeRecord {
329            runtime_id: "primary".to_string(),
330            display_name: "Primary".to_string(),
331            codex_home: Some("/srv/codex-home".to_string()),
332            codex_binary: "codex".to_string(),
333            is_primary: true,
334            auto_start: true,
335            created_at_ms: 1000,
336            updated_at_ms: 1000,
337        };
338        let runtimes = vec![RuntimeSummary::from_parts(&runtime_record, runtime.clone())];
339
340        let payload = build_health_payload(&runtime, &runtimes);
341
342        assert_eq!(payload["ok"], Value::Bool(true));
343        assert_eq!(
344            payload["bridgeVersion"],
345            Value::String(crate::BRIDGE_VERSION.to_string())
346        );
347        assert_eq!(
348            payload["buildHash"],
349            Value::String(crate::BRIDGE_BUILD_HASH.to_string())
350        );
351        assert_eq!(
352            payload["protocolVersion"],
353            Value::Number(crate::BRIDGE_PROTOCOL_VERSION.into())
354        );
355        assert_eq!(payload["runtimeCount"], Value::Number(1.into()));
356        assert_eq!(
357            payload["primaryRuntimeId"],
358            Value::String("primary".to_string())
359        );
360        assert_eq!(
361            payload["runtime"]["runtimeId"],
362            Value::String("primary".to_string())
363        );
364        assert_eq!(
365            payload["runtime"]["status"],
366            Value::String("running".to_string())
367        );
368    }
369
370    #[test]
371    fn parse_client_envelope_accepts_plain_hello_payload() {
372        let envelope = parse_client_envelope(
373            r#"{"kind":"hello","device_id":"device-alpha","last_ack_seq":7}"#,
374        )
375        .expect("hello payload 应可解析");
376
377        match envelope {
378            ClientEnvelope::Hello {
379                device_id,
380                last_ack_seq,
381            } => {
382                assert_eq!(device_id, "device-alpha");
383                assert_eq!(last_ack_seq, Some(7));
384            }
385            _ => panic!("应解析为 hello"),
386        }
387    }
388
389    #[test]
390    fn parse_client_envelope_accepts_double_encoded_hello_payload() {
391        let envelope = parse_client_envelope(
392            r#""{\"kind\":\"hello\",\"device_id\":\"device-beta\",\"last_ack_seq\":9}""#,
393        )
394        .expect("双重编码 hello payload 应可解析");
395
396        match envelope {
397            ClientEnvelope::Hello {
398                device_id,
399                last_ack_seq,
400            } => {
401                assert_eq!(device_id, "device-beta");
402                assert_eq!(last_ack_seq, Some(9));
403            }
404            _ => panic!("应解析为 hello"),
405        }
406    }
407
408    #[tokio::test]
409    async fn runtime_snapshot_returns_without_hanging() {
410        let state = bootstrap_test_state().await;
411
412        let snapshot = timeout(Duration::from_secs(2), state.runtime_snapshot())
413            .await
414            .expect("runtime_snapshot 超时");
415
416        assert_eq!(snapshot.runtime_id, "primary");
417    }
418
419    #[tokio::test]
420    async fn runtime_summaries_return_without_hanging() {
421        let state = bootstrap_test_state().await;
422
423        let summaries = timeout(Duration::from_secs(2), state.runtime_summaries())
424            .await
425            .expect("runtime_summaries 超时");
426
427        assert!(!summaries.is_empty());
428        assert_eq!(summaries[0].runtime_id, "primary");
429    }
430
431    #[tokio::test]
432    async fn health_handler_returns_without_hanging() {
433        let state = bootstrap_test_state().await;
434
435        let _ = timeout(
436            Duration::from_secs(2),
437            health_handler(State(Arc::clone(&state))),
438        )
439        .await
440        .expect("/health handler 超时");
441    }
442
443    #[tokio::test]
444    async fn hello_payload_returns_without_hanging() {
445        let state = bootstrap_test_state().await;
446
447        let (runtime, runtimes, ..) = timeout(
448            Duration::from_secs(2),
449            state.hello_payload("device-test", None),
450        )
451        .await
452        .expect("hello_payload 超时")
453        .expect("hello_payload 返回错误");
454
455        assert_eq!(runtime.runtime_id, "primary");
456        assert!(!runtimes.is_empty());
457        assert_eq!(runtimes[0].runtime_id, "primary");
458    }
459
460    #[tokio::test]
461    async fn list_runtimes_request_returns_without_hanging() {
462        let state = bootstrap_test_state().await;
463
464        let response = timeout(
465            Duration::from_secs(2),
466            state.handle_request("list_runtimes", json!({})),
467        )
468        .await
469        .expect("list_runtimes 超时")
470        .expect("list_runtimes 返回错误");
471
472        let runtimes = response["runtimes"].as_array().expect("runtimes 应为数组");
473        assert!(!runtimes.is_empty());
474        assert_eq!(
475            runtimes[0]["runtimeId"],
476            Value::String("primary".to_string())
477        );
478    }
479
480    #[tokio::test]
481    async fn get_runtime_status_request_returns_without_hanging() {
482        let state = bootstrap_test_state().await;
483
484        let response = timeout(
485            Duration::from_secs(2),
486            state.handle_request("get_runtime_status", json!({ "runtimeId": "primary" })),
487        )
488        .await
489        .expect("get_runtime_status 超时")
490        .expect("get_runtime_status 返回错误");
491
492        assert_eq!(
493            response["runtime"]["runtimeId"],
494            Value::String("primary".to_string())
495        );
496    }
497
498    async fn bootstrap_test_state() -> Arc<BridgeState> {
499        let base_dir = env::temp_dir().join(format!("codex-mobile-bridge-test-{}", Uuid::new_v4()));
500        fs::create_dir_all(&base_dir).expect("创建测试目录失败");
501        let db_path = base_dir.join("bridge.db");
502
503        let config = Config {
504            listen_addr: "127.0.0.1:0".to_string(),
505            token: "test-token".to_string(),
506            runtime_limit: 4,
507            db_path,
508            codex_home: None,
509            codex_binary: resolve_true_binary(),
510            workspace_roots: Vec::new(),
511        };
512
513        BridgeState::bootstrap(config)
514            .await
515            .expect("bootstrap 测试 BridgeState 失败")
516    }
517
518    fn resolve_true_binary() -> String {
519        for candidate in ["/usr/bin/true", "/bin/true"] {
520            if PathBuf::from(candidate).exists() {
521                return candidate.to_string();
522            }
523        }
524        "true".to_string()
525    }
526}