forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug.rs
More file actions
294 lines (250 loc) · 8.8 KB
/
debug.rs
File metadata and controls
294 lines (250 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
use anyhow::Result;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use crate::server;
pub async fn run_debug_command(
command: &str,
arg: &str,
session_id: Option<String>,
socket_path: Option<String>,
_wait: bool,
) -> Result<()> {
match command {
"list" => return debug_list_servers().await,
"start" => return debug_start_server(arg, socket_path).await,
_ => {}
}
let debug_socket = if let Some(ref path) = socket_path {
let main_path = std::path::PathBuf::from(path);
let filename = main_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("jcode.sock");
let debug_filename = filename.replace(".sock", "-debug.sock");
main_path.with_file_name(debug_filename)
} else {
server::debug_socket_path()
};
if !crate::transport::is_socket_path(&debug_socket) {
eprintln!("Debug socket not found at {:?}", debug_socket);
eprintln!("\nMake sure:");
eprintln!(" 1. A jcode server is running (jcode or jcode serve)");
eprintln!(" 2. debug_socket is enabled in ~/.jcode/config.toml");
eprintln!(" [display]");
eprintln!(" debug_socket = true");
eprintln!("\nOr use 'jcode debug start' to start a server.");
eprintln!("Use 'jcode debug list' to see running servers.");
anyhow::bail!("Debug socket not available");
}
let stream = server::connect_socket(&debug_socket).await?;
let (reader, mut writer) = stream.into_split();
let mut reader = BufReader::new(reader);
let debug_cmd = if arg.is_empty() {
command.to_string()
} else {
format!("{}:{}", command, arg)
};
let request = serde_json::json!({
"type": "debug_command",
"id": 1,
"command": debug_cmd,
"session_id": session_id,
});
let mut json = serde_json::to_string(&request)?;
json.push('\n');
writer.write_all(json.as_bytes()).await?;
let mut line = String::new();
let n = reader.read_line(&mut line).await?;
if n == 0 {
anyhow::bail!("Server disconnected before sending response");
}
let response: serde_json::Value = serde_json::from_str(&line)?;
match response.get("type").and_then(|v| v.as_str()) {
Some("debug_response") => {
let ok = response
.get("ok")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let output = response
.get("output")
.and_then(|v| v.as_str())
.unwrap_or("");
if ok {
println!("{}", output);
} else {
eprintln!("Error: {}", output);
std::process::exit(1);
}
}
Some("error") => {
let message = response
.get("message")
.and_then(|v| v.as_str())
.unwrap_or("Unknown error");
eprintln!("Error: {}", message);
std::process::exit(1);
}
_ => {
println!("{}", serde_json::to_string_pretty(&response)?);
}
}
Ok(())
}
async fn debug_list_servers() -> Result<()> {
let mut servers = Vec::new();
let runtime_dir = crate::storage::runtime_dir();
let mut scan_dirs = vec![runtime_dir.clone()];
let temp_dir = std::env::temp_dir();
if temp_dir != runtime_dir {
scan_dirs.push(temp_dir);
}
for dir in scan_dirs {
if let Ok(entries) = std::fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str())
&& name.starts_with("jcode")
&& name.ends_with(".sock")
&& !name.contains("-debug")
{
servers.push(path);
}
}
}
}
if servers.is_empty() {
println!("No running jcode servers found.");
println!("\nStart one with: jcode debug start");
return Ok(());
}
println!("Running jcode servers:\n");
for socket_path in servers {
let debug_socket = {
let filename = socket_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("jcode.sock");
let debug_filename = filename.replace(".sock", "-debug.sock");
socket_path.with_file_name(debug_filename)
};
let alive = crate::transport::Stream::connect(&socket_path)
.await
.is_ok();
let debug_enabled = if crate::transport::is_socket_path(&debug_socket) {
crate::transport::Stream::connect(&debug_socket)
.await
.is_ok()
} else {
false
};
let session_info = if debug_enabled {
get_server_info(&debug_socket).await.unwrap_or_default()
} else {
String::new()
};
let status = if alive {
if debug_enabled {
format!("✓ running, debug: enabled{}", session_info)
} else {
"✓ running, debug: disabled".to_string()
}
} else {
"✗ not responding (stale socket?)".to_string()
};
println!(" {} ({})", socket_path.display(), status);
}
println!("\nUse -s/--socket to target a specific server:");
println!(" jcode debug -s /path/to/socket.sock sessions");
Ok(())
}
async fn get_server_info(debug_socket: &std::path::Path) -> Result<String> {
use crate::transport::Stream;
let stream = Stream::connect(debug_socket).await?;
let (reader, mut writer) = stream.into_split();
let mut reader = BufReader::new(reader);
let request = serde_json::json!({
"type": "debug_command",
"id": 1,
"command": "sessions",
});
let mut json = serde_json::to_string(&request)?;
json.push('\n');
writer.write_all(json.as_bytes()).await?;
let mut line = String::new();
let n = tokio::time::timeout(
std::time::Duration::from_secs(2),
reader.read_line(&mut line),
)
.await??;
if n == 0 {
return Ok(String::new());
}
let response: serde_json::Value = serde_json::from_str(&line)?;
if let Some(output) = response.get("output").and_then(|v| v.as_str())
&& let Ok(sessions) = serde_json::from_str::<Vec<String>>(output)
{
return Ok(format!(", sessions: {}", sessions.len()));
}
Ok(String::new())
}
async fn debug_start_server(arg: &str, socket_path: Option<String>) -> Result<()> {
let socket = socket_path.unwrap_or_else(|| {
if !arg.is_empty() {
arg.to_string()
} else {
server::socket_path().to_string_lossy().to_string()
}
});
let socket_pathbuf = std::path::PathBuf::from(&socket);
if crate::transport::is_socket_path(&socket_pathbuf)
&& crate::transport::Stream::connect(&socket_pathbuf)
.await
.is_ok()
{
eprintln!("Server already running at {}", socket);
eprintln!("Use 'jcode debug list' to see all servers.");
return Ok(());
}
let debug_socket = {
let filename = socket_pathbuf
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("jcode.sock");
let debug_filename = filename.replace(".sock", "-debug.sock");
socket_pathbuf.with_file_name(debug_filename)
};
let _ = std::fs::remove_file(&debug_socket);
eprintln!("Starting jcode server...");
let exe = std::env::current_exe()?;
let mut cmd = std::process::Command::new(&exe);
cmd.arg("serve");
if socket != server::socket_path().to_string_lossy() {
cmd.arg("--socket").arg(&socket);
}
cmd.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()?;
let start = std::time::Instant::now();
loop {
if start.elapsed() > std::time::Duration::from_secs(10) {
anyhow::bail!("Server failed to start within 10 seconds");
}
if crate::transport::is_socket_path(&socket_pathbuf)
&& crate::transport::Stream::connect(&socket_pathbuf)
.await
.is_ok()
{
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
eprintln!("✓ Server started at {}", socket);
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
if crate::transport::is_socket_path(&debug_socket) {
eprintln!("✓ Debug socket at {}", debug_socket.display());
} else {
eprintln!("⚠ Debug socket not enabled. Add to ~/.jcode/config.toml:");
eprintln!(" [display]");
eprintln!(" debug_socket = true");
}
Ok(())
}