Files
nanobot/nanobot/channels/whatsapp/connect.py
T

409 lines
16 KiB
Python

from __future__ import annotations
import asyncio
import os
import secrets
import time
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
from nanobot.channels.connect import ChannelConnectError, QueryParams, query_first
from nanobot.config.loader import load_config
if TYPE_CHECKING:
from nanobot.channels.whatsapp.runtime import WhatsAppChannel
_NATIVE_STOP_TIMEOUT_SECONDS = 10.0
_DATABASE_REPLACE_TIMEOUT_SECONDS = 10.0
_FINALIZE_POLL_WAIT_SECONDS = 0.05
_CONNECT_TTL_SECONDS = 600
@dataclass(slots=True)
class WhatsAppConnectSession:
id: str
channel: WhatsAppChannel
client: Any
result: asyncio.Future[None]
connect_task: asyncio.Task[asyncio.Task[Any] | None]
target_path: Path
pending_path: Path
created_wall: float
deadline: float
qr_url: str = ""
finalize_task: asyncio.Task[None] | None = None
stop_task: asyncio.Task[None] | None = None
discard_task: asyncio.Task[None] | None = None
expiry_task: asyncio.Task[None] | None = None
class WhatsAppConnectStore:
"""In-memory WhatsApp linked-device sessions for the WebUI."""
def __init__(self) -> None:
self._sessions: dict[str, WhatsAppConnectSession] = {}
@property
def has_pending_work(self) -> bool:
"""Keep login/native workers owned until completion or confirmed cleanup."""
return any(
session.finalize_task is None
or not session.finalize_task.done()
or not self._session_stopped(session)
or (session.discard_task is not None and not session.discard_task.done())
for session in self._sessions.values()
)
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
if action == "start":
force = (query_first(query, "force") or "").strip().lower() in {
"1",
"true",
"yes",
}
return await self.start(force=force)
session_id = (query_first(query, "session_id") or "").strip()
if not session_id:
raise ChannelConnectError("missing WhatsApp connect session")
if action == "poll":
return await self.poll(session_id)
if action == "cancel":
return await self.cancel(session_id)
raise ChannelConnectError(f"unsupported WhatsApp connect action: {action}", status=404)
async def start(self, *, force: bool = False) -> dict[str, Any]:
await self._cleanup()
channel, target_path = self._build_channel()
if not force and self._local_state_present(target_path):
return {
"session_id": "",
"status": "succeeded",
"message": "WhatsApp is already connected.",
"interval_ms": 2000,
}
session_id = secrets.token_urlsafe(18)
pending_path = target_path.with_name(f".{target_path.name}.{session_id}.connect")
pending_path.parent.mkdir(parents=True, exist_ok=True)
self._remove_database(pending_path)
channel.config.database_path = str(pending_path)
now_wall = time.time()
async def capture_qr(qr_data: bytes) -> None:
session = self._sessions.get(session_id)
if session is not None:
session.qr_url = qr_data.decode("utf-8")
from nanobot.channels.whatsapp.runtime import WhatsAppDependencyError
try:
client, result = channel.connect_open_client(capture_qr)
except WhatsAppDependencyError as exc:
raise ChannelConnectError(str(exc)) from exc
connect_task = asyncio.create_task(
self._connect(channel, client, result),
name=f"whatsapp-connect-{session_id}",
)
session = WhatsAppConnectSession(
id=session_id,
channel=channel,
client=client,
result=result,
connect_task=connect_task,
target_path=target_path,
pending_path=pending_path,
created_wall=now_wall,
deadline=time.monotonic() + _CONNECT_TTL_SECONDS,
)
self._sessions[session_id] = session
session.expiry_task = asyncio.create_task(
self._expire_session(session), name=f"whatsapp-connect-expire-{session.id}",
)
session.expiry_task.add_done_callback(self._observe_task)
qr_wait = asyncio.create_task(self._wait_for_qr(session))
try:
await asyncio.wait(
{qr_wait, connect_task},
timeout=3,
return_when=asyncio.FIRST_COMPLETED,
)
finally:
if not qr_wait.done():
qr_wait.cancel()
await asyncio.gather(qr_wait, return_exceptions=True)
return self._pending_payload(session)
async def poll(self, session_id: str) -> dict[str, Any]:
await self._cleanup()
session = self._sessions.get(session_id)
if session is None:
return {
"session_id": session_id,
"status": "expired",
"message": "This WhatsApp login has expired. Start again.",
}
if session.discard_task is not None:
# A concurrent poll must not promote a login being cancelled.
return await self.cancel(session_id)
if not session.result.done():
return self._pending_payload(session)
finalize_task = session.finalize_task
if finalize_task is None:
finalize_task = asyncio.create_task(
self._finalize_session(session),
name=f"whatsapp-connect-finalize-{session.id}",
)
session.finalize_task = finalize_task
if not finalize_task.done():
# Finish fast clients in this request without letting native shutdown
# block the polling response path.
await asyncio.wait({finalize_task}, timeout=_FINALIZE_POLL_WAIT_SECONDS)
if session.discard_task is not None:
return await self.cancel(session_id)
if not finalize_task.done():
payload = self._pending_payload(session)
payload["qr_url"] = ""
payload["message"] = "Finishing the WhatsApp connection."
return payload
try:
finalize_task.result()
except Exception as exc:
if self._session_stopped(session):
self._sessions.pop(session_id, None)
return {
"session_id": session_id,
"status": "failed",
"message": f"WhatsApp QR login failed: {exc}",
}
self._sessions.pop(session_id, None)
return {
"session_id": session_id,
"status": "succeeded",
"message": "WhatsApp is connected.",
}
async def _finalize_session(self, session: WhatsAppConnectSession) -> None:
try:
session.result.result()
except BaseException:
await self._close_session(session)
self._remove_database(session.pending_path)
raise
# A stop timeout is not proof that the native SQLite writer exited.
# Preserve its database and ownership for an explicit cleanup retry.
await self._close_session(session)
try:
await self._commit_database(session.pending_path, session.target_path)
except BaseException:
self._remove_database(session.pending_path)
raise
async def cancel(self, session_id: str) -> dict[str, Any]:
session = self._sessions.get(session_id)
if session is not None:
await self._discard_session(session)
return {
"session_id": session_id,
"status": "cancelled",
"message": "WhatsApp login cancelled.",
}
async def _cleanup(self) -> None:
expired = [
session_id
for session_id, session in self._sessions.items()
if time.monotonic() >= session.deadline
]
for session_id in expired:
await self.cancel(session_id)
async def _expire_session(self, session: WhatsAppConnectSession) -> None:
await asyncio.sleep(max(0, session.deadline - time.monotonic()))
await self.cancel(session.id)
async def close(self) -> None:
"""Stop every login client before the gateway event loop closes."""
sessions = tuple(self._sessions.values())
for session in sessions:
await self._discard_session(session)
async def _discard_session(self, session: WhatsAppConnectSession) -> None:
task = session.discard_task
if task is None or task.done():
task = asyncio.create_task(
self._discard_and_remove(session), name=f"whatsapp-connect-discard-{session.id}",
)
task.add_done_callback(self._observe_task)
session.discard_task = task
# Closing a browser/request must not drop the native writer's owner.
await asyncio.shield(task)
async def _discard_and_remove(self, session: WhatsAppConnectSession) -> None:
finalize_task = session.finalize_task
if (
finalize_task is not None
and finalize_task is not asyncio.current_task()
):
if not finalize_task.done():
finalize_task.cancel()
await asyncio.gather(finalize_task, return_exceptions=True)
await self._close_session(session)
self._remove_database(session.pending_path)
if self._sessions.get(session.id) is session:
del self._sessions[session.id]
@staticmethod
async def _connect(
channel: WhatsAppChannel,
client: Any,
result: asyncio.Future[None],
) -> asyncio.Task[Any] | None:
try:
return await channel.connect_start_client(client, result)
except asyncio.CancelledError:
raise
except Exception as exc:
if not result.done():
result.set_exception(exc)
return None
@staticmethod
async def _wait_for_qr(session: WhatsAppConnectSession) -> None:
while not session.qr_url and not session.result.done():
await asyncio.sleep(0.05)
async def _close_session(self, session: WhatsAppConnectSession) -> None:
task = session.stop_task
if task is None or (task.done() and not task.cancelled() and task.exception() is not None):
task = asyncio.create_task(
self._stop_session(session), name=f"whatsapp-connect-stop-{session.id}",
)
task.add_done_callback(self._observe_task)
session.stop_task = task
try:
await asyncio.wait_for(asyncio.shield(task), timeout=_NATIVE_STOP_TIMEOUT_SECONDS)
except TimeoutError as exc:
raise RuntimeError(
"WhatsApp is still stopping. Retry cancelling the connection before updating."
) from exc
@staticmethod
def _observe_task(task: asyncio.Task[None]) -> None:
if not task.cancelled():
task.exception()
@staticmethod
def _session_stopped(session: WhatsAppConnectSession) -> bool:
task = session.stop_task
return task is not None and task.done() and not task.cancelled() and task.exception() is None
@staticmethod
async def _stop_session(session: WhatsAppConnectSession) -> None:
if session.expiry_task is not None:
session.expiry_task.cancel()
await asyncio.gather(session.expiry_task, return_exceptions=True)
if not session.result.done():
session.result.cancel()
elif not session.result.cancelled():
session.result.exception()
# Both Stop and Neonize use asyncio.to_thread in the supported SDK.
# Cancellation cannot join those threads. Signal, then await actual return;
# the bounded caller may time out without cancelling this owned task.
await session.client.stop()
await asyncio.shield(asyncio.gather(session.connect_task, return_exceptions=True))
if session.connect_task.cancelled():
raise RuntimeError("WhatsApp connection shutdown could not be verified")
native_task = session.connect_task.result()
client_native_task = getattr(session.client, "connect_task", None)
if native_task is None and isinstance(client_native_task, asyncio.Task):
native_task = cast(asyncio.Task[Any], client_native_task)
if native_task is not None:
await asyncio.shield(asyncio.gather(native_task, return_exceptions=True))
if native_task.cancelled():
raise RuntimeError("WhatsApp native shutdown could not be verified")
@staticmethod
def _build_channel() -> tuple[WhatsAppChannel, Path]:
from nanobot.bus.queue import MessageBus
from nanobot.channels.whatsapp.runtime import WhatsAppChannel
root_config = load_config()
section = getattr(root_config.channels, "whatsapp", None)
if section is not None and hasattr(section, "model_dump"):
config = section.model_dump(mode="json", by_alias=True)
elif isinstance(section, dict):
config = dict(cast(dict[str, Any], section))
else:
config = {}
channel = WhatsAppChannel(config, MessageBus(), network=root_config.network)
return channel, channel.connect_database_path()
@staticmethod
def _local_state_present(path: Path) -> bool:
try:
return path.is_file() and path.stat().st_size > 0
except OSError:
return False
@classmethod
async def _commit_database(cls, pending: Path, target: Path) -> None:
if not cls._local_state_present(pending):
raise RuntimeError("WhatsApp connected but did not create a local session database")
target.parent.mkdir(parents=True, exist_ok=True)
for pending_file, target_file in cls._database_files(pending, target):
if pending_file.exists():
await cls._replace_database_file(pending_file, target_file)
elif target_file != target and target_file.exists():
target_file.unlink()
@staticmethod
async def _replace_database_file(source: Path, target: Path) -> None:
deadline = time.monotonic() + _DATABASE_REPLACE_TIMEOUT_SECONDS
while True:
try:
os.replace(source, target)
return
except PermissionError as exc:
if time.monotonic() >= deadline:
raise RuntimeError(
"WhatsApp paired, but its local session database is still in use"
) from exc
await asyncio.sleep(0.1)
@classmethod
def _remove_database(cls, path: Path) -> None:
for candidate, _ in cls._database_files(path, path):
with suppress(OSError):
candidate.unlink()
@staticmethod
def _database_files(source: Path, target: Path) -> tuple[tuple[Path, Path], ...]:
return (
(source, target),
(source.with_name(source.name + "-shm"), target.with_name(target.name + "-shm")),
(source.with_name(source.name + "-wal"), target.with_name(target.name + "-wal")),
)
@staticmethod
def _pending_payload(session: WhatsAppConnectSession) -> dict[str, Any]:
payload: dict[str, Any] = {
"session_id": session.id,
"status": "pending",
"interval_ms": 2000,
"expires_at_ms": int((session.created_wall + _CONNECT_TTL_SECONDS) * 1000),
"message": "Waiting for the WhatsApp scan.",
}
if session.qr_url:
payload["qr_url"] = session.qr_url
return payload
__all__ = ["WhatsAppConnectStore"]