1use std::process::Command;
4use std::sync::Arc;
5use std::time::Duration;
6
7use tokio::time::Instant;
8
9use futures::StreamExt;
10use tokio::sync::broadcast;
11use tokio::{signal, time};
12use tokio_tungstenite::connect_async;
13use tokio_tungstenite::tungstenite::Message;
14
15use crate::cli;
16use crate::cli::service;
17use crate::engine::events::{TaskEvent, read_ws_credentials};
18use crate::ui;
19
20const RELAY_RETRY: Duration = Duration::from_secs(3);
21const SERVICE_WAIT: Duration = Duration::from_secs(30);
22
23pub async fn open(print: bool, dev: bool) -> anyhow::Result<()> {
24 if dev {
25 return serve_dev(print).await;
26 }
27
28 if let Some(endpoint) = ui::endpoint().await {
29 return launch(&endpoint, print).await;
30 }
31
32 println!("Starting the orch service");
34 service::start()?;
35 let deadline = Instant::now() + SERVICE_WAIT;
36 while Instant::now() < deadline {
37 if let Some(endpoint) = ui::endpoint().await {
38 return launch(&endpoint, print).await;
39 }
40
41 time::sleep(Duration::from_millis(500)).await;
42 }
43
44 anyhow::bail!("the orch service did not start its web UI. Check `orch log`")
45}
46
47async fn sign_in_url(endpoint: &ui::Endpoint) -> anyhow::Result<String> {
49 let url = format!("http://127.0.0.1:{}/", endpoint.port);
50 let code: serde_json::Value = reqwest::Client::new()
51 .post(format!("{url}login-code"))
52 .bearer_auth(&endpoint.token)
53 .send()
54 .await?
55 .error_for_status()?
56 .json()
57 .await?;
58 let code = code
59 .get("code")
60 .and_then(|c| c.as_str())
61 .ok_or_else(|| anyhow::anyhow!("the orch service sent no sign-in code"))?;
62 Ok(format!("{url}?code={code}"))
63}
64
65async fn launch(endpoint: &ui::Endpoint, print: bool) -> anyhow::Result<()> {
66 let url = format!("http://127.0.0.1:{}/", endpoint.port);
67 let login = sign_in_url(endpoint).await?;
68 if print {
69 println!("{login}");
70 return Ok(());
71 }
72
73 let opener = if cfg!(target_os = "macos") {
74 "open"
75 } else {
76 "xdg-open"
77 };
78 let status = Command::new(opener).arg(&login).status()?;
79 if !status.success() {
80 anyhow::bail!("{opener} failed, run `orch ui --print` and open the address yourself");
81 }
82
83 println!("Opened {url}");
84 Ok(())
85}
86
87async fn serve_dev(print: bool) -> anyhow::Result<()> {
89 let store = Arc::new(cli::init_store().await?);
90 let (tx, _) = broadcast::channel(256);
91 tokio::spawn(relay_events(tx.clone()));
92 let endpoint = ui::serve_on(store, tx).await?;
93 launch(&endpoint, print).await?;
94 println!("Serving the web UI from this build. Ctrl+C to stop");
95 signal::ctrl_c().await?;
96 Ok(())
97}
98
99async fn relay_events(tx: broadcast::Sender<TaskEvent>) {
100 loop {
101 if let Ok((port, token)) = read_ws_credentials() {
102 let url = format!(
103 "ws://127.0.0.1:{port}/events?token={}",
104 urlencoding::encode(&token)
105 );
106 if let Ok((ws, _)) = connect_async(&url).await {
107 let (_write, mut read) = ws.split();
108 while let Some(Ok(msg)) = read.next().await {
109 if let Message::Text(text) = msg
110 && let Ok(event) = serde_json::from_str::<TaskEvent>(&text)
111 {
112 let _ = tx.send(event);
113 }
114 }
115 }
116 }
117
118 time::sleep(RELAY_RETRY).await;
119 }
120}