aboutsummaryrefslogtreecommitdiff
path: root/backends/common.py
diff options
context:
space:
mode:
Diffstat (limited to 'backends/common.py')
-rw-r--r--backends/common.py25
1 files changed, 25 insertions, 0 deletions
diff --git a/backends/common.py b/backends/common.py
index 2c6437f..d707fdc 100644
--- a/backends/common.py
+++ b/backends/common.py
@@ -141,6 +141,31 @@ def url_with_port(url: str, port: int) -> str:
(parts.scheme or "http", f"{host}:{port}", parts.path, "", ""))
+def server_running(url: str, timeout: float = 0.3) -> bool:
+ """True when something accepts TCP connections at URL's host:port.
+
+ A protocol-agnostic socket connect: an HTTP TTS server that is up will
+ accept the connection (we do not need to speak HTTP to know it is
+ listening). Returns False on any parse or connection error, so a
+ misconfigured URL never blocks the hub — it just reports the backend
+ as not running. Used by each backend's ``detect()`` to set
+ ``BackendStatus.running``.
+ """
+ import socket
+ try:
+ parts = urllib.parse.urlsplit(url)
+ host = parts.hostname or "127.0.0.1"
+ port = parts.port or (443 if (parts.scheme or "http") == "https"
+ else 80)
+ except ValueError:
+ return False
+ try:
+ with socket.create_connection((host, port), timeout=timeout):
+ return True
+ except OSError:
+ return False
+
+
def update_config_value(key: str, value: str,
config_path: Optional[Path] = None) -> bool:
"""Rewrite a ``KEY = "value"`` line in converter/config.py.