GeezerVison is showing github.com — refactor(process-daemon): simplify Windows pipe mode (#63346) · drpr/opencode@61325d1
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/process-daemon/SPEC.md +25-25Lines changed: 25 additions & 25 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -145,12 +145,13 @@ starts a pipe process: any command without a terminal. Both return | 145 | 145 | - On Unix the child gets its own process group and an empty signal mask with | 146 | 146 | default actions (the daemon blocks SIGTERM and SIGINT, and std keeps the | 147 | 147 | mask across exec). On Windows it is created with `CREATE_NO_WINDOW` (no | 148 | | - console window and no console) and is placed in a kill-on-close job from | 149 | | - creation. The program is resolved the way `CreateProcessW` resolves a bare | 150 | | - executable name (the application directory, the current directory, the | 151 | | - system directories and `PATH`); the daemon does not run a shell unless the | 152 | | - request itself asks for one, and passing `["/c", command]` to `cmd.exe` is | 153 | | - the caller's job. | | 148 | + console) inside a kill-on-close job. For a bare executable name, | | 149 | + `CreateProcessW` searches the directory containing the daemon executable, | | 150 | + the daemon's current directory, the 32-bit and then 16-bit Windows system | | 151 | + directories, the Windows directory, and finally the directories in the | | 152 | + daemon's `PATH`. This search is independent of the request's `cwd` and `env`, | | 153 | + which set the child's working directory and environment. To invoke a shell, | | 154 | + the caller must request one explicitly, e.g. `cmd.exe` with `["/c", command]`. | 154 | 155 | - `output_path` must be absolute. The daemon opens it before spawning, | 155 | 156 | truncating an existing file or creating one (mode `0666` minus the daemon's | 156 | 157 | umask on Unix), and refuses a symlink or other reparse point as the final | @@ -177,17 +178,17 @@ starts a pipe process: any command without a terminal. Both return | 177 | 178 | nothing reads what comes later. The file is closed before the exit is | 178 | 179 | published. | 179 | 180 | - `Exited` and the lifecycle carry `signal`, the signal's name such as | 180 | | - `"SIGTERM"`, when the daemon terminated the process; `exit_code` is then | 181 | | - null. `signal` is left out when there is none. | | 181 | + `"SIGTERM"`, when a signal ended the process (on Windows, when the daemon | | 182 | + signalled it); `exit_code` is then null. `signal` is left out when there is | | 183 | + none. | 182 | 184 | - On Unix an exited pipe process stays listed, as a zombie, until `terminate`. | 183 | 185 | The zombie keeps its PID and process group ID reserved, so killing the group | 184 | 186 | can never reach an unrelated process. On Windows the process object and job | 185 | 187 | handle stay open until `terminate`, so the PID is not reused either. | 186 | | - `terminate` kills the whole tree (SIGKILL on Unix; `TerminateJobObject`, or | 187 | | - the main process only when no job could be used, on Windows), reaps it and | 188 | | - removes the process; it never waits on a descendant that left the process | 189 | | - group or job and still holds the pipe. The daemon never deletes output | 190 | | - files. | | 188 | + `terminate` kills the whole tree (SIGKILL on Unix; the job on Windows), | | 189 | + reaps it and removes the process; it never waits on a descendant that left | | 190 | + the process group or job and still holds the pipe. The daemon never deletes | | 191 | + output files. | 191 | 192 |
| 192 | 193 | ### Line count | 193 | 194 |
| @@ -221,18 +222,17 @@ only; left out for PTYs), `output_error` (left out when there is none) and | 221 | 222 | `signal { id, signal }` (pipe only; `"SIGTERM"`, `"SIGINT"` or `"SIGKILL"`) | 222 | 223 | signals the process tree and returns `Ok`. On Unix the signal goes to the | 223 | 224 | process group and the child, as a real signal. **On Windows every signal is a | 224 | | -hard kill** of the job (or of the main process when no job could be used) with | 225 | | -`TerminateJobObject`/`TerminateProcess`: there is no console and no console | 226 | | -control event, so SIGTERM and SIGINT cannot be caught or trapped, and the exit | 227 | | -reports the signal that was sent, not a platform exit code. Unlike | 228 | | -`terminate`, `signal` keeps the process: `wait` then gets a normal `Exited` | 229 | | -with `signal`. Signalling an exited process is allowed and reaches whatever is | 230 | | -left of its group or job (an empty group is not an error); after `terminate` | 231 | | -the process is gone and `signal` fails. If an outer job refuses the child | 232 | | -(`ERROR_ACCESS_DENIED`, for example a job with UI restrictions), the daemon | 233 | | -runs the command anyway without a job, logs a warning once, and kills only the | 234 | | -main process with `TerminateProcess`; descendants then survive a signal or | 235 | | -terminate. | | 225 | +hard kill** of the job: there is no console, so SIGTERM and SIGINT cannot be | | 226 | +caught, and the exit reports the signal that was sent, not a platform exit | | 227 | +code. Unlike `terminate`, `signal` keeps the process: `wait` then gets a normal | | 228 | +`Exited` with `signal`. Signalling an exited process is allowed and reaches | | 229 | +whatever is left of its group or job (an empty group is not an error); after | | 230 | +`terminate` the process is gone and `signal` fails. | | 231 | + | | 232 | +If an outer job refuses the child (`ERROR_ACCESS_DENIED`, for example a job | | 233 | +with UI restrictions), the daemon runs the command anyway without a job, logs | | 234 | +a warning once, and kills only the main process; descendants then survive a | | 235 | +signal or terminate. | 236 | 236 |
| 237 | 237 | `metadata` on `create_pipe` is an opaque JSON object the daemon stores and | 238 | 238 | returns as `pipe.metadata` without interpreting it. `set_metadata { id, | |
Collapse file Copy file name to clipboardExpand all lines: packages/process-daemon/src/daemon/windows.rs +4-13Lines changed: 4 additions & 13 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -30,7 +30,7 @@ use windows_sys::Win32::System::WindowsProgramming::{ | 30 | 30 | use super::{LOCK_FILE, REGISTRATION_FILE, Registration, registration_path, sweep}; | 31 | 31 | use crate::protocol::{PROTOCOL_VERSION, features}; | 32 | 32 | use crate::transport::Listener; | 33 | | -use crate::transport::windows::{owned_handle, security::PrivateSecurity}; | | 33 | +use crate::transport::windows::{owned_handle, security::PrivateSecurity, wide}; | 34 | 34 |
| 35 | 35 | pub(super) fn read_registration(directory: &Path) -> Result<Registration> { | 36 | 36 | let security = PrivateSecurity::new()?; | @@ -74,9 +74,9 @@ impl Runtime { | 74 | 74 | if let Some(parent) = directory.parent() { | 75 | 75 | fs::create_dir_all(parent)?; | 76 | 76 | } | 77 | | - let wide = wide_path(directory)?; | | 77 | + let directory_wide = wide(directory.as_os_str())?; | 78 | 78 | // SAFETY: wide path and private descriptor are valid through creation. | 79 | | - if unsafe { CreateDirectoryW(wide.as_ptr(), &security.attributes()) } == 0 { | | 79 | + if unsafe { CreateDirectoryW(directory_wide.as_ptr(), &security.attributes()) } == 0 { | 80 | 80 | let error = std::io::Error::last_os_error(); | 81 | 81 | if error.raw_os_error() != Some(ERROR_ALREADY_EXISTS as i32) { | 82 | 82 | return Err(error.into()); | @@ -300,7 +300,7 @@ fn open( | 300 | 300 | sharing: u32, | 301 | 301 | security: &PrivateSecurity, | 302 | 302 | ) -> Result<File> { | 303 | | - let path = wide_path(path)?; | | 303 | + let path = wide(path.as_os_str())?; | 304 | 304 | // SAFETY: all pointers are valid; OPEN_REPARSE_POINT lets check_kind reject | 305 | 305 | // links rather than inspecting a different target after following them. | 306 | 306 | let handle = unsafe { | @@ -332,15 +332,6 @@ fn check_kind(file: &File, directory: bool) -> Result<()> { | 332 | 332 | Ok(()) | 333 | 333 | } | 334 | 334 |
| 335 | | -fn wide_path(path: &Path) -> Result<Vec<u16>> { | 336 | | - let mut wide = path.as_os_str().encode_wide().collect::<Vec<_>>(); | 337 | | - if wide.contains(&0) { | 338 | | - bail!("PTY storage path contains NUL"); | 339 | | - } | 340 | | - wide.push(0); | 341 | | - Ok(wide) | 342 | | -} | 343 | | - | 344 | 335 | #[cfg(test)] | 345 | 336 | mod tests { | 346 | 337 | use super::*; | |
Collapse file Copy file name to clipboardExpand all lines: packages/process-daemon/src/service/pipe.rs +24-11Lines changed: 24 additions & 11 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 21 | 21 | use std::fs::File; | 22 | 22 | use std::io::{self, Write}; | 23 | 23 | use std::sync::{Arc, Mutex, RwLock}; | 24 | | -use std::thread::JoinHandle; | | 24 | +use std::thread::{self, JoinHandle}; | 25 | 25 | use std::time::Duration; | 26 | 26 |
| 27 | 27 | use anyhow::{Context, Result}; | @@ -149,10 +149,11 @@ fn new_pipe_info(id: TerminalId, pid: u32, request: CreatePipe) -> ProcessInfo { | 149 | 149 | } | 150 | 150 | } | 151 | 151 |
| 152 | | -/// The platform reader and waiter, each spawning its named worker thread. | 153 | | -struct Threads { | 154 | | - reader: Box<dyn FnOnce(OutputSink) -> io::Result<JoinHandle<()>>>, | 155 | | - waiter: Box<dyn FnOnce(Sender<ActorMessage>) -> io::Result<JoinHandle<()>>>, | | 152 | +/// The waiter's result, and something dropped only after the exit message is | | 153 | +/// sent (Unix starts the reader's drain by dropping a pipe writer). | | 154 | +struct Waiter { | | 155 | + exit: io::Result<Exit>, | | 156 | + after: Box<dyn Send>, | 156 | 157 | } | 157 | 158 |
| 158 | 159 | /// Registers a spawned pipe process with its actor, then runs the platform's | @@ -163,9 +164,9 @@ fn start_pipe( | 163 | 164 | order: u64, | 164 | 165 | request: CreatePipe, | 165 | 166 | process: Arc<Process>, | 166 | | - sink: File, | 167 | 167 | cancel: Box<dyn Send>, | 168 | | - threads: Threads, | | 168 | + reader: impl FnOnce(Sender<ActorMessage>) + Send + 'static, | | 169 | + waiter: impl FnOnce() -> Waiter + Send + 'static, | 169 | 170 | ) -> Result<TerminalHandle> { | 170 | 171 | let info = Arc::new(RwLock::new(new_pipe_info(id, process.pid(), request))); | 171 | 172 | // Nothing is ever written to a pipe process; a disconnected queue | @@ -196,21 +197,33 @@ fn start_pipe( | 196 | 197 | thread, | 197 | 198 | } = actor; | 198 | 199 | let mut joins = vec![thread]; | 199 | | - let reader = (threads.reader)(OutputSink::new(sink, actor_tx.clone())); | | 200 | + let reader_actor_tx = actor_tx.clone(); | | 201 | + let reader = thread::Builder::new() | | 202 | + .name(format!("opencode-pty-reader-{id}")) | | 203 | + .spawn(move || reader(reader_actor_tx)) | | 204 | + .context("failed to spawn terminal reader"); | 200 | 205 | let reader = match reader { | 201 | 206 | Ok(reader) => reader, | 202 | 207 | Err(error) => { | 203 | 208 | stop(shutdown_tx, cancel, &process, joins); | 204 | | - return Err(error).context("failed to spawn terminal reader"); | | 209 | + return Err(error); | 205 | 210 | } | 206 | 211 | }; | 207 | 212 | joins.push(reader); | 208 | | - let waiter = (threads.waiter)(actor_tx.clone()); | | 213 | + let wait_actor_tx = actor_tx.clone(); | | 214 | + let waiter = thread::Builder::new() | | 215 | + .name(format!("opencode-pty-wait-{id}")) | | 216 | + .spawn(move || { | | 217 | + let Waiter { exit, after } = waiter(); | | 218 | + let _ = wait_actor_tx.send(exit_message(exit)); | | 219 | + drop(after); | | 220 | + }) | | 221 | + .context("failed to spawn terminal child waiter"); | 209 | 222 | let waiter = match waiter { | 210 | 223 | Ok(waiter) => waiter, | 211 | 224 | Err(error) => { | 212 | 225 | stop(shutdown_tx, cancel, &process, joins); | 213 | | - return Err(error).context("failed to spawn terminal child waiter"); | | 226 | + return Err(error); | 214 | 227 | } | 215 | 228 | }; | 216 | 229 | joins.push(waiter); | |
Collapse file Copy file name to clipboardExpand all lines: packages/process-daemon/src/service/pipe/unix.rs +7-22Lines changed: 7 additions & 22 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -20,14 +20,13 @@ use std::os::unix::fs::OpenOptionsExt; | 20 | 20 | use std::os::unix::process::CommandExt; | 21 | 21 | use std::process::{Command, Stdio}; | 22 | 22 | use std::sync::{Arc, Mutex, PoisonError, RwLock}; | 23 | | -use std::thread; | 24 | 23 | use std::time::Instant; | 25 | 24 |
| 26 | 25 | use anyhow::{Context, Result, bail}; | 27 | 26 | use nix::errno::Errno; | 28 | 27 | use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; | 29 | 28 |
| 30 | | -use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, exit_message, start_pipe}; | | 29 | +use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, start_pipe}; | 31 | 30 | use crate::service::{CreatePipe, ProcessSignal, TerminalHandle, TerminalId}; | 32 | 31 |
| 33 | 32 | /// Serializes pipe creation against `spawn`. macOS has no `pipe2`, so std | @@ -127,32 +126,18 @@ impl TerminalHandle { | 127 | 126 | // Dropping `Child` neither waits nor kills; `Process` reaps it. | 128 | 127 | drop(child); | 129 | 128 |
| 130 | | - let reader_id = id; | 131 | | - let waiter_id = id; | | 129 | + let pid = process.pid; | 132 | 130 | start_pipe( | 133 | 131 | id, | 134 | 132 | order, | 135 | 133 | request, | 136 | 134 | Arc::clone(&process), | 137 | | - sink, | 138 | 135 | Box::new(cancel_writer), | 139 | | - super::Threads { | 140 | | - reader: Box::new(move |sink| { | 141 | | - thread::Builder::new() | 142 | | - .name(format!("opencode-pty-reader-{reader_id}")) | 143 | | - .spawn(move || read_output(output, sink, cancel, exited)) | 144 | | - }), | 145 | | - waiter: Box::new(move |actor| { | 146 | | - let pid = process.pid; | 147 | | - // Spawned last: the waiter must be joined before `reap`. | 148 | | - thread::Builder::new() | 149 | | - .name(format!("opencode-pty-wait-{waiter_id}")) | 150 | | - .spawn(move || { | 151 | | - let _ = actor.send(exit_message(wait_exit(pid))); | 152 | | - // Starts the reader's drain deadline. | 153 | | - drop(exited_writer); | 154 | | - }) | 155 | | - }), | | 136 | + move |actor| read_output(output, OutputSink::new(sink, actor), cancel, exited), | | 137 | + move || super::Waiter { | | 138 | + exit: wait_exit(pid), | | 139 | + // Starts the reader's drain deadline, after the exit message. | | 140 | + after: Box::new(exited_writer), | 156 | 141 | }, | 157 | 142 | ) | 158 | 143 | } | |
|