fix(channels): preserve recovery order and adapter ownership
This commit is contained in:
1 parent
9c1b16b3cc
commit
182ada6825
12 files changed
+191
-29
No files matched your search
@@ -13,6 +13,7 @@ from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, RetryWaitEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -167,6 +168,8 @@ class LinearChannel(BaseChannel):
|
||||
ephemeral=True,
|
||||
)
|
||||
return
|
||||
if self._client is None:
|
||||
raise ChannelNotReadyError("Linear HTTP client is not initialized")
|
||||
body = msg.content
|
||||
if msg.media:
|
||||
attachments = await self._attachment_markdown(msg)
|
||||
|
||||
@@ -37,6 +37,8 @@ from nanobot.channels.contracts import (
|
||||
from nanobot.channels.outbox import RETRY_SECONDS, DeliveryOutbox
|
||||
from nanobot.channels.registry import channel_default_enabled
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.security.workspace_access import WorkspaceScopeResolver
|
||||
from nanobot.security.workspace_policy import resolve_allowed_path
|
||||
from nanobot.utils.restart import (
|
||||
RestartNotice,
|
||||
consume_restart_notice_from_env,
|
||||
@@ -799,6 +801,24 @@ class ChannelManager:
|
||||
if session is None or session.generation != request.session_generation:
|
||||
self._outbox.finish(msg, "failed", "session_replaced")
|
||||
return
|
||||
if msg.media:
|
||||
# An accepted local path can become a symlink during an outage.
|
||||
# Recheck the current source policy before the adapter opens it.
|
||||
scope = WorkspaceScopeResolver(
|
||||
self.config.workspace_path, self.config.tools.restrict_to_workspace,
|
||||
).for_turn(channel=request.session_key.split(":", 1)[0],
|
||||
message_metadata={}, session_metadata=session.metadata)
|
||||
try:
|
||||
for path in msg.media:
|
||||
if not path.startswith(("http://", "https://")):
|
||||
resolve_allowed_path(
|
||||
path, workspace=scope.project_path,
|
||||
allowed_root=scope.project_path if scope.restrict_to_workspace else None,
|
||||
extra_allowed_roots=[self._config_path.parent / "media"],
|
||||
)
|
||||
except (OSError, ValueError):
|
||||
self._outbox.finish(msg, "failed", "attachment_access_denied")
|
||||
return
|
||||
if not self._outbox.claim(msg):
|
||||
return
|
||||
try:
|
||||
|
||||
@@ -19,7 +19,7 @@ from pydantic import Field
|
||||
from websockets.asyncio.client import ClientConnection
|
||||
from websockets.asyncio.client import connect as ws_connect
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
@@ -448,8 +448,7 @@ class NapcatChannel(BaseChannel):
|
||||
|
||||
kind, _, target = msg.chat_id.partition(":")
|
||||
if kind not in ("private", "group") or not target:
|
||||
logger.error("napcat: invalid chat_id '{}'", msg.chat_id)
|
||||
return
|
||||
raise DeliveryRejectedError("napcat: invalid chat_id")
|
||||
|
||||
segments: list[dict[str, Any]] = []
|
||||
for ref in msg.media or []:
|
||||
|
||||
@@ -39,18 +39,24 @@ class DeliveryOutbox:
|
||||
fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o600)
|
||||
os.close(fd)
|
||||
db = sqlite3.connect(self.path)
|
||||
db.execute("PRAGMA secure_delete=ON")
|
||||
db.row_factory = sqlite3.Row
|
||||
try:
|
||||
with db:
|
||||
if not self._initialized:
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS deliveries (
|
||||
id TEXT PRIMARY KEY, run_id TEXT NOT NULL, channel TEXT NOT NULL,
|
||||
chat_id TEXT NOT NULL,
|
||||
payload TEXT, status TEXT NOT NULL, created REAL NOT NULL,
|
||||
updated REAL NOT NULL, next_attempt REAL NOT NULL, error TEXT
|
||||
)""")
|
||||
# A crash during send cannot tell us whether the service accepted it.
|
||||
interrupted = db.execute("SELECT id, run_id, channel FROM deliveries WHERE status='sending'").fetchall()
|
||||
db.execute("""UPDATE deliveries SET status='unknown', payload=NULL,
|
||||
error='interrupted_send', updated=? WHERE status='sending'""", (time.time(),))
|
||||
for row in interrupted:
|
||||
logger.warning("Channel delivery: run={} delivery={} channel={} status=unknown error=interrupted_send",
|
||||
row["run_id"], row["id"], row["channel"])
|
||||
yield db
|
||||
self._initialized = True
|
||||
finally:
|
||||
@@ -79,16 +85,18 @@ class DeliveryOutbox:
|
||||
).fetchone()[0]
|
||||
if count >= MAX_PENDING:
|
||||
raise RuntimeError("Scheduled delivery queue is full; check channel connectivity")
|
||||
db.execute("INSERT INTO deliveries VALUES (?, ?, ?, ?, 'pending', ?, ?, ?, NULL)",
|
||||
(delivery_id, msg.delivery.run_id, msg.channel, payload, now, now, now))
|
||||
db.execute("INSERT INTO deliveries VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?, NULL)",
|
||||
(delivery_id, msg.delivery.run_id, msg.channel, msg.chat_id, payload, now, now, now))
|
||||
msg.delivery_id = delivery_id
|
||||
self._log(msg, "pending")
|
||||
|
||||
@staticmethod
|
||||
def _prune(db: sqlite3.Connection, now: float) -> None:
|
||||
db.execute("""UPDATE deliveries SET status='failed', payload=NULL,
|
||||
expired = db.execute("""UPDATE deliveries SET status='failed', payload=NULL,
|
||||
error='expired', updated=? WHERE status='pending' AND created<=?""",
|
||||
(now, now - MAX_AGE_SECONDS))
|
||||
(now, now - MAX_AGE_SECONDS)).rowcount
|
||||
if expired:
|
||||
logger.warning("{} scheduled deliveries expired; check the instance delivery store", expired)
|
||||
db.execute("DELETE FROM deliveries WHERE status NOT IN ('pending','sending') AND updated<?",
|
||||
(now - RETENTION_SECONDS,))
|
||||
db.execute("""DELETE FROM deliveries WHERE id IN (
|
||||
@@ -116,17 +124,23 @@ class DeliveryOutbox:
|
||||
with self._connect() as db:
|
||||
self._prune(db, now)
|
||||
changed = db.execute("""UPDATE deliveries SET status='sending', updated=?
|
||||
WHERE id=? AND status='pending' AND next_attempt<=?""",
|
||||
WHERE id=? AND status='pending' AND next_attempt<=?
|
||||
AND NOT EXISTS (SELECT 1 FROM deliveries AS older
|
||||
WHERE older.channel=deliveries.channel AND older.chat_id=deliveries.chat_id
|
||||
AND older.rowid<deliveries.rowid AND older.status IN ('pending','sending'))""",
|
||||
(now, msg.delivery_id, now)).rowcount
|
||||
return changed == 1
|
||||
|
||||
def finish(self, msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:
|
||||
now = time.time()
|
||||
with self._connect() as db:
|
||||
db.execute("""UPDATE deliveries SET status=?, error=?, updated=?, next_attempt=?,
|
||||
payload=CASE WHEN ?='pending' THEN payload ELSE NULL END WHERE id=?""",
|
||||
(status, error, now, now + RETRY_SECONDS, status, msg.delivery_id))
|
||||
self._log(msg, status, error)
|
||||
changed = db.execute("""UPDATE deliveries SET status=?, error=?, updated=?, next_attempt=?,
|
||||
payload=CASE WHEN ?='pending' THEN payload ELSE NULL END
|
||||
WHERE id=? AND status IN ('pending','sending')""",
|
||||
(status, error, now, now + RETRY_SECONDS, status, msg.delivery_id)).rowcount
|
||||
self._prune(db, now)
|
||||
if changed:
|
||||
self._log(msg, status, error)
|
||||
|
||||
@staticmethod
|
||||
def _log(msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:
|
||||
|
||||
@@ -17,6 +17,7 @@ from typing import Any, TypedDict, cast
|
||||
import httpx
|
||||
from pydantic import Field, computed_field, field_validator
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -571,6 +572,8 @@ class SignalChannel(BaseChannel):
|
||||
msg.event.notify or self.show_compaction_notices
|
||||
):
|
||||
return
|
||||
if not self._http:
|
||||
raise ChannelNotReadyError("Signal client not connected")
|
||||
is_progress_message = isinstance(msg.event, ProgressEvent)
|
||||
try:
|
||||
plain_text, text_styles = _markdown_to_signal(msg.content)
|
||||
|
||||
@@ -802,7 +802,7 @@ class TelegramChannel(BaseChannel):
|
||||
with suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(self._app_ready.wait(), APP_RESTART_SEND_WAIT_SECONDS)
|
||||
if not self._app_ready.is_set() or self._app is None:
|
||||
raise RuntimeError("Telegram application is restarting; message not delivered")
|
||||
raise ChannelNotReadyError("Telegram application is restarting; message not delivered")
|
||||
return self._app
|
||||
|
||||
def _note_poll_ok(self) -> None:
|
||||
|
||||
@@ -12,6 +12,7 @@ try:
|
||||
except ImportError:
|
||||
pytest.skip("Telegram dependencies not installed (python-telegram-bot)", allow_module_level=True)
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -621,14 +622,15 @@ async def test_send_during_rebuild_fails_instead_of_dropping(monkeypatch) -> Non
|
||||
channel._app = None
|
||||
|
||||
msg = OutboundMessage(channel="telegram", chat_id="123", content="hello")
|
||||
with pytest.raises(RuntimeError, match="restarting"):
|
||||
with pytest.raises(ChannelNotReadyError, match="restarting"):
|
||||
await channel.send(msg)
|
||||
with pytest.raises(RuntimeError, match="restarting"):
|
||||
await channel.send_delta("123", "hello", stream_id="s1")
|
||||
|
||||
# Stopped: nothing to deliver, so stay quiet.
|
||||
# A stopped channel must not report a final message as delivered.
|
||||
channel._running = False
|
||||
await channel.send(msg)
|
||||
with pytest.raises(ChannelNotReadyError, match="not running"):
|
||||
await channel.send(msg)
|
||||
await channel.send_delta("123", "hello", stream_id="s1")
|
||||
|
||||
|
||||
|
||||
@@ -2082,7 +2082,13 @@ class WeixinChannel(BaseChannel):
|
||||
)
|
||||
delivery_state.completed_parts.add(text_part)
|
||||
completed = True
|
||||
except WeixinQuotaError:
|
||||
except WeixinQuotaError as error:
|
||||
if msg.delivery_id is not None:
|
||||
# The durable outbox owns scheduled results. Do not also retain
|
||||
# one in the channel's independently replayed, volatile queue.
|
||||
if not delivery_state.completed_parts:
|
||||
raise ChannelNotReadyError("WeChat needs a fresh inbound context") from error
|
||||
raise
|
||||
if not is_progress:
|
||||
self._defer_outbound(msg)
|
||||
self.logger.warning(
|
||||
|
||||
@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.weixin import runtime as weixin_mod
|
||||
@@ -546,9 +547,7 @@ async def test_send_without_context_token_raises() -> None:
|
||||
channel._send_text = AsyncMock()
|
||||
|
||||
with pytest.raises(RuntimeError, match="context_token missing"):
|
||||
await channel.send(
|
||||
type("Msg", (), {"chat_id": "unknown-user", "content": "pong", "media": [], "metadata": {}})()
|
||||
)
|
||||
await channel.send(_make_outbound_msg(chat_id="unknown-user", content="pong"))
|
||||
|
||||
channel._send_text.assert_not_awaited()
|
||||
|
||||
@@ -1482,6 +1481,26 @@ def _make_outbound_msg(chat_id: str = "wx-user", content: str = "", media: list
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("partial", [False, True])
|
||||
async def test_scheduled_quota_failure_has_only_one_recovery_owner(partial):
|
||||
channel, _bus = _make_channel()
|
||||
channel._client = object()
|
||||
channel._token = "token"
|
||||
channel._refresh_context_token_if_stale = AsyncMock(return_value="context")
|
||||
channel._get_typing_ticket = AsyncMock(return_value="")
|
||||
channel._send_media_part = AsyncMock()
|
||||
channel._send_text = AsyncMock(side_effect=weixin_mod.WeixinQuotaError("sendmessage"))
|
||||
msg = _make_outbound_msg(content="result", media=["image.png"] if partial else [])
|
||||
msg.delivery_id = "scheduled-result"
|
||||
|
||||
expected = weixin_mod.WeixinQuotaError if partial else ChannelNotReadyError
|
||||
with pytest.raises(expected):
|
||||
await channel.send(msg)
|
||||
|
||||
assert channel._deferred_outbound == {}
|
||||
assert channel._send_media_part.await_count == int(partial)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_media_timeout_error_propagates_without_text_fallback() -> None:
|
||||
"""httpx.TimeoutException during media send must re-raise immediately,
|
||||
|
||||
Reference in new issue
Block a user