|
| 1 | +"""Per-session file lock guarding against concurrent Telegram connections. |
| 2 | +
|
| 3 | +MCP clients (Claude Desktop in particular) sometimes spawn more than one |
| 4 | +instance of this server for the same configured session -- most commonly |
| 5 | +when a connector is restarted and the old process hasn't exited yet before |
| 6 | +the new one starts. Two processes calling ``TelegramClient.connect()`` / |
| 7 | +``start()`` with the same auth key at the same time trips Telegram's abuse |
| 8 | +protection (``AuthKeyDuplicatedError``), which can knock out *both* |
| 9 | +connections rather than just the newcomer. |
| 10 | +
|
| 11 | +This module provides an OS-level advisory file lock (``flock`` on POSIX, |
| 12 | +``msvcrt.locking`` on Windows) keyed by the session's actual identity (its |
| 13 | +string value or file path), not just the account label, since two different |
| 14 | +projects/labels could otherwise collide or one label could map to different |
| 15 | +sessions across deployments. The lock is held for the lifetime of the |
| 16 | +process and is released automatically by the OS if the process exits or is |
| 17 | +killed, so there is no stale-lock file to clean up. |
| 18 | +
|
| 19 | +A second instance racing for the same session waits briefly (covers the |
| 20 | +"restart replaces the old process" case) and, if the lock is still held once |
| 21 | +the grace period elapses, raises :class:`SessionLockError` instead of ever |
| 22 | +calling ``connect()`` -- so the live session is never disturbed. |
| 23 | +""" |
| 24 | + |
| 25 | +from __future__ import annotations |
| 26 | + |
| 27 | +import hashlib |
| 28 | +import os |
| 29 | +import tempfile |
| 30 | +import time |
| 31 | +from pathlib import Path |
| 32 | +from typing import IO, Optional |
| 33 | + |
| 34 | +if os.name == "nt": |
| 35 | + import msvcrt |
| 36 | + |
| 37 | + def _try_lock(fh: IO) -> bool: |
| 38 | + try: |
| 39 | + fh.seek(0) |
| 40 | + msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1) |
| 41 | + return True |
| 42 | + except OSError: |
| 43 | + return False |
| 44 | + |
| 45 | + def _unlock(fh: IO) -> None: |
| 46 | + try: |
| 47 | + fh.seek(0) |
| 48 | + msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1) |
| 49 | + except OSError: |
| 50 | + pass |
| 51 | + |
| 52 | +else: |
| 53 | + import fcntl |
| 54 | + |
| 55 | + def _try_lock(fh: IO) -> bool: |
| 56 | + try: |
| 57 | + fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 58 | + return True |
| 59 | + except OSError: |
| 60 | + return False |
| 61 | + |
| 62 | + def _unlock(fh: IO) -> None: |
| 63 | + try: |
| 64 | + fcntl.flock(fh.fileno(), fcntl.LOCK_UN) |
| 65 | + except OSError: |
| 66 | + pass |
| 67 | + |
| 68 | + |
| 69 | +DEFAULT_LOCK_DIR = Path(tempfile.gettempdir()) / "telegram-mcp-locks" |
| 70 | +DEFAULT_GRACE_SECONDS = 20.0 |
| 71 | +DEFAULT_POLL_INTERVAL = 0.5 |
| 72 | + |
| 73 | + |
| 74 | +class SessionLockError(RuntimeError): |
| 75 | + """Raised when a session lock isn't acquired before its grace period elapses.""" |
| 76 | + |
| 77 | + |
| 78 | +class SessionLock: |
| 79 | + """Exclusive, OS-released lock for one Telegram session, held for process lifetime.""" |
| 80 | + |
| 81 | + def __init__(self, label: str, session_identity: str, *, lock_dir: Path = DEFAULT_LOCK_DIR): |
| 82 | + digest = hashlib.sha256(session_identity.encode("utf-8")).hexdigest()[:16] |
| 83 | + lock_dir.mkdir(parents=True, exist_ok=True) |
| 84 | + self.path = lock_dir / f"{label}-{digest}.lock" |
| 85 | + self._fh: Optional[IO] = None |
| 86 | + |
| 87 | + def acquire( |
| 88 | + self, |
| 89 | + *, |
| 90 | + grace_seconds: float = DEFAULT_GRACE_SECONDS, |
| 91 | + poll_interval: float = DEFAULT_POLL_INTERVAL, |
| 92 | + ) -> None: |
| 93 | + """Block (up to ``grace_seconds``) until the lock is free, then take it. |
| 94 | +
|
| 95 | + Raises :class:`SessionLockError` if another live process still holds |
| 96 | + the lock once the grace period elapses. |
| 97 | + """ |
| 98 | + fh = open(self.path, "a+") |
| 99 | + deadline = time.monotonic() + grace_seconds |
| 100 | + while True: |
| 101 | + if _try_lock(fh): |
| 102 | + self._fh = fh |
| 103 | + return |
| 104 | + if time.monotonic() >= deadline: |
| 105 | + fh.close() |
| 106 | + raise SessionLockError( |
| 107 | + "Another telegram-mcp process is already connected with this " |
| 108 | + f"session (lock held: {self.path}). Refusing to connect a " |
| 109 | + "second time to avoid Telegram's AuthKeyDuplicatedError. If " |
| 110 | + "that other process already exited, this lock will clear on " |
| 111 | + "its own -- retry." |
| 112 | + ) |
| 113 | + time.sleep(poll_interval) |
| 114 | + |
| 115 | + def release(self) -> None: |
| 116 | + if self._fh is not None: |
| 117 | + _unlock(self._fh) |
| 118 | + self._fh.close() |
| 119 | + self._fh = None |
| 120 | + |
| 121 | + |
| 122 | +def session_identity(client: object) -> str: |
| 123 | + """Derive a stable identity string for a ``TelegramClient``'s session. |
| 124 | +
|
| 125 | + File-based sessions key on the absolute file path; string sessions key on |
| 126 | + their serialized value (same auth key -> same identity, regardless of |
| 127 | + which process or working directory loaded it). Falls back to the |
| 128 | + client's object id for sessionless test doubles. |
| 129 | + """ |
| 130 | + session = getattr(client, "session", None) |
| 131 | + if session is not None: |
| 132 | + filename = getattr(session, "filename", None) |
| 133 | + if filename: |
| 134 | + return f"file:{os.path.abspath(filename)}" |
| 135 | + save = getattr(session, "save", None) |
| 136 | + if callable(save): |
| 137 | + try: |
| 138 | + saved = save() |
| 139 | + except Exception: |
| 140 | + saved = None |
| 141 | + if saved: |
| 142 | + return f"string:{saved}" |
| 143 | + return f"anon:{id(client)}" |
0 commit comments