devbox-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
devbox/commands.py ADDED
@@ -0,0 +1,698 @@
1
+ """Process operations inside a sandbox: run commands, reconnect to running
2
+ processes, and deliver input and signals by process ID.
3
+
4
+ Exposed as :attr:`Sandbox.commands` / :attr:`AsyncSandbox.commands`; see
5
+ :mod:`devbox.pty` for interactive terminal sessions.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import codecs
12
+ import inspect
13
+ import time
14
+ from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Iterator, Mapping
15
+ from typing import Any, Literal, overload
16
+
17
+ from ._transport import AsyncTransport, SyncTransport
18
+ from .errors import CommandExitError, ConfigurationError, ProtocolError, RequestTimeoutError
19
+ from .models import CommandResult, OutputChunk, ProcessInfo, PtySize
20
+
21
+ OutputHandler = Callable[[str], None]
22
+ AsyncOutputHandler = Callable[[str], Awaitable[None] | None]
23
+ SyncTransportProvider = Callable[[], SyncTransport]
24
+ AsyncTransportProvider = Callable[[], Awaitable[AsyncTransport]]
25
+
26
+ _PROCESS = "/process.Process"
27
+
28
+
29
+ class _MissingExitStatus(ProtocolError):
30
+ pass
31
+
32
+
33
+ class CommandHandle:
34
+ """A running process that can receive input, signals, or be reconnected."""
35
+
36
+ def __init__(
37
+ self,
38
+ pid: int,
39
+ commands: Commands,
40
+ events: Generator[Mapping[str, Any], None, None] | None = None,
41
+ *,
42
+ input_stream: str = "stdin",
43
+ reconnect_timeout: float | None = 60,
44
+ ) -> None:
45
+ self.pid = pid
46
+ self._commands = commands
47
+ self._events = events
48
+ self._input_stream = input_stream
49
+ self._reconnect_timeout = reconnect_timeout
50
+ self._result: CommandResult | None = None
51
+
52
+ def wait(
53
+ self,
54
+ *,
55
+ on_stdout: OutputHandler | None = None,
56
+ on_stderr: OutputHandler | None = None,
57
+ check: bool = True,
58
+ ) -> CommandResult:
59
+ """Wait for completion and collect the command output."""
60
+ if self._result is None:
61
+ events = self._events or self._commands._connect_events(
62
+ self.pid, self._reconnect_timeout
63
+ )
64
+ self._events = None
65
+ try:
66
+ self._result = self._commands._collect_events(
67
+ events, self.pid, on_stdout, on_stderr
68
+ )
69
+ finally:
70
+ events.close()
71
+ if check and self._result.exit_code != 0:
72
+ raise CommandExitError(self._result)
73
+ return self._result
74
+
75
+ def send_stdin(self, data: str | bytes) -> None:
76
+ """Send data to the process standard input."""
77
+ self._ensure_active()
78
+ self._commands._send_input(self.pid, data, self._input_stream)
79
+
80
+ def close_stdin(self) -> None:
81
+ """Close the process standard input stream."""
82
+ self._ensure_active()
83
+ self._commands.close_stdin(self.pid)
84
+
85
+ def send_signal(self, signal: Literal["SIGTERM", "SIGKILL"]) -> None:
86
+ """Send a POSIX signal such as ``SIGTERM`` to the process."""
87
+ self._ensure_active()
88
+ self._commands.send_signal(self.pid, signal)
89
+
90
+ def kill(self) -> None:
91
+ """Terminate the process with ``SIGKILL``."""
92
+ self.send_signal("SIGKILL")
93
+
94
+ def disconnect(self) -> None:
95
+ """Close the local stream without stopping the remote process."""
96
+ if self._events is not None:
97
+ self._events.close()
98
+ self._events = None
99
+
100
+ def _ensure_active(self) -> None:
101
+ if self._result is not None:
102
+ raise RuntimeError("process has already completed")
103
+
104
+
105
+ class Commands:
106
+ """Run and manage processes inside a sandbox."""
107
+
108
+ def __init__(self, transport: SyncTransportProvider) -> None:
109
+ self._transport = transport
110
+
111
+ @overload
112
+ def run(
113
+ self,
114
+ command: str,
115
+ *,
116
+ background: Literal[False] = False,
117
+ envs: Mapping[str, str] | None = None,
118
+ cwd: str | None = None,
119
+ user: str | None = None,
120
+ stdin: bool = False,
121
+ timeout: float | None = 60,
122
+ on_stdout: OutputHandler | None = None,
123
+ on_stderr: OutputHandler | None = None,
124
+ check: bool = True,
125
+ ) -> CommandResult: ...
126
+
127
+ @overload
128
+ def run(
129
+ self,
130
+ command: str,
131
+ *,
132
+ background: Literal[True],
133
+ envs: Mapping[str, str] | None = None,
134
+ cwd: str | None = None,
135
+ user: str | None = None,
136
+ stdin: bool = False,
137
+ timeout: float | None = 60,
138
+ on_stdout: None = None,
139
+ on_stderr: None = None,
140
+ check: bool = True,
141
+ ) -> CommandHandle: ...
142
+
143
+ def run(
144
+ self,
145
+ command: str,
146
+ *,
147
+ background: bool = False,
148
+ envs: Mapping[str, str] | None = None,
149
+ cwd: str | None = None,
150
+ user: str | None = None,
151
+ stdin: bool = False,
152
+ timeout: float | None = 60,
153
+ on_stdout: OutputHandler | None = None,
154
+ on_stderr: OutputHandler | None = None,
155
+ check: bool = True,
156
+ ) -> CommandResult | CommandHandle:
157
+ """Run a shell command or return a handle for a background command.
158
+
159
+ Foreground runs collect stdout/stderr and raise
160
+ :class:`CommandExitError` on a nonzero exit when ``check`` is true;
161
+ ``background=True`` returns a :class:`CommandHandle` immediately.
162
+ """
163
+ if background and (on_stdout is not None or on_stderr is not None):
164
+ raise ValueError("background output callbacks belong on handle.wait()")
165
+ started = time.monotonic()
166
+ handle = self._start(_command_body(command, envs, cwd, stdin), timeout=timeout, user=user)
167
+ if background:
168
+ return handle
169
+ try:
170
+ return handle.wait(on_stdout=on_stdout, on_stderr=on_stderr, check=check)
171
+ except _MissingExitStatus as error:
172
+ if timeout and time.monotonic() - started >= timeout:
173
+ raise RequestTimeoutError("command timed out") from error
174
+ raise
175
+
176
+ def connect(self, pid: int, *, timeout: float | None = 60) -> CommandHandle:
177
+ """Reconnect to a running process by process ID."""
178
+ _validate_pid(pid)
179
+ return CommandHandle(
180
+ pid,
181
+ self,
182
+ self._connect_events(pid, timeout),
183
+ reconnect_timeout=timeout,
184
+ )
185
+
186
+ def list(self) -> tuple[ProcessInfo, ...]:
187
+ """List processes managed by EnvD in this sandbox."""
188
+ payload = self._transport().connect_unary(f"{_PROCESS}/List", {})
189
+ return tuple(ProcessInfo.from_wire(item) for item in _items(payload, "processes"))
190
+
191
+ def send_stdin(self, pid: int, data: str | bytes) -> None:
192
+ """Send standard input to a process by process ID."""
193
+ self._send_input(pid, data, "stdin")
194
+
195
+ def close_stdin(self, pid: int) -> None:
196
+ """Close standard input for a process by process ID."""
197
+ _validate_pid(pid)
198
+ self._transport().connect_unary(f"{_PROCESS}/CloseStdin", {"process": {"pid": pid}})
199
+
200
+ def send_signal(self, pid: int, signal: Literal["SIGTERM", "SIGKILL"]) -> None:
201
+ """Send a POSIX signal to a process by process ID."""
202
+ _validate_pid(pid)
203
+ self._transport().connect_unary(
204
+ f"{_PROCESS}/SendSignal",
205
+ {"process": {"pid": pid}, "signal": _signal(signal)},
206
+ )
207
+
208
+ def _start(
209
+ self,
210
+ body: Mapping[str, object],
211
+ *,
212
+ timeout: float | None,
213
+ user: str | None = None,
214
+ pty: PtySize | None = None,
215
+ input_stream: str = "stdin",
216
+ ) -> CommandHandle:
217
+ headers = _process_headers(user)
218
+ request = dict(body)
219
+ if pty:
220
+ request["pty"] = {"size": {"rows": pty.rows, "cols": pty.cols}}
221
+ transport = self._transport()
222
+ events = transport.connect_stream(
223
+ f"{_PROCESS}/Start",
224
+ request,
225
+ timeout=timeout,
226
+ headers=headers,
227
+ )
228
+ try:
229
+ pid = _first_pid(events, "start process")
230
+ except BaseException:
231
+ events.close()
232
+ raise
233
+ return CommandHandle(
234
+ pid,
235
+ self,
236
+ events,
237
+ input_stream=input_stream,
238
+ reconnect_timeout=timeout,
239
+ )
240
+
241
+ def _connect_events(
242
+ self, pid: int, timeout: float | None
243
+ ) -> Generator[Mapping[str, Any], None, None]:
244
+ events = self._transport().connect_stream(
245
+ f"{_PROCESS}/Connect",
246
+ {"process": {"pid": pid}},
247
+ timeout=timeout,
248
+ headers={"Keepalive-Ping-Interval": "50"},
249
+ )
250
+ try:
251
+ connected_pid = _first_pid(events, "connect to process")
252
+ if connected_pid != pid:
253
+ raise ProtocolError("EnvD connected to an unexpected process")
254
+ except BaseException:
255
+ events.close()
256
+ raise
257
+ return events
258
+
259
+ def _send_input(self, pid: int, data: str | bytes, stream: str) -> None:
260
+ _validate_pid(pid)
261
+ self._transport().connect_unary(
262
+ f"{_PROCESS}/SendInput",
263
+ {
264
+ "process": {"pid": pid},
265
+ "input": {stream: base64.b64encode(_bytes(data)).decode("ascii")},
266
+ },
267
+ )
268
+
269
+ @staticmethod
270
+ def _collect_events(
271
+ events: Iterator[Mapping[str, Any]],
272
+ pid: int,
273
+ on_stdout: OutputHandler | None,
274
+ on_stderr: OutputHandler | None,
275
+ ) -> CommandResult:
276
+ collector = _OutputCollector(pid, on_stdout, on_stderr)
277
+ for event in events:
278
+ collector.add(event)
279
+ return collector.result()
280
+
281
+
282
+ class AsyncCommandHandle:
283
+ """Asynchronous counterpart of :class:`CommandHandle`.
284
+
285
+ Consumes the process event stream until exit; ``wait`` collects the
286
+ output and returns the final :class:`CommandResult`.
287
+ """
288
+
289
+ def __init__(
290
+ self,
291
+ pid: int,
292
+ commands: AsyncCommands,
293
+ events: AsyncGenerator[Mapping[str, Any], None] | None = None,
294
+ *,
295
+ input_stream: str = "stdin",
296
+ reconnect_timeout: float | None = 60,
297
+ ) -> None:
298
+ self.pid = pid
299
+ self._commands = commands
300
+ self._events = events
301
+ self._input_stream = input_stream
302
+ self._reconnect_timeout = reconnect_timeout
303
+ self._result: CommandResult | None = None
304
+
305
+ async def wait(
306
+ self,
307
+ *,
308
+ on_stdout: AsyncOutputHandler | None = None,
309
+ on_stderr: AsyncOutputHandler | None = None,
310
+ check: bool = True,
311
+ ) -> CommandResult:
312
+ """Wait for exit and collect output; raises on nonzero exit when ``check`` is true."""
313
+ if self._result is None:
314
+ events = self._events or await self._commands._connect_events(
315
+ self.pid, self._reconnect_timeout
316
+ )
317
+ self._events = None
318
+ try:
319
+ self._result = await self._commands._collect_events(
320
+ events, self.pid, on_stdout, on_stderr
321
+ )
322
+ finally:
323
+ await events.aclose()
324
+ if check and self._result.exit_code != 0:
325
+ raise CommandExitError(self._result)
326
+ return self._result
327
+
328
+ async def send_stdin(self, data: str | bytes) -> None:
329
+ """Write data to this process's stdin or terminal."""
330
+ self._ensure_active()
331
+ await self._commands._send_input(self.pid, data, self._input_stream)
332
+
333
+ async def close_stdin(self) -> None:
334
+ """Send EOF to this (non-PTY) process so it can finish consuming input."""
335
+ self._ensure_active()
336
+ await self._commands.close_stdin(self.pid)
337
+
338
+ async def send_signal(self, signal: Literal["SIGTERM", "SIGKILL"]) -> None:
339
+ """Deliver a signal to this process; only SIGTERM and SIGKILL are supported."""
340
+ self._ensure_active()
341
+ await self._commands.send_signal(self.pid, signal)
342
+
343
+ async def kill(self) -> None:
344
+ """Force-kill this process (SIGKILL)."""
345
+ await self.send_signal("SIGKILL")
346
+
347
+ async def disconnect(self) -> None:
348
+ """Close the local output stream without stopping the remote process."""
349
+ if self._events is not None:
350
+ await self._events.aclose()
351
+ self._events = None
352
+
353
+ def _ensure_active(self) -> None:
354
+ if self._result is not None:
355
+ raise RuntimeError("process has already completed")
356
+
357
+
358
+ class AsyncCommands:
359
+ """Run and manage processes through the asynchronous API."""
360
+
361
+ def __init__(self, transport: AsyncTransportProvider) -> None:
362
+ self._transport = transport
363
+
364
+ @overload
365
+ async def run(
366
+ self,
367
+ command: str,
368
+ *,
369
+ background: Literal[False] = False,
370
+ envs: Mapping[str, str] | None = None,
371
+ cwd: str | None = None,
372
+ user: str | None = None,
373
+ stdin: bool = False,
374
+ timeout: float | None = 60,
375
+ on_stdout: AsyncOutputHandler | None = None,
376
+ on_stderr: AsyncOutputHandler | None = None,
377
+ check: bool = True,
378
+ ) -> CommandResult: ...
379
+
380
+ @overload
381
+ async def run(
382
+ self,
383
+ command: str,
384
+ *,
385
+ background: Literal[True],
386
+ envs: Mapping[str, str] | None = None,
387
+ cwd: str | None = None,
388
+ user: str | None = None,
389
+ stdin: bool = False,
390
+ timeout: float | None = 60,
391
+ on_stdout: None = None,
392
+ on_stderr: None = None,
393
+ check: bool = True,
394
+ ) -> AsyncCommandHandle: ...
395
+
396
+ async def run(
397
+ self,
398
+ command: str,
399
+ *,
400
+ background: bool = False,
401
+ envs: Mapping[str, str] | None = None,
402
+ cwd: str | None = None,
403
+ user: str | None = None,
404
+ stdin: bool = False,
405
+ timeout: float | None = 60,
406
+ on_stdout: AsyncOutputHandler | None = None,
407
+ on_stderr: AsyncOutputHandler | None = None,
408
+ check: bool = True,
409
+ ) -> CommandResult | AsyncCommandHandle:
410
+ """Run a shell command or return a handle for a background command.
411
+
412
+ Foreground runs collect stdout/stderr and raise
413
+ :class:`CommandExitError` on a nonzero exit when ``check`` is true;
414
+ ``background=True`` returns an :class:`AsyncCommandHandle` immediately.
415
+ """
416
+ if background and (on_stdout is not None or on_stderr is not None):
417
+ raise ValueError("background output callbacks belong on handle.wait()")
418
+ started = time.monotonic()
419
+ handle = await self._start(
420
+ _command_body(command, envs, cwd, stdin), timeout=timeout, user=user
421
+ )
422
+ if background:
423
+ return handle
424
+ try:
425
+ return await handle.wait(on_stdout=on_stdout, on_stderr=on_stderr, check=check)
426
+ except _MissingExitStatus as error:
427
+ if timeout and time.monotonic() - started >= timeout:
428
+ raise RequestTimeoutError("command timed out") from error
429
+ raise
430
+
431
+ async def connect(self, pid: int, *, timeout: float | None = 60) -> AsyncCommandHandle:
432
+ """Reconnect to a running process by process ID."""
433
+ _validate_pid(pid)
434
+ return AsyncCommandHandle(
435
+ pid,
436
+ self,
437
+ await self._connect_events(pid, timeout),
438
+ reconnect_timeout=timeout,
439
+ )
440
+
441
+ async def list(self) -> tuple[ProcessInfo, ...]:
442
+ """List processes managed by EnvD in this sandbox."""
443
+ transport = await self._transport()
444
+ payload = await transport.connect_unary(f"{_PROCESS}/List", {})
445
+ return tuple(ProcessInfo.from_wire(item) for item in _items(payload, "processes"))
446
+
447
+ async def send_stdin(self, pid: int, data: str | bytes) -> None:
448
+ """Send standard input to a process by process ID."""
449
+ await self._send_input(pid, data, "stdin")
450
+
451
+ async def close_stdin(self, pid: int) -> None:
452
+ """Close standard input for a process by process ID."""
453
+ _validate_pid(pid)
454
+ transport = await self._transport()
455
+ await transport.connect_unary(f"{_PROCESS}/CloseStdin", {"process": {"pid": pid}})
456
+
457
+ async def send_signal(self, pid: int, signal: Literal["SIGTERM", "SIGKILL"]) -> None:
458
+ """Send a POSIX signal to a process by process ID."""
459
+ _validate_pid(pid)
460
+ transport = await self._transport()
461
+ await transport.connect_unary(
462
+ f"{_PROCESS}/SendSignal",
463
+ {"process": {"pid": pid}, "signal": _signal(signal)},
464
+ )
465
+
466
+ async def _start(
467
+ self,
468
+ body: Mapping[str, object],
469
+ *,
470
+ timeout: float | None,
471
+ user: str | None = None,
472
+ pty: PtySize | None = None,
473
+ input_stream: str = "stdin",
474
+ ) -> AsyncCommandHandle:
475
+ headers = _process_headers(user)
476
+ request = dict(body)
477
+ if pty:
478
+ request["pty"] = {"size": {"rows": pty.rows, "cols": pty.cols}}
479
+ transport = await self._transport()
480
+ events = transport.connect_stream(
481
+ f"{_PROCESS}/Start",
482
+ request,
483
+ timeout=timeout,
484
+ headers=headers,
485
+ )
486
+ try:
487
+ pid = await _first_pid_async(events, "start process")
488
+ except BaseException:
489
+ await events.aclose()
490
+ raise
491
+ return AsyncCommandHandle(
492
+ pid,
493
+ self,
494
+ events,
495
+ input_stream=input_stream,
496
+ reconnect_timeout=timeout,
497
+ )
498
+
499
+ async def _connect_events(
500
+ self, pid: int, timeout: float | None
501
+ ) -> AsyncGenerator[Mapping[str, Any], None]:
502
+ transport = await self._transport()
503
+ events = transport.connect_stream(
504
+ f"{_PROCESS}/Connect",
505
+ {"process": {"pid": pid}},
506
+ timeout=timeout,
507
+ headers={"Keepalive-Ping-Interval": "50"},
508
+ )
509
+ try:
510
+ connected_pid = await _first_pid_async(events, "connect to process")
511
+ if connected_pid != pid:
512
+ raise ProtocolError("EnvD connected to an unexpected process")
513
+ except BaseException:
514
+ await events.aclose()
515
+ raise
516
+ return events
517
+
518
+ async def _send_input(self, pid: int, data: str | bytes, stream: str) -> None:
519
+ _validate_pid(pid)
520
+ transport = await self._transport()
521
+ await transport.connect_unary(
522
+ f"{_PROCESS}/SendInput",
523
+ {
524
+ "process": {"pid": pid},
525
+ "input": {stream: base64.b64encode(_bytes(data)).decode("ascii")},
526
+ },
527
+ )
528
+
529
+ @staticmethod
530
+ async def _collect_events(
531
+ events: AsyncGenerator[Mapping[str, Any], None],
532
+ pid: int,
533
+ on_stdout: AsyncOutputHandler | None,
534
+ on_stderr: AsyncOutputHandler | None,
535
+ ) -> CommandResult:
536
+ collector = _OutputCollector(pid)
537
+ async for event in events:
538
+ for chunk in collector.add(event):
539
+ if chunk.stream == "stdout" and on_stdout:
540
+ await _invoke(on_stdout, chunk.data)
541
+ if chunk.stream == "stderr" and on_stderr:
542
+ await _invoke(on_stderr, chunk.data)
543
+ return collector.result()
544
+
545
+
546
+ class _OutputCollector:
547
+ def __init__(
548
+ self,
549
+ pid: int,
550
+ on_stdout: OutputHandler | None = None,
551
+ on_stderr: OutputHandler | None = None,
552
+ ) -> None:
553
+ self._pid = pid
554
+ self._stdout: list[str] = []
555
+ self._stderr: list[str] = []
556
+ self._exit_code: int | None = None
557
+ self._stdout_decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
558
+ self._stderr_decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
559
+ self._on_stdout = on_stdout
560
+ self._on_stderr = on_stderr
561
+
562
+ def add(self, response: Mapping[str, Any]) -> tuple[OutputChunk, ...]:
563
+ event = response.get("event")
564
+ if not isinstance(event, Mapping):
565
+ return ()
566
+ chunks: list[OutputChunk] = []
567
+ data = event.get("data")
568
+ if isinstance(data, Mapping):
569
+ for stream in ("stdout", "stderr", "pty"):
570
+ if stream in data:
571
+ target = "stdout" if stream == "pty" else stream
572
+ value = self._decode(target, data[stream])
573
+ if value:
574
+ self._append(target, value)
575
+ chunks.append(OutputChunk(stream=target, data=value))
576
+ end = event.get("end")
577
+ if isinstance(end, Mapping):
578
+ self._exit_code = int(end.get("exitCode", end.get("exit_code", 0)))
579
+ return tuple(chunks)
580
+
581
+ def result(self) -> CommandResult:
582
+ self._flush()
583
+ if self._exit_code is None:
584
+ raise _MissingExitStatus("command stream ended without an exit status")
585
+ return CommandResult(
586
+ exit_code=self._exit_code,
587
+ stdout="".join(self._stdout),
588
+ stderr="".join(self._stderr),
589
+ pid=self._pid,
590
+ )
591
+
592
+ def _decode(self, stream: str, value: object) -> str:
593
+ try:
594
+ data = base64.b64decode(str(value), validate=True)
595
+ except ValueError as error:
596
+ raise ProtocolError("EnvD returned invalid process output") from error
597
+ decoder = self._stdout_decoder if stream == "stdout" else self._stderr_decoder
598
+ return decoder.decode(data)
599
+
600
+ def _flush(self) -> None:
601
+ stdout = self._stdout_decoder.decode(b"", final=True)
602
+ stderr = self._stderr_decoder.decode(b"", final=True)
603
+ if stdout:
604
+ self._append("stdout", stdout)
605
+ if stderr:
606
+ self._append("stderr", stderr)
607
+
608
+ def _append(self, stream: str, data: str) -> None:
609
+ if stream == "stdout":
610
+ self._stdout.append(data)
611
+ if self._on_stdout:
612
+ self._on_stdout(data)
613
+ else:
614
+ self._stderr.append(data)
615
+ if self._on_stderr:
616
+ self._on_stderr(data)
617
+
618
+
619
+ def _command_body(
620
+ command: str,
621
+ envs: Mapping[str, str] | None,
622
+ cwd: str | None,
623
+ stdin: bool,
624
+ ) -> dict[str, object]:
625
+ if not command.strip():
626
+ raise ValueError("command must not be blank")
627
+ process: dict[str, object] = {
628
+ "cmd": "/bin/bash",
629
+ "args": ["-l", "-c", command],
630
+ "envs": dict(envs or {}),
631
+ }
632
+ if cwd:
633
+ process["cwd"] = cwd
634
+ return {"process": process, "stdin": stdin}
635
+
636
+
637
+ def _process_headers(user: str | None) -> dict[str, str]:
638
+ headers = {"Keepalive-Ping-Interval": "50"}
639
+ if user is not None:
640
+ if not user or user != user.strip() or ":" in user or "\x00" in user:
641
+ raise ConfigurationError("user must be a non-empty sandbox username")
642
+ encoded = base64.b64encode(f"{user}:".encode()).decode("ascii")
643
+ headers["Authorization"] = f"Basic {encoded}"
644
+ return headers
645
+
646
+
647
+ def _first_pid(events: Iterator[Mapping[str, Any]], action: str) -> int:
648
+ try:
649
+ response = next(events)
650
+ except StopIteration as error:
651
+ raise ProtocolError(f"EnvD did not {action}") from error
652
+ return _start_pid(response, action)
653
+
654
+
655
+ async def _first_pid_async(events: AsyncGenerator[Mapping[str, Any], None], action: str) -> int:
656
+ try:
657
+ response = await anext(events)
658
+ except StopAsyncIteration as error:
659
+ raise ProtocolError(f"EnvD did not {action}") from error
660
+ return _start_pid(response, action)
661
+
662
+
663
+ def _start_pid(response: Mapping[str, Any], action: str) -> int:
664
+ event = response.get("event")
665
+ start = event.get("start") if isinstance(event, Mapping) else None
666
+ if not isinstance(start, Mapping) or "pid" not in start:
667
+ raise ProtocolError(f"EnvD did not {action}")
668
+ pid = int(start["pid"])
669
+ _validate_pid(pid)
670
+ return pid
671
+
672
+
673
+ def _items(payload: object, key: str) -> tuple[Mapping[str, Any], ...]:
674
+ source = payload.get(key, []) if isinstance(payload, Mapping) else []
675
+ if not isinstance(source, list):
676
+ raise ProtocolError("process response is invalid")
677
+ return tuple(item for item in source if isinstance(item, Mapping))
678
+
679
+
680
+ def _signal(value: str) -> str:
681
+ if value not in {"SIGTERM", "SIGKILL"}:
682
+ raise ValueError("signal must be SIGTERM or SIGKILL")
683
+ return f"SIGNAL_{value}"
684
+
685
+
686
+ def _bytes(value: str | bytes) -> bytes:
687
+ return value.encode() if isinstance(value, str) else value
688
+
689
+
690
+ def _validate_pid(pid: int) -> None:
691
+ if pid < 1:
692
+ raise ValueError("pid must be positive")
693
+
694
+
695
+ async def _invoke(handler: AsyncOutputHandler, value: str) -> None:
696
+ result = handler(value)
697
+ if inspect.isawaitable(result):
698
+ await result