Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Mattermost directory search waits for the bridge to connect

Petr Bauch3b248964da83
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index 97b302113..71626f520 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -99,6 +99,12 @@ _MAX_BOT_ICON_BYTES = 5 * 1024 * 1024
# would hold the call, and anything waiting on it, indefinitely.
_MM_REQUEST_TIMEOUT_SECONDS = 10.0
+# How long a directory search made while the adapter is still connecting waits
+# for it. A bridge is searched as soon as it is registered (the gateway's
+# directory dialog, the setup scripts), and connecting is a log-in and two
+# reads, so it is normally under a second.
+_CONNECT_WAIT_SECONDS = 15.0
+
# Mattermost channel types a bot can be *added* to: open and private channels.
# Membership of a DM ("D") or group DM ("G") is a property of the conversation
# existing rather than of anyone joining, so Mattermost raises no `user_added`
@@ -408,6 +414,10 @@ class MattermostAdapter(PlatformAdapter):
self._admin_driver: Driver | None = None
self._team_id: str = ""
+ # Set once the admin driver has logged in and the team is known: what
+ # a directory search needs. The lifecycle starts the adapter in the
+ # background, so a search can arrive before then.
+ self._connected = asyncio.Event()
self._admin_user_id: str = ""
self._agent_bots: dict[str, dict[str, str]] = {}
@@ -494,11 +504,12 @@ class MattermostAdapter(PlatformAdapter):
self._on_app_joined = on_app_joined
self._main_loop = asyncio.get_event_loop()
- self._admin_driver = self._create_driver(
+ admin_driver = self._create_driver(
login_id=self._config.admin_user,
password=self._config.admin_password,
)
- await self._main_loop.run_in_executor(None, self._admin_driver.login)
+ await self._main_loop.run_in_executor(None, admin_driver.login)
+ self._admin_driver = admin_driver
me = await self._main_loop.run_in_executor(
None, self._admin_driver.users.get_user, "me"
@@ -509,6 +520,7 @@ class MattermostAdapter(PlatformAdapter):
None, self._admin_driver.teams.get_team_by_name, self._config.team_name
)
self._team_id = team["id"]
+ self._connected.set()
await self._ensure_admin_bot()
@@ -521,6 +533,7 @@ class MattermostAdapter(PlatformAdapter):
)
async def stop(self) -> None:
+ self._connected.clear()
for agent_name in list(self._ws_stops):
self._close_bot_socket(agent_name)
self._admin_driver = None
@@ -2784,14 +2797,21 @@ class MattermostAdapter(PlatformAdapter):
Scoped to the bridge's team, and bots are dropped — a bot is not a
person who can own an agent.
"""
- if not self._admin_driver or not self._main_loop:
- raise RuntimeError("Mattermost adapter is not started")
-
term = query.strip()
if not term:
return []
+ try:
+ async with asyncio.timeout(_CONNECT_WAIT_SECONDS):
+ await self._connected.wait()
+ except TimeoutError:
+ raise RuntimeError(
+ "The Mattermost bridge is not connected yet, so its directory "
+ f"cannot be searched; it did not connect within {_CONNECT_WAIT_SECONDS:.0f}s."
+ ) from None
driver = self._admin_driver
+ if driver is None or self._main_loop is None:
+ raise RuntimeError("Mattermost adapter is not started")
try:
found = await self._main_loop.run_in_executor(
None,
diff --git a/core/switch_core/bridges/collaboration/mattermost/http_client.py b/core/switch_core/bridges/collaboration/mattermost/http_client.py
index 7e6e3968c..5cfec96cd 100644
--- a/core/switch_core/bridges/collaboration/mattermost/http_client.py
+++ b/core/switch_core/bridges/collaboration/mattermost/http_client.py
@@ -92,7 +92,10 @@ class NoRedirectClient(Client): # type: ignore[misc]
message = body.get("message", body)
except ValueError:
message = response.text
- logger.error("Mattermost %s %s failed: %s", method, endpoint, message)
+ # An expired session is routine: the adapter logs in again and
+ # retries (`_mm_api_blocking`), and raises where it cannot.
+ log = logger.warning if exc.response.status_code == 401 else logger.error
+ log("Mattermost %s %s failed: %s", method, endpoint, message)
error = _ERRORS_BY_STATUS.get(exc.response.status_code)
if error is not None:
raise error(message) from None
diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_directory_search.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_directory_search.py
new file mode 100644
index 000000000..76c26f5e9
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_directory_search.py
@@ -0,0 +1,182 @@
+"""Searching a Mattermost bridge's directory while it is still connecting.
+
+The lifecycle starts the adapter in the background, and a bridge is searched
+as soon as it is registered (the gateway's directory dialog, setup scripts).
+A search that arrived before the admin driver had logged in went out with no
+session, and Mattermost refused it as "Invalid or expired session", logged as
+an error and answered as a 502. It now waits for the adapter to connect.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import threading
+from typing import Any
+
+import pytest
+import requests
+
+from switch_core.bridges.collaboration.mattermost import adapter as adapter_module
+from switch_core.bridges.collaboration.mattermost.adapter import (
+ MattermostAdapter,
+ MattermostConnectionConfig,
+)
+from switch_core.bridges.collaboration.mattermost.http_client import NoRedirectClient
+
+
+def _adapter() -> MattermostAdapter:
+ return MattermostAdapter(
+ config=MattermostConnectionConfig(
+ url="http://mm.example",
+ admin_user="admin",
+ admin_password="pw",
+ team_name="team",
+ callback_base_url=None,
+ )
+ )
+
+
+class _Users:
+ def __init__(self, logged_in: threading.Event) -> None:
+ self._logged_in = logged_in
+ self.searches: list[dict[str, Any]] = []
+
+ def get_user(self, user_id: str) -> dict[str, Any]:
+ return {"id": "admin-id"}
+
+ def search_users(self, options: dict[str, Any]) -> list[dict[str, Any]]:
+ assert self._logged_in.is_set(), "searched before logging in"
+ self.searches.append(options)
+ return [{"id": "u1", "username": "ada", "first_name": "Ada", "last_name": "L"}]
+
+
+class _Teams:
+ def get_team_by_name(self, name: str) -> dict[str, Any]:
+ return {"id": "team-id"}
+
+
+class _Driver:
+ """Logs in only once `release` is set, as a slow Mattermost would."""
+
+ def __init__(self) -> None:
+ self.release = threading.Event()
+ self.logged_in = threading.Event()
+ self.users = _Users(self.logged_in)
+ self.teams = _Teams()
+
+ def login(self) -> None:
+ assert self.release.wait(5)
+ self.logged_in.set()
+
+
+async def _connecting(
+ monkeypatch: pytest.MonkeyPatch,
+) -> tuple[MattermostAdapter, _Driver, asyncio.Task[None]]:
+ adapter = _adapter()
+ driver = _Driver()
+ monkeypatch.setattr(adapter, "_create_driver", lambda **_: driver)
+
+ async def nothing() -> None:
+ return None
+
+ monkeypatch.setattr(adapter, "_ensure_admin_bot", nothing)
+ monkeypatch.setattr(adapter, "_start_callbacks", nothing)
+
+ async def ignore(*_: object) -> None:
+ return None
+
+ starting = asyncio.create_task(
+ adapter.start(ignore, ignore, ignore, ignore, ignore)
+ )
+ await asyncio.sleep(0.05)
+ return adapter, driver, starting
+
+
+async def test_a_search_made_while_connecting_waits_and_then_runs_logged_in(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ adapter, driver, starting = await _connecting(monkeypatch)
+ assert adapter._admin_driver is None
+
+ searching = asyncio.create_task(adapter.search_directory_users("ada"))
+ await asyncio.sleep(0.05)
+ assert not searching.done()
+ assert driver.users.searches == []
+
+ driver.release.set()
+ found = await asyncio.wait_for(searching, 5)
+ await starting
+
+ assert [user.username for user in found] == ["ada"]
+ assert driver.users.searches == [
+ {"term": "ada", "team_id": "team-id", "allow_inactive": False}
+ ]
+
+
+async def test_a_search_says_so_when_the_adapter_never_connects(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(adapter_module, "_CONNECT_WAIT_SECONDS", 0.1)
+ adapter, driver, starting = await _connecting(monkeypatch)
+ try:
+ with pytest.raises(RuntimeError, match="not connected yet"):
+ await adapter.search_directory_users("ada")
+ assert driver.users.searches == []
+ finally:
+ driver.release.set()
+ await starting
+
+
+async def test_a_stopped_adapter_is_not_searched_as_connected(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(adapter_module, "_CONNECT_WAIT_SECONDS", 0.1)
+ adapter, driver, starting = await _connecting(monkeypatch)
+ driver.release.set()
+ await starting
+ await adapter.stop()
+ with pytest.raises(RuntimeError, match="not connected yet"):
+ await adapter.search_directory_users("ada")
+
+
+def _client_answering(status: int, monkeypatch: pytest.MonkeyPatch) -> NoRedirectClient:
+ response = requests.Response()
+ response.status_code = status
+ response._content = (
+ b'{"message": "Invalid or expired session, please login again."}'
+ )
+ response.url = "http://mm.example/api/v4/users/search"
+ monkeypatch.setattr(requests, "request", lambda *_args, **_kwargs: response)
+ return NoRedirectClient(
+ {
+ "url": "mm.example",
+ "scheme": "http",
+ "port": 80,
+ "basepath": "/api/v4",
+ "verify": True,
+ "timeout": 5,
+ "request_timeout": 5,
+ "token": None,
+ "login_id": "admin",
+ "password": "pw",
+ "mfa_token": None,
+ "auth": None,
+ "debug": False,
+ }
+ )
+
+
+ ("status", "level"), [(401, logging.WARNING), (403, logging.ERROR)]
+)
+def test_an_expired_session_is_a_warning_and_other_refusals_errors(
+ status: int,
+ level: int,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ client = _client_answering(status, monkeypatch)
+ with caplog.at_level(logging.WARNING), pytest.raises(requests.HTTPError):
+ client.make_request("post", "/users/search", options={"term": "ada"})
+ assert [record.levelno for record in caplog.records] == [level]