robotcode-repl 2.9.0.dev197__py3-none-any.whl → 2.9.0.dev214__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.
@@ -11,8 +11,7 @@ processes is part of the answers, and none of it is written to a file.
11
11
 
12
12
  Each open session has a file in a folder of the user, by which the `robotcode session`
13
13
  commands find it. A session stays open after its REPL or run has ended, until it is
14
- stopped or has been idle too long. A restart starts a new process, which takes over the
15
- ID, the file and the pipe of the session.
14
+ stopped or has been idle too long.
16
15
  """
17
16
 
18
17
  import codecs
@@ -47,13 +46,16 @@ from robotcode.core.utils.dataclasses import from_json
47
46
  from robotcode.plugin import Application
48
47
  from robotcode.robot.config.utils import get_config_files
49
48
 
50
- from ._debug import BreakpointState, DebugController
51
49
  from .console_interpreter import ConsoleInterpreter
52
50
 
53
51
  if sys.platform == "win32":
54
52
  import _winapi
55
53
  import msvcrt
56
54
 
55
+ from . import _windows_job
56
+ else:
57
+ import fcntl
58
+
57
59
  # Without `$XDG_RUNTIME_DIR`, as in a container, platformdirs falls back to another folder, which works for the sessions
58
60
  # too, and warns about it at every call. Older versions of platformdirs don't warn.
59
61
  if hasattr(platformdirs, "RuntimeDirWarning"):
@@ -107,7 +109,6 @@ class Request(_Value):
107
109
  # Whether the session runs, waits or its REPL or run has ended; takes none of the output.
108
110
  STATE = "state"
109
111
  RESULT = "result"
110
- RESTART = "restart"
111
112
 
112
113
 
113
114
  @unique
@@ -164,21 +165,6 @@ class StoppedAnswer:
164
165
  output: str
165
166
 
166
167
 
167
- @dataclass
168
- class RestartedAnswer:
169
- """The answer to `restart` once the new process has taken over, with the output since the last answer."""
170
-
171
- output: str
172
-
173
-
174
- @dataclass
175
- class RestartFailedAnswer:
176
- """The answer to `restart` when the new process didn't get ready, so that the session stays as it is."""
177
-
178
- output: str
179
- reason: str
180
-
181
-
182
168
  @dataclass
183
169
  class RefusedAnswer:
184
170
  """The session doesn't take the request, for the reason in the message."""
@@ -186,17 +172,10 @@ class RefusedAnswer:
186
172
  message: str
187
173
 
188
174
 
189
- @dataclass
190
- class MovedAnswer:
191
- """The new process of a restart has taken over the session, so that the command has to ask that process."""
192
-
193
-
194
175
  # What a session answers to the requests it takes.
195
- SessionAnswer = Union[
196
- OutputAnswer, StateAnswer, ResultAnswer, InterruptedAnswer, StoppedAnswer, RestartedAnswer, RestartFailedAnswer
197
- ]
198
- # What a channel answers, also when its session doesn't take a request or has moved to another process.
199
- ChannelAnswer = Union[SessionAnswer, RefusedAnswer, MovedAnswer]
176
+ SessionAnswer = Union[OutputAnswer, StateAnswer, ResultAnswer, InterruptedAnswer, StoppedAnswer]
177
+ # What a channel answers, also when its session doesn't take a request.
178
+ ChannelAnswer = Union[SessionAnswer, RefusedAnswer]
200
179
 
201
180
 
202
181
  _ID_PATTERN = re.compile(rf"(?:{'|'.join(kind.value for kind in SessionKind)})-[0-9a-f]{{8}}")
@@ -246,19 +225,16 @@ def _entry_path(session_id: str) -> Path:
246
225
  return sessions_dir() / f"{session_id}.json"
247
226
 
248
227
 
249
- def _address(session_id: str, generation: int = 0) -> str:
250
- """The address of the channel of a session process. After a restart, each new process has a `generation` of its
251
- own, and with it an address of its own."""
252
- name = f"{session_id}-{generation}" if generation else session_id
228
+ def _address(session_id: str) -> str:
229
+ """The address of the channel of a session."""
253
230
  if sys.platform == "win32":
254
- return rf"\\.\pipe\robotcode-{name}"
255
- return str(sessions_dir() / f"{name}.sock")
231
+ return rf"\\.\pipe\robotcode-{session_id}"
232
+ return str(sessions_dir() / f"{session_id}.sock")
256
233
 
257
234
 
258
- def _restart_path(session_id: str) -> Path:
259
- """The file in which a session process hands its breakpoints, its start time and the next generation to the new
260
- process of a restart."""
261
- return sessions_dir() / f"{session_id}.restart"
235
+ def _pipe_path(session_id: str) -> Path:
236
+ """The pipe of the output of a session on Linux and macOS, a FIFO, which the session process opens by its path."""
237
+ return sessions_dir() / f"{session_id}.pipe"
262
238
 
263
239
 
264
240
  def new_session_id(kind: SessionKind) -> str:
@@ -297,14 +273,24 @@ class SessionEntry:
297
273
 
298
274
 
299
275
  @dataclass
300
- class _Handover:
301
- """The file in which a session process hands on to the new process of a restart."""
276
+ class PipeHolder:
277
+ """The process that holds the read end of the pipe of a session on Windows, from which the session process takes
278
+ it; on its command line as `PID:HANDLE`."""
302
279
 
303
- # The number of the new process, by which it gets a channel of its own.
304
- generation: int
305
- # When the session started.
306
- started: float
307
- breakpoints: Optional[BreakpointState] = None
280
+ pid: int
281
+ handle: int
282
+
283
+ def __str__(self) -> str:
284
+ return f"{self.pid}:{self.handle}"
285
+
286
+ @classmethod
287
+ def parse(cls, text: str) -> "PipeHolder":
288
+ """The holder that `str` has written as `text`; `SessionError` when `text` isn't one."""
289
+ try:
290
+ pid, handle = text.split(":")
291
+ return cls(int(pid), int(handle))
292
+ except ValueError as e:
293
+ raise SessionError(f"'{text}' names no process that holds the output of the session.") from e
308
294
 
309
295
 
310
296
  def _retried(action: Callable[[], _T]) -> _T:
@@ -325,27 +311,21 @@ def _temp_path(path: Path) -> Path:
325
311
  return path.with_name(f"{path.name}.tmp")
326
312
 
327
313
 
328
- def _write_json(path: Path, data: Union[SessionEntry, _Handover]) -> None:
329
- """Write `data` to `path` as a whole, readable only by the user."""
314
+ def _write_entry(entry: SessionEntry) -> None:
315
+ """Write the file of the session `entry` as a whole, readable only by the user."""
316
+ path = _entry_path(entry.id)
330
317
  temp = _temp_path(path)
331
318
  fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
332
319
  with os.fdopen(fd, "w", encoding="utf-8") as f:
333
- json.dump(dataclasses.asdict(data), f)
320
+ json.dump(dataclasses.asdict(entry), f)
334
321
  _retried(lambda: os.replace(temp, path))
335
322
 
336
323
 
337
- def _write_entry(entry: SessionEntry) -> None:
338
- _write_json(_entry_path(entry.id), entry)
339
-
340
-
341
324
  def remove_session_files(session_id: str) -> None:
342
325
  """Remove the files of the session `session_id`: its file, the one a session leaves when it ends while it writes
343
- its file, the file of a restart, and the sockets of all its processes."""
344
- folder = sessions_dir()
326
+ its file, the pipe and the socket."""
345
327
  entry = _entry_path(session_id)
346
- restart = _restart_path(session_id)
347
- sockets = [folder / f"{session_id}.sock", *folder.glob(f"{session_id}-*.sock")]
348
- for path in (entry, _temp_path(entry), restart, _temp_path(restart), *sockets):
328
+ for path in (entry, _temp_path(entry), _pipe_path(session_id), sessions_dir() / f"{session_id}.sock"):
349
329
  with contextlib.suppress(OSError):
350
330
  path.unlink()
351
331
 
@@ -386,13 +366,9 @@ def read_entry(session_id: str) -> Optional[SessionEntry]:
386
366
  if not _ID_PATTERN.fullmatch(session_id):
387
367
  return None
388
368
  entry = _load_entry(session_id)
389
- while entry is not None and _channel_gone(entry.address):
390
- # At a restart, the new process names its channel in the file before the old process closes its own.
391
- again = _load_entry(session_id)
392
- if again is None or again.address == entry.address:
393
- remove_session_files(session_id)
394
- return None
395
- entry = again
369
+ if entry is not None and _channel_gone(entry.address):
370
+ remove_session_files(session_id)
371
+ return None
396
372
  return entry
397
373
 
398
374
 
@@ -407,93 +383,177 @@ def connect(entry: SessionEntry) -> Connection:
407
383
  return Client(entry.address, family=_FAMILY, authkey=bytes.fromhex(entry.key))
408
384
 
409
385
 
410
- # By default a pipe on Windows holds only a few kilobytes; this holds what a session writes before it starts reading the
411
- # pipe.
386
+ # By default a pipe holds only a few kilobytes on Windows and 64 KiB on Linux; this holds what the session and its
387
+ # `wrapper` write before the session starts reading the pipe. As much as a user may set on Linux by default.
412
388
  _PIPE_SIZE = 1 << 20
413
389
 
414
390
 
415
- def create_output_pipe() -> Tuple[int, int]:
416
- """The read end and the write end of a new pipe for the output of a session."""
391
+ def create_output_pipe(session_id: str) -> Tuple[int, int]:
392
+ """The read end and the write end of a new pipe for the output of the session `session_id`: on Linux and macOS
393
+ the FIFO of the session, which the session process opens by its path."""
417
394
  if sys.platform == "win32":
418
395
  read_handle, write_handle = _winapi.CreatePipe(None, _PIPE_SIZE)
419
396
  return msvcrt.open_osfhandle(read_handle, 0), msvcrt.open_osfhandle(write_handle, 0)
420
- return os.pipe()
397
+ path = _pipe_path(session_id)
398
+ os.mkfifo(path, 0o600)
399
+ # Without blocking, as nothing writes to the FIFO yet.
400
+ read_end = os.open(path, os.O_RDONLY | os.O_NONBLOCK)
401
+ write_end = os.open(path, os.O_WRONLY)
402
+ if sys.platform == "linux":
403
+ # Elsewhere the size of a FIFO can't be set. Without it, the FIFO keeps its default size.
404
+ with contextlib.suppress(OSError):
405
+ fcntl.fcntl(write_end, fcntl.F_SETPIPE_SZ, _PIPE_SIZE)
406
+ return read_end, write_end
421
407
 
422
408
 
423
- def read_to_end(fd: int) -> str:
424
- """What the pipe `fd` holds up to its end, once nothing writes to it any more."""
409
+ def output_holder(read_end: int) -> Optional[PipeHolder]:
410
+ """This process as the holder of the read end `read_end` on Windows, from which the session process takes it;
411
+ None elsewhere, where it opens the FIFO by its path."""
412
+ if sys.platform == "win32":
413
+ return PipeHolder(os.getpid(), msvcrt.get_osfhandle(read_end))
414
+ return None
415
+
416
+
417
+ def read_available(fd: int) -> str:
418
+ """What the pipe `fd` holds now, without waiting for a process that may still write to it, such as one that a
419
+ `wrapper` has started outside the process group or the job of the session."""
425
420
  chunks = []
426
- while data := os.read(fd, 65536):
427
- chunks.append(data)
421
+ if sys.platform == "win32":
422
+ handle = msvcrt.get_osfhandle(fd)
423
+ while True:
424
+ try:
425
+ available = _winapi.PeekNamedPipe(handle)[0]
426
+ except OSError:
427
+ # Empty, and nothing writes to it any more.
428
+ break
429
+ if not available:
430
+ break
431
+ chunks.append(os.read(fd, available))
432
+ else:
433
+ os.set_blocking(fd, False)
434
+ with contextlib.suppress(BlockingIOError):
435
+ while data := os.read(fd, 65536):
436
+ chunks.append(data)
428
437
  return b"".join(chunks).decode("utf-8", errors="replace").replace("\r\n", "\n")
429
438
 
430
439
 
431
- def start_session_process(
432
- command: List[str], output: int, stdout: int, env: Dict[str, str], cwd: Optional[str] = None
433
- ) -> "subprocess.Popen[bytes]":
440
+ @dataclass
441
+ class SessionProcess:
442
+ """A session process that this process has started, together with the processes it starts, such as those of a
443
+ `wrapper`: on Linux and macOS its process group, on Windows a job."""
444
+
445
+ popen: "subprocess.Popen[bytes]"
446
+ # Only on Windows; None when Windows didn't put the process into a job, or once it is released.
447
+ job: Optional[int] = None
448
+ ended: bool = False
449
+
450
+ def end(self) -> None:
451
+ """End the process and the processes it has started, unless they have left its process group or job, and wait
452
+ for the process."""
453
+ if self.ended:
454
+ # Once its process group is gone, its ID may belong to another one.
455
+ return
456
+ self.ended = True
457
+ if sys.platform == "win32":
458
+ if self.job is not None:
459
+ with contextlib.suppress(OSError):
460
+ _windows_job.terminate(self.job)
461
+ _winapi.CloseHandle(self.job)
462
+ self.job = None
463
+ # Also when the job couldn't end it.
464
+ self.popen.kill()
465
+ else:
466
+ with contextlib.suppress(ProcessLookupError):
467
+ os.killpg(self.popen.pid, signal.SIGKILL)
468
+ self.popen.wait()
469
+
470
+ def release(self) -> None:
471
+ """Let the session run on when this process ends, now that it is ready. Until then, Windows ends it and the
472
+ processes it has started together with this process (`_windows_job.job_with`)."""
473
+ if sys.platform == "win32" and self.job is not None:
474
+ try:
475
+ _windows_job.release(self.job)
476
+ finally:
477
+ _winapi.CloseHandle(self.job)
478
+ self.job = None
479
+
480
+
481
+ def start_session_process(command: List[str], stdout: int, env: Dict[str, str]) -> SessionProcess:
434
482
  """Start a session process, detached from this one. The process writes its standard output and standard error to
435
- `stdout` and reads them back from `output`, the read end of the same pipe, which it inherits: a handle on
436
- Windows, and there the only one it inherits beside its standard handles.
483
+ `stdout`, the write end of its pipe, and takes the read end itself (`_take_pipe`). It inherits only its standard
484
+ handles, so that it gets its output also under a `wrapper` that passes on no other ones.
437
485
 
438
486
  The process keeps running after the command that started it has returned: in a new process session on Linux and
439
487
  macOS, on Windows in a new process group, which a Ctrl-C at the console of the command doesn't reach, and with a
440
488
  console without a window. Console programs that the session starts use that console instead of opening windows of
441
- their own."""
489
+ their own. On Windows it starts suspended and runs once it is in its job, so that no process it starts is outside
490
+ of it."""
442
491
  if sys.platform == "win32":
443
- os.set_handle_inheritable(output, True)
492
+ popen = subprocess.Popen(
493
+ command,
494
+ stdin=subprocess.PIPE,
495
+ stdout=stdout,
496
+ stderr=subprocess.STDOUT,
497
+ env=env,
498
+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP
499
+ | subprocess.CREATE_NO_WINDOW
500
+ | _windows_job.CREATE_SUSPENDED,
501
+ )
502
+ job: Optional[int]
444
503
  try:
445
- process = subprocess.Popen(
504
+ job = _windows_job.job_with(popen.pid)
505
+ except OSError:
506
+ # Then ending the session ends only this process.
507
+ job = None
508
+ process = SessionProcess(popen, job)
509
+ try:
510
+ _windows_job.resume(popen.pid)
511
+ except BaseException:
512
+ process.end()
513
+ raise
514
+ else:
515
+ process = SessionProcess(
516
+ subprocess.Popen(
446
517
  command,
447
518
  stdin=subprocess.PIPE,
448
519
  stdout=stdout,
449
520
  stderr=subprocess.STDOUT,
450
521
  env=env,
451
- cwd=cwd,
452
- creationflags=subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW,
453
- startupinfo=subprocess.STARTUPINFO(lpAttributeList={"handle_list": [output]}),
522
+ start_new_session=True,
454
523
  )
455
- finally:
456
- os.set_handle_inheritable(output, False)
457
- else:
458
- process = subprocess.Popen(
459
- command,
460
- stdin=subprocess.PIPE,
461
- stdout=stdout,
462
- stderr=subprocess.STDOUT,
463
- env=env,
464
- cwd=cwd,
465
- start_new_session=True,
466
- pass_fds=(output,),
467
524
  )
468
525
  # The session reads its inputs from its channel. A closed pipe as standard input makes it a session without a
469
526
  # terminal on every platform, unlike the null device, which Windows takes for a terminal.
470
- if process.stdin is not None:
471
- process.stdin.close()
527
+ if process.popen.stdin is not None:
528
+ process.popen.stdin.close()
472
529
  return process
473
530
 
474
531
 
475
- def _take_handover(session_id: str) -> Optional[_Handover]:
476
- """Read and remove the file that the previous process of the session wrote for this one at a restart; None for
477
- the first process of a session."""
478
- path = _restart_path(session_id)
479
- try:
480
- handover = from_json(_retried(lambda: path.read_text(encoding="utf-8")), _Handover)
481
- except (OSError, ValueError, TypeError):
482
- return None
483
- with contextlib.suppress(OSError):
484
- path.unlink()
485
- return handover
486
-
487
-
488
- def _own_pipe(output: int) -> int:
489
- """The file descriptor of the read end `output` that `session start` passed down, a handle on Windows, which the
490
- processes that the session starts don't inherit."""
532
+ def _take_pipe(session_id: str, holder: Optional[PipeHolder]) -> int:
533
+ """A file descriptor of the read end of the pipe of the session, which the processes that the session starts don't
534
+ inherit: the FIFO opened by its path on Linux and macOS, the handle duplicated from `holder` on Windows.
535
+ `SessionError` with the reason when the process can't take it."""
491
536
  if sys.platform == "win32":
492
- os.set_handle_inheritable(output, False)
493
- return msvcrt.open_osfhandle(output, 0)
494
- os.set_inheritable(output, False)
495
- os.set_blocking(output, False)
496
- return output
537
+ if holder is None:
538
+ raise SessionError("No process that holds the output of the session was given.")
539
+ try:
540
+ process = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, holder.pid)
541
+ try:
542
+ handle = _winapi.DuplicateHandle(
543
+ process, holder.handle, _winapi.GetCurrentProcess(), 0, False, _winapi.DUPLICATE_SAME_ACCESS
544
+ )
545
+ finally:
546
+ _winapi.CloseHandle(process)
547
+ return msvcrt.open_osfhandle(handle, 0)
548
+ except OSError as e:
549
+ raise SessionError(
550
+ f"Can't take the output of the session from process {holder.pid}: {e.strerror or e}."
551
+ ) from e
552
+ path = _pipe_path(session_id)
553
+ try:
554
+ return os.open(path, os.O_RDONLY | os.O_NONBLOCK)
555
+ except OSError as e:
556
+ raise SessionError(f"Can't open the output of the session at {path}: {e.strerror or e}.") from e
497
557
 
498
558
 
499
559
  def _flush_output() -> None:
@@ -532,10 +592,12 @@ class SessionServer:
532
592
  The interpreter takes its inputs from `next_input`, in the main thread. Each request is answered on a thread of its
533
593
  own, so that a request to interrupt or stop the session, or one for the output so far, is answered while a statement
534
594
  runs; the inputs of the `send` requests run one after the other. When the REPL or the run has ended, `end` keeps the
535
- session open until it is stopped or has been idle too long, or starts it again in a new process for a restart.
595
+ session open until it is stopped or has been idle too long.
536
596
  """
537
597
 
538
- def __init__(self, session_id: str, kind: SessionKind, project: Path, idle_timeout: float, output: int) -> None:
598
+ def __init__(
599
+ self, session_id: str, kind: SessionKind, project: Path, idle_timeout: float, holder: Optional[PipeHolder]
600
+ ) -> None:
539
601
  self.session_id = session_id
540
602
  self._kind = kind
541
603
  self._condition = threading.Condition()
@@ -558,41 +620,20 @@ class SessionServer:
558
620
  # The REPL or the run ended because the session was idle too long, which ends the session too.
559
621
  self._idle_ended = False
560
622
  self._stop_requested = False
561
- self._restart_requested = False
562
623
  self._interrupted = False
563
624
  # The interpreter, which tells whether a signal has ended the REPL or the run.
564
625
  self._interpreter: Optional["SessionInterpreter"] = None
565
- # The answer to `restart`, once the new process has taken over or failed to.
566
- self._restart_answer: Optional[Union[RestartedAnswer, RestartFailedAnswer]] = None
567
- # Set while a restart starts the new process, which writes the session file from then on; `_handed_over` once
568
- # the new process has taken over and answers the requests.
569
- self._handing_over = False
570
- self._handed_over = False
571
626
  # Set when the channel starts to close, so that the requests that wait send their last answers, and once it has
572
627
  # closed.
573
628
  self._closing = False
574
629
  self._closed = False
575
630
  # Requests that are being answered.
576
631
  self._serving = 0
577
- # The debugger, whose breakpoints a restart hands on.
578
- self._controller: Optional[DebugController] = None
579
- # A restart starts the new process the way this one was started, with the environment and the current folder
580
- # from before the run could change them. With `sys.executable`, not `sys.orig_argv[0]`: on Windows, the
581
- # `python.exe` of a virtual environment runs the base interpreter, which `sys.orig_argv[0]` names and which
582
- # doesn't find the packages of the environment.
583
- self._command = [sys.executable, *sys.orig_argv[1:]]
584
- self._environment = dict(os.environ)
585
- self._folder = os.getcwd()
586
- handover = _take_handover(session_id)
587
- self._generation = handover.generation if handover is not None else 0
588
- self._handed_breakpoints = handover.breakpoints if handover is not None else None
589
632
  # The pipe the process writes its standard output and standard error to. What the session has read from it
590
633
  # stays in memory until an answer carries it.
591
- self._pipe = _own_pipe(output)
634
+ self._pipe = _take_pipe(session_id, holder)
592
635
  self._output = bytearray()
593
636
  self._output_lock = threading.Lock()
594
- # Whether this process reads the pipe; at a restart, the new process takes the reading over.
595
- self._reading = True
596
637
  # How much the session has read from the pipe, and how much of it the answers have carried.
597
638
  self._read_size = 0
598
639
  self._position = 0
@@ -600,8 +641,7 @@ class SessionServer:
600
641
  self._at_line_start = True
601
642
  self._decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
602
643
  key = os.urandom(32)
603
- create_sessions_dir()
604
- address = _address(session_id, self._generation)
644
+ address = _address(session_id)
605
645
  try:
606
646
  self._listener = Listener(address, family=_FAMILY, backlog=_BACKLOG, authkey=key)
607
647
  except OSError as e:
@@ -614,7 +654,7 @@ class SessionServer:
614
654
  address=str(self._listener.address),
615
655
  key=key.hex(),
616
656
  project=str(project),
617
- started=handover.started if handover is not None else now,
657
+ started=now,
618
658
  idle_timeout=idle_timeout,
619
659
  last_request=now,
620
660
  )
@@ -627,7 +667,7 @@ class SessionServer:
627
667
  threading.Thread(target=self._accept, name="robotcode-session", daemon=True).start()
628
668
  # Only once the file exists: until then, `session start` reads the pipe itself if the process ends before it is
629
669
  # ready.
630
- self._reader = self._start_reading()
670
+ threading.Thread(target=self._read_pipe, name="robotcode-session-output", daemon=True).start()
631
671
 
632
672
  def __enter__(self) -> "SessionServer":
633
673
  return self
@@ -646,19 +686,12 @@ class SessionServer:
646
686
  its REPL or run."""
647
687
  self._interpreter = interpreter
648
688
 
649
- def keep_breakpoints(self, controller: DebugController) -> None:
650
- """Remember `controller`, whose breakpoints a restart hands to the new process, and give it the breakpoints
651
- of the process before when a restart has started this one."""
652
- self._controller = controller
653
- if self._handed_breakpoints is not None:
654
- controller.restore_breakpoints(self._handed_breakpoints)
655
-
656
689
  # --- the interpreter, in the main thread ---------------------------------
657
690
 
658
691
  def next_input(self, prompt: str) -> str:
659
692
  """Wait at `prompt` for the next request and return its whole input; the request that ran before gets its
660
693
  answer first. While it waits, end the REPL or the run when the session has been idle too long or is asked to
661
- stop or restart."""
694
+ stop."""
662
695
  with self._condition:
663
696
  self._arrive(_Prompt.STOP if prompt.strip() == ConsoleInterpreter.DEBUG_PROMPT.strip() else _Prompt.INPUT)
664
697
  while True:
@@ -669,7 +702,7 @@ class SessionServer:
669
702
  self._update_entry(state=SessionState.RUNS)
670
703
  return queued.text
671
704
  if self._waits_at_stop():
672
- if self._stop_requested or self._restart_requested:
705
+ if self._stop_requested:
673
706
  # A debug session ends its run as `.abort` does.
674
707
  return ".abort"
675
708
  if self._idle():
@@ -689,7 +722,7 @@ class SessionServer:
689
722
 
690
723
  def end(self, exit_code: int) -> None:
691
724
  """The REPL or the run has ended with `exit_code`. The session stays open until it is stopped or idle too
692
- long, or until a restart has started it again in a new process."""
725
+ long."""
693
726
  _flush_output()
694
727
  with self._condition:
695
728
  if self._run_ended:
@@ -704,24 +737,21 @@ class SessionServer:
704
737
  ended_from_outside = (
705
738
  self._interpreter is not None
706
739
  and self._interpreter.termination_requested
707
- and not (self._stop_requested or self._restart_requested or self._interrupted)
740
+ and not (self._stop_requested or self._interrupted)
708
741
  )
709
742
  if not (self._idle_ended or ended_from_outside):
710
- while self._wait_after_end():
711
- if self._start_again():
712
- return
743
+ self._wait_after_end()
713
744
  with self._condition:
714
745
  # Before the last answers go out, so that a `session` command right after one doesn't find the session.
715
746
  _entry_path(self.session_id).unlink(missing_ok=True)
747
+ _pipe_path(self.session_id).unlink(missing_ok=True)
716
748
  self._close_channel()
717
749
 
718
- def _wait_after_end(self) -> bool:
719
- """Wait after the end of the REPL or the run until the session is asked to stop or restart, or has been idle
720
- too long; True for a restart."""
750
+ def _wait_after_end(self) -> None:
751
+ """Wait after the end of the REPL or the run until the session is asked to stop or has been idle too long."""
721
752
  with self._condition:
722
- while not (self._stop_requested or self._restart_requested or self._idle()):
753
+ while not (self._stop_requested or self._idle()):
723
754
  self._condition.wait(0.1)
724
- return self._restart_requested and not self._stop_requested
725
755
 
726
756
  def _close_channel(self) -> None:
727
757
  """Give the requests that wait a moment for their last answers, then close the channel. The caller holds
@@ -735,90 +765,6 @@ class SessionServer:
735
765
  with contextlib.suppress(OSError):
736
766
  self._listener.close()
737
767
 
738
- def _start_again(self) -> bool:
739
- """Start the session again in a new process, which takes over the session file and the pipe and opens a
740
- channel of its own; True once it has taken over. When the new process doesn't get ready, the session stays as
741
- it is."""
742
- with self._condition:
743
- self._handing_over = True
744
- breakpoints = self._controller.breakpoint_state() if self._controller is not None else None
745
- handover = _Handover(self._generation + 1, self._entry.started, breakpoints)
746
- # Only one process may read the pipe; from now on it is the new one.
747
- self._stop_reading()
748
- process: "Optional[subprocess.Popen[bytes]]" = None
749
- try:
750
- _write_json(_restart_path(self.session_id), handover)
751
- process = start_session_process(self._command, self._pipe_handle(), 1, self._environment, self._folder)
752
- self._wait_for_new_process(process)
753
- except SessionError as e:
754
- failure = str(e)
755
- except OSError as e:
756
- failure = f"The session couldn't start again: {e.strerror or e}."
757
- else:
758
- self._hand_over()
759
- return True
760
- self._keep_session(process, failure)
761
- return False
762
-
763
- def _wait_for_new_process(self, process: "subprocess.Popen[bytes]") -> None:
764
- """Wait until `process` has written the session file, which it does once it accepts requests; `SessionError`
765
- with the reason when it doesn't get ready."""
766
- # Known by its channel: on Windows, the `python.exe` of a virtual environment runs the interpreter in a process
767
- # of its own, whose ID isn't that of `process`.
768
- address = _address(self.session_id, self._generation + 1)
769
- ready_by = time.monotonic() + STARTUP_LIMIT
770
- while True:
771
- entry = _load_entry(self.session_id)
772
- if entry is not None and entry.address == address:
773
- return
774
- if process.poll() is not None:
775
- raise SessionError(
776
- f"The session couldn't start again; its new process ended with exit code {process.returncode}."
777
- )
778
- if time.monotonic() >= ready_by:
779
- process.kill()
780
- process.wait()
781
- raise SessionError(
782
- f"The session couldn't start again; its new process wasn't ready after {STARTUP_LIMIT} seconds "
783
- "and was ended."
784
- )
785
- time.sleep(0.05)
786
-
787
- def _hand_over(self) -> None:
788
- """Answer `restart` with the output since the last command, and close the channel, now that the new process
789
- has taken over the session file and the pipe."""
790
- with self._output_lock:
791
- size = self._read_size
792
- with self._condition:
793
- self._restart_answer = RestartedAnswer(self._read_output(size))
794
- self._handed_over = True
795
- self._close_channel()
796
- # Anything this process still writes would end up in the output of the new process.
797
- devnull = os.open(os.devnull, os.O_WRONLY)
798
- os.dup2(devnull, 1)
799
- os.dup2(devnull, 2)
800
- os.close(devnull)
801
-
802
- def _keep_session(self, process: "Optional[subprocess.Popen[bytes]]", failure: str) -> None:
803
- """After a restart that failed: end the new process, take what it wrote, and keep the session with its REPL or
804
- run ended."""
805
- if process is not None and process.poll() is None:
806
- process.kill()
807
- process.wait()
808
- with contextlib.suppress(OSError):
809
- _restart_path(self.session_id).unlink()
810
- with self._output_lock:
811
- # What the new process wrote, so that the answer carries it, before the reading goes on.
812
- self._take_output()
813
- self._reader = self._start_reading()
814
- with self._condition:
815
- self._handing_over = False
816
- # The new process may have written the file before it ended.
817
- self._update_entry()
818
- self._restart_answer = RestartFailedAnswer(self._read_output(self._output_size()), failure)
819
- self._restart_requested = False
820
- self._condition.notify_all()
821
-
822
768
  def _arrive(self, prompt: _Prompt) -> None:
823
769
  """The interpreter has arrived at `prompt`: give the request that ran its answer, and wake the threads that
824
770
  wait for it."""
@@ -879,9 +825,6 @@ class SessionServer:
879
825
  def _answer(self, connection: Connection, request: SessionRequest) -> ChannelAnswer:
880
826
  kind = request.kind
881
827
  with self._condition:
882
- if self._handed_over:
883
- # The command then asks the new process, which the session file names now.
884
- return MovedAnswer()
885
828
  if self._closing:
886
829
  # The session has just ended, as the next command would find.
887
830
  return RefusedAnswer(f"No session '{self.session_id}' is open.")
@@ -913,15 +856,13 @@ class SessionServer:
913
856
  return InterruptedAnswer()
914
857
  if kind is Request.STOP:
915
858
  return self._stop(connection)
916
- if kind is Request.RESTART:
917
- return self._restart(connection)
918
859
  assert_never(kind)
919
860
 
920
861
  def _ended_error(self) -> RefusedAnswer:
921
862
  session_id = self.session_id
922
863
  return RefusedAnswer(
923
- f"{self._kind.what} of session '{session_id}' has ended; `robotcode session restart {session_id}` starts "
924
- f"it again, and `robotcode session result {session_id}` prints its exit code."
864
+ f"{self._kind.what} of session '{session_id}' has ended; `robotcode session result {session_id}` prints "
865
+ f"its exit code, and `robotcode session stop {session_id}` ends the session."
925
866
  )
926
867
 
927
868
  def _send(self, connection: Connection, text: str) -> ChannelAnswer:
@@ -963,26 +904,12 @@ class SessionServer:
963
904
  self._stop_requested = True
964
905
  self._condition.notify_all()
965
906
  self._end_run()
966
- return self._await(connection, lambda: self._stopped_answer() if self._closing else None)
967
-
968
- def _stopped_answer(self) -> Union[MovedAnswer, StoppedAnswer]:
969
- if self._handed_over:
970
- # A restart has taken over meanwhile: the command stops the new process.
971
- return MovedAnswer()
972
- return StoppedAnswer(self._read_output(self._output_size()))
973
-
974
- def _restart(self, connection: Connection) -> ChannelAnswer:
975
- with self._condition:
976
- if self._restart_requested:
977
- return RefusedAnswer(f"Session '{self.session_id}' restarts already.")
978
- self._restart_requested = True
979
- self._restart_answer = None
980
- self._condition.notify_all()
981
- self._end_run()
982
- return self._await(connection, lambda: self._restart_answer)
907
+ return self._await(
908
+ connection, lambda: StoppedAnswer(self._read_output(self._output_size())) if self._closing else None
909
+ )
983
910
 
984
911
  def _end_run(self) -> None:
985
- """End the REPL or the run, unless it has ended, for a `stop` or a `restart` that the caller has noted."""
912
+ """End the REPL or the run, unless it has ended, for a `stop` that the caller has noted."""
986
913
  with self._condition:
987
914
  if self._run_ended:
988
915
  return
@@ -1052,55 +979,28 @@ class SessionServer:
1052
979
  return self._decoder.decode(data).replace("\r\n", "\n")
1053
980
 
1054
981
  def _output_size(self) -> int:
1055
- """How much the process has written so far, with what is still in the pipe; once the new process of a restart
1056
- reads the pipe, only what this process has read."""
982
+ """How much the process has written so far, with what is still in the pipe."""
1057
983
  with self._output_lock:
1058
- if self._reading:
1059
- self._take_output()
984
+ self._take_output()
1060
985
  return self._read_size
1061
986
 
1062
987
  def at_line_start(self) -> bool:
1063
988
  """Whether what the process has written up to now ends with a line break, or there is nothing yet."""
1064
989
  _flush_output()
1065
- with self._output_lock:
1066
- if self._reading:
1067
- self._take_output()
1068
- return self._at_line_start
1069
-
1070
- def _start_reading(self) -> threading.Thread:
1071
- self._reading = True
1072
- reader = threading.Thread(target=self._read_pipe, name="robotcode-session-output", daemon=True)
1073
- reader.start()
1074
- return reader
1075
-
1076
- def _stop_reading(self) -> None:
1077
- """Stop reading the pipe, so that the new process of a restart can read it; what the pipe holds now still
1078
- belongs to this process and is read first."""
1079
990
  with self._output_lock:
1080
991
  self._take_output()
1081
- self._reading = False
1082
- self._reader.join()
1083
-
1084
- def _pipe_handle(self) -> int:
1085
- """The pipe of the output as `session start` passed it down, a handle on Windows."""
1086
- if sys.platform == "win32":
1087
- return msvcrt.get_osfhandle(self._pipe)
1088
- return self._pipe
992
+ return self._at_line_start
1089
993
 
1090
994
  def _read_pipe(self) -> None:
1091
- """Read the pipe into memory while this process reads it, so that it doesn't fill up and hold up the processes
1092
- that write to it."""
995
+ """Read the pipe into memory, so that it doesn't fill up and hold up the processes that write to it."""
1093
996
  delay = 0.001
1094
997
  while True:
1095
998
  if sys.platform == "win32":
1096
999
  # Windows can't wait until a pipe has something to read.
1097
1000
  time.sleep(delay)
1098
1001
  else:
1099
- # With a timeout, so that the thread soon notices when a restart stops the reading.
1100
- select.select([self._pipe], [], [], 0.1)
1002
+ select.select([self._pipe], [], [])
1101
1003
  with self._output_lock:
1102
- if not self._reading:
1103
- return
1104
1004
  size = self._read_size
1105
1005
  if not self._take_output():
1106
1006
  return
@@ -1137,7 +1037,7 @@ class SessionServer:
1137
1037
  last_request: Optional[float] = None,
1138
1038
  ) -> None:
1139
1039
  """Write the session file, with the values given changed."""
1140
- if self._closing or self._handing_over:
1040
+ if self._closing:
1141
1041
  return
1142
1042
  if state is not None:
1143
1043
  self._entry.state = state
@@ -1150,8 +1050,8 @@ class SessionServer:
1150
1050
 
1151
1051
  def _signal(self, signum: int) -> None:
1152
1052
  """Let the interpreter, in the main thread, handle `signum` as when the signal arrives. Robot Framework handles
1153
- signals only during a run; without its handlers, as in the new process of a restart that is still starting, the
1154
- signal would end the process at once. So it waits for them, unless the REPL or the run has ended already."""
1053
+ signals only during a run; without its handlers, as in a session process that is still starting, the signal
1054
+ would end the process at once. So it waits for them, unless the REPL or the run has ended already."""
1155
1055
  while signal.getsignal(signum) in (signal.SIG_DFL, signal.default_int_handler):
1156
1056
  if self._run_ended:
1157
1057
  return