refactor: remove unreachable internal code paths
Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com>
This commit is contained in:
1 parent
4212ad726d
commit
9257383bec
21 files changed
+86
-285
No files matched your search
@@ -497,12 +497,12 @@ class DiscordChannel(BaseChannel):
|
||||
self.logger.exception("client startup failed")
|
||||
finally:
|
||||
self._running = False
|
||||
await self._reset_runtime_state(close_client=True)
|
||||
await self._reset_runtime_state()
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the Discord channel."""
|
||||
self._running = False
|
||||
await self._reset_runtime_state(close_client=True)
|
||||
await self._reset_runtime_state()
|
||||
|
||||
def _remember_compaction_notice(
|
||||
self,
|
||||
@@ -907,7 +907,7 @@ class DiscordChannel(BaseChannel):
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
self._working_emoji_tasks.clear()
|
||||
|
||||
async def _reset_runtime_state(self, close_client: bool) -> None:
|
||||
async def _reset_runtime_state(self) -> None:
|
||||
self._running = False
|
||||
# Drain callbacks before clearing the state they can still create after an await.
|
||||
current = asyncio.current_task()
|
||||
@@ -921,7 +921,7 @@ class DiscordChannel(BaseChannel):
|
||||
self._compaction_notices.clear()
|
||||
self._stream_bufs.clear()
|
||||
self._known_channels.clear()
|
||||
if close_client and self._client is not None and not self._client.is_closed():
|
||||
if self._client is not None and not self._client.is_closed():
|
||||
try:
|
||||
await self._client.close()
|
||||
except Exception as e:
|
||||
|
||||
@@ -1850,6 +1850,6 @@ async def test_reset_discards_in_flight_compaction_notices() -> None:
|
||||
owner, client = _client_with_channel(target)
|
||||
await client.send_outbound(_compaction_message("Compressing context…", "started"))
|
||||
|
||||
await owner._reset_runtime_state(close_client=False)
|
||||
await owner._reset_runtime_state()
|
||||
|
||||
assert owner._compaction_notices == {}
|
||||
@@ -142,7 +142,7 @@ class MSTeamsChannel(BaseChannel):
|
||||
self._conversation_refs: dict[str, ConversationRef] = self._load_refs()
|
||||
with self._refs_guard:
|
||||
if self._prune_conversation_refs():
|
||||
self._save_refs_locked(prune=True)
|
||||
self._save_refs_locked()
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Start the Teams webhook listener."""
|
||||
@@ -286,7 +286,7 @@ class MSTeamsChannel(BaseChannel):
|
||||
resp = await self._http.post(base_url, headers=headers, json=payload)
|
||||
resp.raise_for_status()
|
||||
self.logger.info("Message sent to {}", ref.conversation_id)
|
||||
self._touch_conversation_ref(str(msg.chat_id), persist=True)
|
||||
self._touch_conversation_ref(str(msg.chat_id))
|
||||
except Exception:
|
||||
self.logger.exception("Send failed")
|
||||
raise
|
||||
@@ -736,7 +736,7 @@ class MSTeamsChannel(BaseChannel):
|
||||
if disk_ts > mem_ts:
|
||||
self._conversation_refs[key] = disk_ref
|
||||
|
||||
def _touch_conversation_ref(self, chat_id: str, *, persist: bool = False) -> None:
|
||||
def _touch_conversation_ref(self, chat_id: str) -> None:
|
||||
with self._refs_guard:
|
||||
ref = self._conversation_refs.get(str(chat_id))
|
||||
if not ref:
|
||||
@@ -747,8 +747,7 @@ class MSTeamsChannel(BaseChannel):
|
||||
if min_interval > 0 and prev > 0 and now - prev < min_interval:
|
||||
return
|
||||
ref.updated_at = now
|
||||
if persist:
|
||||
self._save_refs_locked()
|
||||
self._save_refs_locked()
|
||||
|
||||
def _write_json_atomically(self, path: Path, data: dict[str, Any]) -> None:
|
||||
payload = json.dumps(data, indent=2)
|
||||
@@ -769,13 +768,12 @@ class MSTeamsChannel(BaseChannel):
|
||||
with suppress(OSError):
|
||||
os.unlink(tmp_path)
|
||||
|
||||
def _save_refs_locked(self, *, prune: bool = True) -> None:
|
||||
def _save_refs_locked(self) -> None:
|
||||
"""Persist conversation references (caller must hold _refs_guard)."""
|
||||
try:
|
||||
with self._refs_file_lock():
|
||||
self._merge_refs_from_disk_locked()
|
||||
if prune:
|
||||
self._prune_conversation_refs()
|
||||
self._prune_conversation_refs()
|
||||
refs_data = {
|
||||
key: {
|
||||
"service_url": ref.service_url,
|
||||
|
||||
@@ -374,9 +374,6 @@ class WebSocketChannel(BaseChannel):
|
||||
session_projection=gateway.session_projection,
|
||||
)
|
||||
self._commands = WebUICommandRouter(self, gateway, outbound=self._outbound)
|
||||
self._webui_request_tasks = self._commands.request_tasks
|
||||
self._webui_request_operations = self._commands.request_operations
|
||||
self._webui_request_locks = self._commands.request_locks
|
||||
|
||||
|
||||
def webui_subscribers(self, chat_id: str) -> tuple[ServerConnection, ...]:
|
||||
|
||||
@@ -421,7 +421,7 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm
|
||||
assert (await preview(owner, str(outside)))["error"]["status"] == 403
|
||||
assert (await preview(owner, str(outside), probe=True))["result"] == {"available": False}
|
||||
assert (await preview(AsyncMock()))["error"]["status"] == 403
|
||||
assert not channel._webui_request_operations
|
||||
assert not channel._commands.request_operations
|
||||
assert {path for path in tmp_path.rglob("*") if path.is_file()} == disk_before
|
||||
assert sessions.list_sessions() == []
|
||||
|
||||
@@ -430,7 +430,7 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm
|
||||
})
|
||||
assert (await preview(owner))["error"]["status"] == 404
|
||||
assert (await preview(owner, metadata=True))["error"]["status"] == 404
|
||||
assert not channel._webui_request_operations
|
||||
assert not channel._commands.request_operations
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1220,7 +1220,7 @@ async def test_authenticated_webui_request_returns_correlated_success(bus: Magic
|
||||
"payload": {"provider": "openrouter", "apiKey": "secret"},
|
||||
},
|
||||
)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
channel.gateway.http.dispatch_webui_mutation.assert_awaited_once_with(
|
||||
conn,
|
||||
@@ -1281,7 +1281,7 @@ async def test_webui_mutations_preserve_request_and_response_order(bus: MagicMoc
|
||||
assert dispatch_order == ["settings.provider.update"]
|
||||
|
||||
release_first.set()
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
assert dispatch_order == [
|
||||
"settings.provider.update",
|
||||
@@ -1350,7 +1350,7 @@ async def test_webui_request_survives_disconnect_and_preserves_reconnect_order(
|
||||
await asyncio.sleep(0)
|
||||
assert dispatch_order == ["automation.run"]
|
||||
|
||||
pending = tuple(channel._webui_request_tasks.values())
|
||||
pending = tuple(channel._commands.request_tasks.values())
|
||||
release.set()
|
||||
await asyncio.gather(*pending)
|
||||
|
||||
@@ -1361,7 +1361,7 @@ async def test_webui_request_survives_disconnect_and_preserves_reconnect_order(
|
||||
"request-queued",
|
||||
"request-next",
|
||||
]
|
||||
assert first_conn not in channel._webui_request_locks
|
||||
assert first_conn not in channel._commands.request_locks
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1381,9 +1381,9 @@ async def test_webui_request_replays_completed_result_after_reconnect(bus: Magic
|
||||
}
|
||||
|
||||
await channel._dispatch_envelope(first_conn, "webui-client", envelope)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
await channel._dispatch_envelope(retry_conn, "webui-client", envelope)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
channel.gateway.http.dispatch_webui_mutation.assert_awaited_once()
|
||||
assert json.loads(retry_conn.send.await_args.args[0]) == {
|
||||
@@ -1416,7 +1416,7 @@ async def test_webui_request_rejects_request_id_reuse_with_different_payload(
|
||||
"payload": {"id": "job-a"},
|
||||
},
|
||||
)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
await channel._dispatch_envelope(
|
||||
retry_conn,
|
||||
"webui-client",
|
||||
@@ -1449,7 +1449,7 @@ def test_webui_request_cache_prunes_expired_completed_but_keeps_pending(
|
||||
channel = _ch(bus)
|
||||
now = 1_000.0
|
||||
monkeypatch.setattr(websocket_module, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
operations = cast(dict[str, Any], channel._webui_request_operations)
|
||||
operations = cast(dict[str, Any], channel._commands.request_operations)
|
||||
operations["pending"] = SimpleNamespace(completed_at=None)
|
||||
operations["expired"] = SimpleNamespace(
|
||||
completed_at=now - websocket_module._WEBUI_REQUEST_CACHE_TTL_S
|
||||
@@ -1472,7 +1472,7 @@ def test_webui_request_cache_prunes_oldest_completed_at_capacity(
|
||||
channel = _ch(bus)
|
||||
now = 1_000.0
|
||||
monkeypatch.setattr(websocket_module, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
operations = cast(dict[str, Any], channel._webui_request_operations)
|
||||
operations = cast(dict[str, Any], channel._commands.request_operations)
|
||||
operations["pending"] = SimpleNamespace(completed_at=None)
|
||||
for index in range(websocket_module._WEBUI_REQUEST_CACHE_MAX + 1):
|
||||
operations[f"completed-{index}"] = SimpleNamespace(
|
||||
@@ -1507,7 +1507,7 @@ async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> N
|
||||
"payload": {},
|
||||
},
|
||||
)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
assert json.loads(conn.send.await_args.args[0]) == {
|
||||
"event": "webui_response",
|
||||
@@ -1570,7 +1570,7 @@ async def test_webui_persists_sidebar_state_larger_than_http_request_line(
|
||||
assert len(json.dumps(envelope).encode()) > 8_192
|
||||
|
||||
await channel._dispatch_envelope(conn, "webui-client", envelope)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
saved = json.loads((tmp_path / "webui" / "sidebar-state.json").read_text(encoding="utf-8"))
|
||||
assert saved["session_order"] == session_order
|
||||
@@ -1624,7 +1624,7 @@ async def test_webui_sidebar_state_update_broadcasts_workbench_to_other_devices(
|
||||
}
|
||||
try:
|
||||
await channel._dispatch_envelope(source, "webui-client", envelope)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
event = json.loads(other_device.send.await_args.args[0])
|
||||
assert event["event"] == "sidebar_state_updated"
|
||||
assert event["state"]["archived_keys"] == ["websocket:b"]
|
||||
|
||||
@@ -339,7 +339,7 @@ async def test_local_reference_inspection_send_recheck_and_no_staging(tmp_path,
|
||||
assert local["kind"] == "video"
|
||||
assert channel.gateway.uploads.store._entries == {}
|
||||
assert not list(channel.gateway.uploads.store.media_dir.glob("*"))
|
||||
assert channel._webui_request_operations == {}
|
||||
assert channel._commands.request_operations == {}
|
||||
|
||||
for invalid in ("missing.mp4", str(workspace), str(tmp_path / "outside.mp4")):
|
||||
failure = await inspect(invalid)
|
||||
|
||||
@@ -670,13 +670,10 @@ class WeixinChannel(BaseChannel):
|
||||
endpoint: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
auth: bool = True,
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
assert self._client is not None
|
||||
url = f"{base_url.rstrip('/')}/{endpoint}"
|
||||
hdrs = self._make_headers(auth=auth)
|
||||
if extra_headers:
|
||||
hdrs.update(extra_headers)
|
||||
return await self._request_json(
|
||||
"GET", url, endpoint=endpoint, params=params, headers=hdrs,
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user