GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — refactor(process-daemon): simplify Windows pipe mode (#63346) · drpr/opencode@61325d1

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/process-daemon
    • SPEC.md
    • src
      • daemon
        • windows.rs
      • service
        • pipe.rs
        • pipe
          • unix.rs
          • windows.rs
      • transport
        • windows.rs
    • tests
      • pipe_windows.rs
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/process-daemon/SPEC.md‎

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 numberDiff line numberDiff line change
@@ -145,12 +145,13 @@ starts a pipe process: any command without a terminal. Both return
145145
- On Unix the child gets its own process group and an empty signal mask with
146146
default actions (the daemon blocks SIGTERM and SIGINT, and std keeps the
147147
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]`.
154155
- `output_path` must be absolute. The daemon opens it before spawning,
155156
truncating an existing file or creating one (mode `0666` minus the daemon's
156157
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
177178
nothing reads what comes later. The file is closed before the exit is
178179
published.
179180
- `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.
182184
- On Unix an exited pipe process stays listed, as a zombie, until `terminate`.
183185
The zombie keeps its PID and process group ID reserved, so killing the group
184186
can never reach an unrelated process. On Windows the process object and job
185187
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.
191192

192193
### Line count
193194

@@ -221,18 +222,17 @@ only; left out for PTYs), `output_error` (left out when there is none) and
221222
`signal { id, signal }` (pipe only; `"SIGTERM"`, `"SIGINT"` or `"SIGKILL"`)
222223
signals the process tree and returns `Ok`. On Unix the signal goes to the
223224
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.
236236

237237
`metadata` on `create_pipe` is an opaque JSON object the daemon stores and
238238
returns as `pipe.metadata` without interpreting it. `set_metadata { id,
Collapse file

‎packages/process-daemon/src/daemon/windows.rs‎

Copy file name to clipboardExpand all lines: packages/process-daemon/src/daemon/windows.rs
+4-13Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use windows_sys::Win32::System::WindowsProgramming::{
3030
use super::{LOCK_FILE, REGISTRATION_FILE, Registration, registration_path, sweep};
3131
use crate::protocol::{PROTOCOL_VERSION, features};
3232
use crate::transport::Listener;
33-
use crate::transport::windows::{owned_handle, security::PrivateSecurity};
33+
use crate::transport::windows::{owned_handle, security::PrivateSecurity, wide};
3434

3535
pub(super) fn read_registration(directory: &Path) -> Result<Registration> {
3636
let security = PrivateSecurity::new()?;
@@ -74,9 +74,9 @@ impl Runtime {
7474
if let Some(parent) = directory.parent() {
7575
fs::create_dir_all(parent)?;
7676
}
77-
let wide = wide_path(directory)?;
77+
let directory_wide = wide(directory.as_os_str())?;
7878
// 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 {
8080
let error = std::io::Error::last_os_error();
8181
if error.raw_os_error() != Some(ERROR_ALREADY_EXISTS as i32) {
8282
return Err(error.into());
@@ -300,7 +300,7 @@ fn open(
300300
sharing: u32,
301301
security: &PrivateSecurity,
302302
) -> Result<File> {
303-
let path = wide_path(path)?;
303+
let path = wide(path.as_os_str())?;
304304
// SAFETY: all pointers are valid; OPEN_REPARSE_POINT lets check_kind reject
305305
// links rather than inspecting a different target after following them.
306306
let handle = unsafe {
@@ -332,15 +332,6 @@ fn check_kind(file: &File, directory: bool) -> Result<()> {
332332
Ok(())
333333
}
334334

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-
344335
#[cfg(test)]
345336
mod tests {
346337
use super::*;
Collapse file

‎packages/process-daemon/src/service/pipe.rs‎

Copy file name to clipboardExpand all lines: packages/process-daemon/src/service/pipe.rs
+24-11Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
use std::fs::File;
2222
use std::io::{self, Write};
2323
use std::sync::{Arc, Mutex, RwLock};
24-
use std::thread::JoinHandle;
24+
use std::thread::{self, JoinHandle};
2525
use std::time::Duration;
2626

2727
use anyhow::{Context, Result};
@@ -149,10 +149,11 @@ fn new_pipe_info(id: TerminalId, pid: u32, request: CreatePipe) -> ProcessInfo {
149149
}
150150
}
151151

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>,
156157
}
157158

158159
/// Registers a spawned pipe process with its actor, then runs the platform's
@@ -163,9 +164,9 @@ fn start_pipe(
163164
order: u64,
164165
request: CreatePipe,
165166
process: Arc<Process>,
166-
sink: File,
167167
cancel: Box<dyn Send>,
168-
threads: Threads,
168+
reader: impl FnOnce(Sender<ActorMessage>) + Send + 'static,
169+
waiter: impl FnOnce() -> Waiter + Send + 'static,
169170
) -> Result<TerminalHandle> {
170171
let info = Arc::new(RwLock::new(new_pipe_info(id, process.pid(), request)));
171172
// Nothing is ever written to a pipe process; a disconnected queue
@@ -196,21 +197,33 @@ fn start_pipe(
196197
thread,
197198
} = actor;
198199
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");
200205
let reader = match reader {
201206
Ok(reader) => reader,
202207
Err(error) => {
203208
stop(shutdown_tx, cancel, &process, joins);
204-
return Err(error).context("failed to spawn terminal reader");
209+
return Err(error);
205210
}
206211
};
207212
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");
209222
let waiter = match waiter {
210223
Ok(waiter) => waiter,
211224
Err(error) => {
212225
stop(shutdown_tx, cancel, &process, joins);
213-
return Err(error).context("failed to spawn terminal child waiter");
226+
return Err(error);
214227
}
215228
};
216229
joins.push(waiter);
Collapse file

‎packages/process-daemon/src/service/pipe/unix.rs‎

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 numberDiff line numberDiff line change
@@ -20,14 +20,13 @@ use std::os::unix::fs::OpenOptionsExt;
2020
use std::os::unix::process::CommandExt;
2121
use std::process::{Command, Stdio};
2222
use std::sync::{Arc, Mutex, PoisonError, RwLock};
23-
use std::thread;
2423
use std::time::Instant;
2524

2625
use anyhow::{Context, Result, bail};
2726
use nix::errno::Errno;
2827
use nix::poll::{PollFd, PollFlags, PollTimeout, poll};
2928

30-
use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, exit_message, start_pipe};
29+
use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, start_pipe};
3130
use crate::service::{CreatePipe, ProcessSignal, TerminalHandle, TerminalId};
3231

3332
/// Serializes pipe creation against `spawn`. macOS has no `pipe2`, so std
@@ -127,32 +126,18 @@ impl TerminalHandle {
127126
// Dropping `Child` neither waits nor kills; `Process` reaps it.
128127
drop(child);
129128

130-
let reader_id = id;
131-
let waiter_id = id;
129+
let pid = process.pid;
132130
start_pipe(
133131
id,
134132
order,
135133
request,
136134
Arc::clone(&process),
137-
sink,
138135
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),
156141
},
157142
)
158143
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.