|
1 | 1 | import asyncio
|
2 | 2 | import json
|
3 | 3 | import logging
|
| 4 | +import signal |
| 5 | +import sys |
4 | 6 | import time
|
5 | 7 | from collections.abc import Awaitable
|
6 | 8 | from typing import Any, Callable, Optional
|
@@ -29,6 +31,9 @@ class Stagehand(StagehandBase):
|
29 | 31 |
|
30 | 32 | # Dictionary to store one lock per session_id
|
31 | 33 | _session_locks = {}
|
| 34 | + |
| 35 | + # Flag to track if cleanup has been called |
| 36 | + _cleanup_called = False |
32 | 37 |
|
33 | 38 | def __init__(
|
34 | 39 | self,
|
@@ -115,6 +120,9 @@ def __init__(
|
115 | 120 | raise ValueError(
|
116 | 121 | "browserbase_project_id is required (or set BROWSERBASE_PROJECT_ID in env)."
|
117 | 122 | )
|
| 123 | + |
| 124 | + # Register signal handlers for graceful shutdown |
| 125 | + self._register_signal_handlers() |
118 | 126 |
|
119 | 127 | def _get_lock_for_session(self) -> asyncio.Lock:
|
120 | 128 | """
|
@@ -428,3 +436,40 @@ def _log(self, message: str, level: int = 1):
|
428 | 436 | logger.warning(formatted_msg)
|
429 | 437 | else:
|
430 | 438 | logger.debug(formatted_msg)
|
| 439 | + |
| 440 | + def _register_signal_handlers(self): |
| 441 | + """Register signal handlers for SIGINT and SIGTERM to ensure proper cleanup.""" |
| 442 | + def cleanup_handler(sig, frame): |
| 443 | + if self.__class__._cleanup_called: |
| 444 | + return |
| 445 | + |
| 446 | + self.__class__._cleanup_called = True |
| 447 | + print(f"\n[{signal.Signals(sig).name}] received. Ending Browserbase session...") |
| 448 | + |
| 449 | + try: |
| 450 | + # For more niceness, try to end the session synchronously |
| 451 | + if self.session_id: |
| 452 | + import requests |
| 453 | + headers = { |
| 454 | + "x-bb-api-key": self.browserbase_api_key, |
| 455 | + "x-bb-project-id": self.browserbase_project_id, |
| 456 | + "Content-Type": "application/json", |
| 457 | + } |
| 458 | + try: |
| 459 | + requests.post( |
| 460 | + f"{self.server_url}/sessions/{self.session_id}/end", |
| 461 | + json={"sessionId": self.session_id}, |
| 462 | + headers=headers, |
| 463 | + timeout=3.0 # Short timeout to avoid hanging |
| 464 | + ) |
| 465 | + print(f"Session {self.session_id} ended successfully") |
| 466 | + except Exception: |
| 467 | + # Ignore any errors during cleanup |
| 468 | + pass |
| 469 | + finally: |
| 470 | + # Just exit immediately with a successful status code |
| 471 | + sys.exit(0) |
| 472 | + |
| 473 | + # Register signal handlers |
| 474 | + signal.signal(signal.SIGINT, cleanup_handler) |
| 475 | + signal.signal(signal.SIGTERM, cleanup_handler) |
0 commit comments