Coverage for faststream/_internal/cli/supervisors/utils.py: 94%

44 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1import asyncio 

2import multiprocessing 

3import os 

4import signal 

5import sys 

6import time 

7from collections.abc import Callable 

8from contextlib import suppress 

9from typing import TYPE_CHECKING, Any, Optional 

10 

11from faststream._internal._compat import IS_WINDOWS 

12 

13if TYPE_CHECKING: 

14 from multiprocessing.context import SpawnProcess 

15 from types import FrameType 

16 

17 from faststream._internal.basic_types import DecoratedCallableNone 

18 

19multiprocessing.allow_connection_pickling() 

20spawn = multiprocessing.get_context("spawn") 

21 

22 

23# Matches gunicorn's graceful timeout: long enough for a worker to drain, short 

24# enough that a stuck one cannot hold the supervisor hostage. 

25SHUTDOWN_TIMEOUT = 30.0 

26 

27# How often a lock-free wait re-reads its flag. 

28EXIT_POLL_INTERVAL = 0.05 

29 

30HANDLED_SIGNALS: tuple[int, ...] = ( 

31 signal.SIGINT, # Unix signal 2. Sent by Ctrl+C. 

32 signal.SIGTERM, # Unix signal 15. Sent by `kill <pid>`. 

33) 

34if IS_WINDOWS: # pragma: py-not-win32 

35 # Windows signal 21. Sent by Ctrl+Break. 

36 sigbreak: int | None = getattr(signal, "SIGBREAK", None) 

37 if sigbreak is not None: 37 ↛ 41line 37 didn't jump to line 41 because the condition on line 37 was always true

38 HANDLED_SIGNALS += (sigbreak,) 

39 

40 

41class ExitEvent: 

42 """A `threading.Event` a signal handler can set, because nothing here takes a lock. 

43 

44 `threading.Event.set()` holds the condition's lock while it notifies waiters. A 

45 second signal arriving in that window re-enters the handler and deadlocks the 

46 process on a lock it already owns (see issue #3119). 

47 """ 

48 

49 __slots__ = ("_is_set",) 

50 

51 def __init__(self) -> None: 

52 self._is_set = False 

53 

54 def set(self) -> None: 

55 self._is_set = True 

56 

57 def is_set(self) -> bool: 

58 return self._is_set 

59 

60 def wait(self, timeout: float | None = None) -> bool: 

61 deadline = None if timeout is None else time.monotonic() + timeout 

62 

63 while not self._is_set: 

64 if deadline is None: 64 ↛ 65line 64 didn't jump to line 65 because the condition on line 64 was never true

65 time.sleep(EXIT_POLL_INTERVAL) 

66 continue 

67 

68 remaining = deadline - time.monotonic() 

69 if remaining <= 0: 

70 return False 

71 

72 time.sleep(min(EXIT_POLL_INTERVAL, remaining)) 

73 

74 return True 

75 

76 

77def set_exit( 

78 func: Callable[[int, Optional["FrameType"]], Any], 

79 *, 

80 sync: bool = False, 

81) -> None: 

82 """Set exit handler for signals. 

83 

84 Args: 

85 func: A callable object that takes an integer and an optional frame type as arguments and returns any value. 

86 sync: set sync or async signal callback. 

87 """ 

88 if not sync: 

89 with suppress(NotImplementedError): 

90 loop = asyncio.get_event_loop() 

91 

92 for sig in HANDLED_SIGNALS: 

93 loop.add_signal_handler(sig, func, sig, None) 

94 

95 return 

96 

97 # Windows or sync mode 

98 for sig in HANDLED_SIGNALS: 

99 signal.signal(sig, func) 

100 

101 

102def get_subprocess( 

103 target: "DecoratedCallableNone", args: tuple[Any, ...] 

104) -> "SpawnProcess": 

105 """Spawn a subprocess.""" 

106 stdin_fileno: int | None 

107 try: 

108 stdin_fileno = sys.stdin.fileno() 

109 except OSError: 

110 stdin_fileno = None 

111 

112 return spawn.Process( 

113 target=subprocess_started, 

114 args=args, 

115 kwargs={"t": target, "stdin_fileno": stdin_fileno}, 

116 ) 

117 

118 

119def stop_process(process: "SpawnProcess", timeout: float = SHUTDOWN_TIMEOUT) -> None: 

120 """Terminate a worker, escalating to SIGKILL if it outlives the timeout.""" 

121 process.terminate() 

122 process.join(timeout) 

123 

124 if process.is_alive(): 

125 # An unbounded join hangs the supervisor forever on a worker deaf to SIGTERM. 

126 process.kill() 

127 process.join() 

128 

129 

130def subprocess_started( 

131 *args: Any, 

132 t: "DecoratedCallableNone", 

133 stdin_fileno: int | None, 

134) -> None: 

135 """Start a subprocess.""" 

136 if stdin_fileno is not None: # pragma: no cover 

137 sys.stdin = os.fdopen(stdin_fileno) 

138 t(*args)