Skip to content

Self-improving AI Employees for everyone

refactor(plugin): social_provider_registry closes nodes/social→nodes/whatsapp cross-plugin reach (Wave 12 C4 #A)

trohitgd1cc33cfc083
diff --git a/server/nodes/social/_base.py b/server/nodes/social/_base.py
index 25e8c337..8db5cd1c 100644
--- a/server/nodes/social/_base.py
+++ b/server/nodes/social/_base.py
@@ -471,11 +471,23 @@ async def _send_via_whatsapp(
recipient_type: str,
message_type: str
) -> Dict[str, Any]:
- """Route message to WhatsApp via existing handler.
+ """Route message to WhatsApp via the social-provider registry.
- Maps socialSend parameters to whatsappSend parameters.
+ Maps socialSend parameters to whatsappSend parameters, then
+ dispatches through :func:`services.plugin.social_provider_registry.
+ get_social_send_handler`. The whatsapp plugin self-registers as the
+ ``"whatsapp"`` platform from its own ``__init__.py`` — no
+ cross-plugin import from this module.
"""
- from nodes.whatsapp._service import handle_whatsapp_send as whatsapp_send_handler
+ from services.plugin.social_provider_registry import get_social_send_handler
+
+ whatsapp_send_handler = get_social_send_handler("whatsapp")
+ if whatsapp_send_handler is None:
+ raise RuntimeError(
+ "social: 'whatsapp' platform not registered. "
+ "Check that nodes/whatsapp/__init__.py is imported at startup "
+ "and calls register_social_send_handler('whatsapp', ...). "
+ )
# Map socialSend params to whatsappSend format
whatsapp_params = {
diff --git a/server/nodes/whatsapp/__init__.py b/server/nodes/whatsapp/__init__.py
index 206396e6..84a37324 100644
--- a/server/nodes/whatsapp/__init__.py
+++ b/server/nodes/whatsapp/__init__.py
@@ -21,6 +21,7 @@ Two self-registrations happen on package import:
from services._supervisor import register_supervisor
from services.deployment.canary_registry import register_canary_trigger_type
from services.event_waiter import register_filter_builder
+from services.plugin.social_provider_registry import register_social_send_handler
from services.status_broadcaster import register_service_refresh
from services.ws_handler_registry import (
register_option_loader,
@@ -39,6 +40,7 @@ from ._handlers import WS_HANDLERS
from ._option_loaders import load_channels, load_group_members, load_groups
from ._refresh import refresh_whatsapp_status
from ._runtime import WhatsAppRuntime, get_whatsapp_runtime
+from ._service import handle_whatsapp_send
# Supervisor: ensures shutdown_all_supervisors() reaches us.
# get_instance() constructs the singleton once (lazy in spawn, not here).
@@ -74,6 +76,12 @@ register_option_loader("whatsappGroupMembers", load_group_members)
# See services/deployment/canary_registry.py.
register_canary_trigger_type("whatsappReceive")
+# Wave 12 C4 sub-piece A: opt this plugin into the social-provider
+# registry so the social node dispatches by platform identifier
+# instead of cross-importing _service.handle_whatsapp_send. See
+# services/plugin/social_provider_registry.py.
+register_social_send_handler("whatsapp", handle_whatsapp_send)
+
__all__ = [
"WhatsAppRuntime",
"get_whatsapp_runtime",
diff --git a/server/services/plugin/social_provider_registry.py b/server/services/plugin/social_provider_registry.py
new file mode 100644
index 00000000..99fdd345
--- /dev/null
+++ b/server/services/plugin/social_provider_registry.py
@@ -0,0 +1,82 @@
+"""Plugin-owned dispatch registry for the social-messaging facade.
+
+Closes the cross-plugin reach from ``nodes/social/_base.py:478`` —
+``from nodes.whatsapp._service import handle_whatsapp_send`` — which
+made the ``social`` plugin depend on the ``whatsapp`` plugin's
+internals and violated the "framework knows no plugin names" rule.
+
+Each social platform plugin (whatsapp, telegram, slack, discord, …)
+registers a send handler keyed by the platform identifier from its
+own ``__init__.py``. The social node queries the registry instead of
+importing platform internals — same Wave-11.I plugin-self-registration
+pattern as ``register_filter_builder`` / ``register_poll_coroutine_factory``
+/ ``register_ws_handlers`` / ``register_canary_trigger_type``.
+
+Handler signature
+-----------------
+
+::
+
+ handler(params: Dict[str, Any]) -> Awaitable[Dict[str, Any]]
+
+The social node maps its own parameter shape onto the platform's
+expected shape and calls the handler. The handler returns the
+platform's native result dict; the social node passes that through.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Awaitable, Callable, Dict, Optional
+
+from services.plugin.registry import IdempotentRegistry
+
+
+# (params: Dict) -> Awaitable[Dict]
+SocialSendHandler = Callable[[Dict[str, Any]], Awaitable[Dict[str, Any]]]
+
+
+_REGISTRY: IdempotentRegistry[str, SocialSendHandler] = IdempotentRegistry(
+ "social_send_handler"
+)
+
+
+def register_social_send_handler(platform: str, handler: SocialSendHandler) -> None:
+ """Publish a send handler for one social platform.
+
+ Idempotent on re-import (same callable for the same platform key
+ is a no-op). A different callable for an existing platform raises
+ ``ValueError`` to surface plugin namespace collisions at import time.
+
+ Args:
+ platform: Lower-case platform identifier (``"whatsapp"``,
+ ``"telegram"``, …). Matches the value the social node's
+ ``platform`` parameter holds at runtime.
+ handler: Async function accepting platform-specific
+ ``params: Dict`` and returning the platform's native
+ result dict. The social node builds the params dict by
+ mapping its generic shape onto the platform's keys.
+ """
+ _REGISTRY.register(platform, handler)
+
+
+def get_social_send_handler(platform: str) -> Optional[SocialSendHandler]:
+ """Return the handler for ``platform``, or ``None`` if unregistered.
+
+ A ``None`` return surfaces as a clear "unsupported platform" error
+ at the social node call site instead of an ``ImportError`` deep
+ inside the platform's ``_service.py``.
+ """
+ return _REGISTRY.get(platform)
+
+
+def registered_platforms() -> frozenset[str]:
+ """Return an immutable snapshot of registered platform identifiers."""
+ return frozenset(_REGISTRY.keys())
+
+
+__all__ = [
+ "register_social_send_handler",
+ "get_social_send_handler",
+ "registered_platforms",
+ "SocialSendHandler",
+]
diff --git a/server/tests/test_social_provider_registry.py b/server/tests/test_social_provider_registry.py
new file mode 100644
index 00000000..77ad5354
--- /dev/null
+++ b/server/tests/test_social_provider_registry.py
@@ -0,0 +1,173 @@
+"""Wave 12 C4 sub-piece A: social-provider registry contract + invariant.
+
+Locks two layers:
+
+1. **Registry surface**: idempotent registration, retrieval, snapshot.
+
+2. **Architectural invariant**: ``nodes/social/_base.py`` does NOT
+ import ``handle_whatsapp_send`` (or any other plugin's send
+ function) directly. The dispatch must route through
+ :func:`services.plugin.social_provider_registry.get_social_send_handler`.
+ This is the regression catch for the load-bearing cross-plugin reach
+ the migration closed.
+
+Same style as ``test_canary_registry.py`` and
+``test_plugin_self_containment.py`` — source-introspection-driven,
+no live Temporal cluster needed.
+"""
+
+from __future__ import annotations
+
+import inspect
+import re
+import sys
+import types
+from typing import Any, Dict
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+
+if "machina" not in sys.modules:
+ _machina = types.ModuleType("machina")
+ _machina.__path__ = []
+ sys.modules["machina"] = _machina
+ _machina_tcp = types.ModuleType("machina.tcp")
+ _machina_tcp.probe_tcp_port = MagicMock(return_value=False)
+ sys.modules["machina.tcp"] = _machina_tcp
+
+
+def fresh_registry(monkeypatch):
+ """Reset the registry's backing dict so each test runs in isolation.
+
+ The production registry accumulates as plugins import — that's
+ correct for runtime. Scope assertions must isolate from accumulated
+ state so a future plugin opt-in doesn't silently flip outcomes.
+ """
+ from services.plugin import social_provider_registry as reg
+
+ # IdempotentRegistry exposes its backing dict via .items() but the
+ # field is `_items`. monkeypatching the inner dict is the standard
+ # pattern used in other registry tests.
+ fresh = type(reg._REGISTRY)(reg._REGISTRY._name) # type: ignore[attr-defined]
+ monkeypatch.setattr(reg, "_REGISTRY", fresh)
+ return reg
+
+
+class TestRegistryContract:
+ """Surface API: register, query, snapshot."""
+
+ def test_unregistered_platform_returns_none(self, fresh_registry):
+ assert fresh_registry.get_social_send_handler("whatsapp") is None
+
+ @pytest.mark.asyncio
+ async def test_register_then_get_returns_handler(self, fresh_registry):
+ captured = []
+
+ async def fake_handler(params: Dict[str, Any]):
+ captured.append(params)
+ return {"sent": True}
+
+ fresh_registry.register_social_send_handler("whatsapp", fake_handler)
+ handler = fresh_registry.get_social_send_handler("whatsapp")
+
+ assert handler is fake_handler
+ result = await handler({"recipient": "+1234567890"})
+ assert result == {"sent": True}
+ assert captured == [{"recipient": "+1234567890"}]
+
+ def test_idempotent_register_same_callable(self, fresh_registry):
+ async def h(params):
+ return {}
+
+ fresh_registry.register_social_send_handler("whatsapp", h)
+ fresh_registry.register_social_send_handler("whatsapp", h)
+ assert fresh_registry.registered_platforms() == frozenset({"whatsapp"})
+
+ def test_conflicting_register_raises(self, fresh_registry):
+ async def h1(params):
+ return {}
+
+ async def h2(params):
+ return {}
+
+ fresh_registry.register_social_send_handler("whatsapp", h1)
+ with pytest.raises(ValueError, match="already registered"):
+ fresh_registry.register_social_send_handler("whatsapp", h2)
+
+ def test_multiple_platforms_coexist(self, fresh_registry):
+ async def h(params):
+ return {}
+
+ for p in ("whatsapp", "telegram", "slack"):
+ fresh_registry.register_social_send_handler(p, h)
+
+ assert fresh_registry.registered_platforms() == frozenset({
+ "whatsapp", "telegram", "slack",
+ })
+
+
+class TestNoCrossPluginReachInSocialBase:
+ """Architectural invariant: ``nodes/social/_base.py`` must NOT
+ import any plugin's ``_service`` directly. Dispatch goes through
+ ``get_social_send_handler`` from the registry.
+
+ Regression catch: if someone re-introduces the ``from nodes.whatsapp.
+ _service import handle_whatsapp_send`` (or any sibling), this test
+ fails at import-time with a pointer to the registry pattern.
+ """
+
+ _FORBIDDEN_PATTERN = re.compile(
+ r"^\s*from\s+nodes\.\w+\._service\s+import",
+ re.MULTILINE,
+ )
+
+ def test_social_base_does_not_cross_import_service(self):
+ from nodes.social import _base as social_base
+
+ src = inspect.getsource(social_base)
+ match = self._FORBIDDEN_PATTERN.search(src)
+ assert match is None, (
+ f"nodes/social/_base.py contains a cross-plugin _service "
+ f"import (matched at offset {match.start()}):\n "
+ f"{src[match.start():match.end()].strip()}\n"
+ "Route through services.plugin.social_provider_registry."
+ "get_social_send_handler('<platform>') instead. Each platform "
+ "plugin self-registers from its __init__.py."
+ )
+
+ def test_social_base_calls_registry_lookup(self):
+ """The dispatcher must query the registry — not just hide
+ the cross-plugin import behind a runtime import."""
+ from nodes.social import _base as social_base
+
+ src = inspect.getsource(social_base._send_via_whatsapp)
+ assert "get_social_send_handler" in src, (
+ "_send_via_whatsapp must call get_social_send_handler "
+ "from services.plugin.social_provider_registry. Hardcoded "
+ "fallback imports defeat the plugin-self-registration pattern."
+ )
+
+
+class TestWhatsappPluginSelfRegistersAsSocialProvider:
+ """Importing the whatsapp plugin registers it as the 'whatsapp'
+ social send handler.
+ """
+
+ def test_whatsapp_plugin_import_populates_registry(self):
+ from services.plugin import social_provider_registry as reg
+
+ try:
+ __import__("nodes.whatsapp")
+ except ImportError as exc: # pragma: no cover
+ pytest.xfail(f"nodes.whatsapp not importable: {exc}")
+
+ handler = reg.get_social_send_handler("whatsapp")
+ assert handler is not None, (
+ "Importing nodes.whatsapp should call "
+ "register_social_send_handler('whatsapp', handle_whatsapp_send). "
+ "Check the __init__.py bottom section."
+ )
+ # And it should be callable (sanity).
+ assert callable(handler)