debug_ita_monitor.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #!/usr/bin/env python3
  2. """Run a bounded local Italy Query monitor with no booking side effects."""
  3. from __future__ import annotations
  4. import argparse
  5. import os
  6. import random
  7. import sys
  8. import time
  9. from pathlib import Path
  10. from typing import Callable, Mapping
  11. REPO_ROOT = Path(__file__).resolve().parents[1]
  12. if str(REPO_ROOT) not in sys.path:
  13. sys.path.insert(0, str(REPO_ROOT))
  14. from plugins.ita_plugin import ItaPlugin
  15. from tools.debug_ita_query import (
  16. _get_query_credentials,
  17. _is_nonempty_query_result,
  18. _is_weak_entry_signal,
  19. _popup_text_for_log,
  20. _prepare_query_profile,
  21. _print_booking_form_structure,
  22. _print_failure_context,
  23. build_query_config,
  24. resolve_debug_route,
  25. )
  26. from tools.debug_ita_session import (
  27. DebugConfigurationError,
  28. resolve_chrome_path,
  29. )
  30. from tools.ita_local_handoff import (
  31. ITA_LOCAL_SIGNAL_TTL_SECONDS,
  32. publish_local_weak_signal,
  33. )
  34. from vs_types import BizLogicError
  35. MIN_SAFE_WAIT_SECONDS = 60
  36. DEFAULT_MAX_WAIT_SECONDS = 300
  37. DEFAULT_MAX_PROBES = 10
  38. MAX_ALLOWED_PROBES = 100
  39. class _MonitorCancelled(Exception):
  40. """Internal control flow for a clean Ctrl+C."""
  41. def _validate_monitor_limits(
  42. *,
  43. min_wait: int,
  44. max_wait: int,
  45. max_probes: int,
  46. ) -> None:
  47. if min_wait < MIN_SAFE_WAIT_SECONDS:
  48. raise DebugConfigurationError(
  49. f"min_wait must be at least {MIN_SAFE_WAIT_SECONDS} seconds"
  50. )
  51. if max_wait < min_wait:
  52. raise DebugConfigurationError("max_wait must be greater than min_wait")
  53. if not 1 <= max_probes <= MAX_ALLOWED_PROBES:
  54. raise DebugConfigurationError(
  55. f"max_probes must be between 1 and {MAX_ALLOWED_PROBES}"
  56. )
  57. def run_monitor(
  58. env: Mapping[str, str],
  59. *,
  60. apply: bool,
  61. non_interactive: bool,
  62. min_wait: int,
  63. max_wait: int,
  64. max_probes: int,
  65. publish_local_signal: bool = False,
  66. signal_publisher: Callable[[], object] | None = None,
  67. randint: Callable[[int, int], int] = random.randint,
  68. sleep: Callable[[float], None] = time.sleep,
  69. ) -> int:
  70. route = resolve_debug_route(env)
  71. route_log = (
  72. f"service_id={route.service_id} routing_key={route.routing_key}"
  73. )
  74. _validate_monitor_limits(
  75. min_wait=min_wait,
  76. max_wait=max_wait,
  77. max_probes=max_probes,
  78. )
  79. if not apply:
  80. print(
  81. "ITA_MONITOR_PREFLIGHT_OK "
  82. f"{route_log} min_wait={min_wait} "
  83. f"max_wait={max_wait} max_probes={max_probes} "
  84. f"local_handoff={str(publish_local_signal).lower()} "
  85. "external_request=false"
  86. )
  87. return 0
  88. chrome_path = resolve_chrome_path(env)
  89. os.environ["CHROME_BIN"] = str(chrome_path)
  90. username, password = _get_query_credentials(
  91. env,
  92. non_interactive=non_interactive,
  93. )
  94. profile_path = _prepare_query_profile(username)
  95. config = build_query_config(
  96. env,
  97. username=username,
  98. password=password,
  99. persistent_profile_path=profile_path,
  100. route=route,
  101. )
  102. plugin = ItaPlugin(group_id="ita-monitor-local-debug")
  103. plugin.set_log(lambda message: print(message, flush=True))
  104. plugin.set_config(config)
  105. exit_code = 0
  106. cleanup_error: Exception | None = None
  107. try:
  108. plugin.create_session()
  109. print(
  110. "ITA_MONITOR_STARTED "
  111. f"{route_log} session_attempts=1 "
  112. f"max_probes={max_probes}"
  113. )
  114. for probe_number in range(1, max_probes + 1):
  115. print(
  116. "ITA_MONITOR_PROBE_START "
  117. f"{route_log} probe={probe_number}"
  118. )
  119. result = plugin.query(route.appointment_type())
  120. if _is_weak_entry_signal(result):
  121. if publish_local_signal:
  122. publisher = signal_publisher or (
  123. lambda: publish_local_weak_signal(
  124. service_id=route.service_id,
  125. routing_key=route.routing_key,
  126. )
  127. )
  128. publisher()
  129. print(
  130. "ITA_MONITOR_HANDOFF_PUBLISHED "
  131. f"{route_log} "
  132. f"ttl_seconds={ITA_LOCAL_SIGNAL_TTL_SECONDS} "
  133. "payload=metadata-only",
  134. flush=True,
  135. )
  136. _print_booking_form_structure(plugin, route=route)
  137. print(
  138. "\aITA_MONITOR_WEAK_SIGNAL "
  139. f"{route_log} probe={probe_number} "
  140. "evidence=booking-form action=start-user-book-recheck-now",
  141. flush=True,
  142. )
  143. exit_code = 4
  144. break
  145. if _is_nonempty_query_result(result):
  146. print(
  147. "ITA_MONITOR_SAFE_STOP "
  148. f"{route_log} probe={probe_number} "
  149. "reason=non-empty-availability-result"
  150. )
  151. exit_code = 4
  152. break
  153. print(
  154. "ITA_MONITOR_NONE_AVAILABLE "
  155. f"{route_log} probe={probe_number}"
  156. )
  157. if probe_number == max_probes:
  158. print(
  159. "ITA_MONITOR_MAX_PROBES_REACHED "
  160. f"{route_log} probes={max_probes}"
  161. )
  162. break
  163. wait_seconds = randint(min_wait, max_wait)
  164. print(
  165. "ITA_MONITOR_WAIT "
  166. f"next_probe={probe_number + 1} seconds={wait_seconds}",
  167. flush=True,
  168. )
  169. try:
  170. sleep(wait_seconds)
  171. except KeyboardInterrupt:
  172. raise _MonitorCancelled from None
  173. except _MonitorCancelled:
  174. print(
  175. "\nITA_MONITOR_CANCELLED "
  176. f"{route_log}",
  177. )
  178. exit_code = 130
  179. except KeyboardInterrupt:
  180. print(
  181. "\nITA_MONITOR_CANCELLED "
  182. f"{route_log}",
  183. )
  184. exit_code = 130
  185. except BizLogicError as exc:
  186. print(
  187. f"ITA_MONITOR_FAILED type={type(exc).__name__} "
  188. f"message={_popup_text_for_log(exc)}"
  189. )
  190. _print_failure_context(plugin)
  191. exit_code = 1
  192. except Exception as exc:
  193. print(
  194. f"ITA_MONITOR_FAILED type={type(exc).__name__} "
  195. f"message={_popup_text_for_log(exc)}"
  196. )
  197. _print_failure_context(plugin)
  198. exit_code = 1
  199. finally:
  200. try:
  201. plugin.cleanup()
  202. print("ITA_MONITOR_CLEANUP_OK")
  203. except Exception as exc:
  204. cleanup_error = exc
  205. print(
  206. f"ITA_MONITOR_CLEANUP_FAILED type={type(exc).__name__} "
  207. f"message={_popup_text_for_log(exc)}",
  208. file=sys.stderr,
  209. )
  210. return 3 if cleanup_error is not None else exit_code
  211. def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
  212. parser = argparse.ArgumentParser(
  213. description=(
  214. "Bounded route-configured Italy Query monitor. Without --run, "
  215. "performs a zero-network preflight only."
  216. )
  217. )
  218. parser.add_argument(
  219. "--run",
  220. action="store_true",
  221. help="Start the bounded real website monitor.",
  222. )
  223. parser.add_argument(
  224. "--non-interactive",
  225. action="store_true",
  226. help="Fail instead of prompting when local credentials are unavailable.",
  227. )
  228. parser.add_argument(
  229. "--min-wait",
  230. type=int,
  231. default=MIN_SAFE_WAIT_SECONDS,
  232. help=f"Minimum seconds between probes (floor: {MIN_SAFE_WAIT_SECONDS}).",
  233. )
  234. parser.add_argument(
  235. "--max-wait",
  236. type=int,
  237. default=DEFAULT_MAX_WAIT_SECONDS,
  238. help="Maximum seconds between probes.",
  239. )
  240. parser.add_argument(
  241. "--max-probes",
  242. type=int,
  243. default=DEFAULT_MAX_PROBES,
  244. help=f"Maximum probes in one run (ceiling: {MAX_ALLOWED_PROBES}).",
  245. )
  246. parser.add_argument(
  247. "--publish-local-signal",
  248. action="store_true",
  249. help=(
  250. "On a verified weak signal, atomically notify one local Book "
  251. "debugger. Production signaling behavior is unchanged."
  252. ),
  253. )
  254. return parser.parse_args(argv)
  255. def main(argv: list[str] | None = None) -> int:
  256. args = parse_args(argv)
  257. try:
  258. return run_monitor(
  259. os.environ,
  260. apply=args.run,
  261. non_interactive=args.non_interactive,
  262. min_wait=args.min_wait,
  263. max_wait=args.max_wait,
  264. max_probes=args.max_probes,
  265. publish_local_signal=args.publish_local_signal,
  266. )
  267. except DebugConfigurationError as exc:
  268. print(f"ITA_MONITOR_CONFIG_ERROR: {exc}", file=sys.stderr)
  269. return 2
  270. if __name__ == "__main__":
  271. raise SystemExit(main())