mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-11-18 09:42:31 +00:00
fix(dingtalk): surface rejection details when delivery fails
A failed group send only reported HTTPStatusError, so an operator had to reproduce the request by hand to learn why DingTalk refused it. Include the status code and the whitelisted error keys from the response body in both the log line and the raised RuntimeError. Only `code`, `message`, and `requestid` are reported: the request body carries the message content and credentials, so an error response that echoes it back must not reach the log. Detail is truncated to 200 chars. Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
4cc9a1c292
commit
19ede6d6ac
2 changed files with 85 additions and 4 deletions
|
|
@ -12,11 +12,38 @@ from reme.steps.file_io._path import gate_md, resolve_path
|
|||
|
||||
_GROUP_SEND_URL = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
|
||||
|
||||
_MAX_ERROR_DETAIL = 200
|
||||
_ERROR_BODY_KEYS = ("code", "message", "requestid")
|
||||
|
||||
|
||||
def _conversation_ids(value: str) -> list[str]:
|
||||
return [item.strip() for item in value.split(",") if item.strip()]
|
||||
|
||||
|
||||
def _failure_detail(exc: Exception) -> str:
|
||||
"""Summarize a delivery failure for logs and response metadata.
|
||||
|
||||
DingTalk reports rejections (an oversized ``msgParam``, say) as an HTTP error whose
|
||||
body carries a machine-readable ``code``; without it the operator only sees
|
||||
``HTTPStatusError`` and has to reproduce the request by hand. Only that whitelist of
|
||||
keys is reported -- the request body holds the message content and credentials, so a
|
||||
DingTalk error that echoes it back must not reach the log.
|
||||
"""
|
||||
if not isinstance(exc, httpx.HTTPStatusError):
|
||||
return f"{type(exc).__name__}: {exc}"[:_MAX_ERROR_DETAIL]
|
||||
response = exc.response
|
||||
detail = f"HTTP {response.status_code}"
|
||||
try:
|
||||
body = response.json()
|
||||
except ValueError:
|
||||
body = None
|
||||
if isinstance(body, dict):
|
||||
for key in _ERROR_BODY_KEYS:
|
||||
if body.get(key):
|
||||
detail += f" {key}={body[key]}"
|
||||
return detail[:_MAX_ERROR_DETAIL]
|
||||
|
||||
|
||||
class DingTalkMarkdownSendStep(BaseStep):
|
||||
"""Send one Markdown document serially to configured DingTalk groups."""
|
||||
|
||||
|
|
@ -105,10 +132,10 @@ class DingTalkMarkdownSendStep(BaseStep):
|
|||
if not isinstance(result, dict) or not result.get("processQueryKey"):
|
||||
raise ValueError("missing processQueryKey")
|
||||
except (httpx.HTTPError, ValueError) as exc:
|
||||
failures.append(f"recipient {index}: {type(exc).__name__}")
|
||||
detail = _failure_detail(exc)
|
||||
failures.append(f"recipient {index}: {detail}")
|
||||
self.logger.warning(
|
||||
f"[{self.name}] DingTalk delivery failed recipient={index}/{len(recipients)} "
|
||||
f"error_type={type(exc).__name__}",
|
||||
f"[{self.name}] DingTalk delivery failed recipient={index}/{len(recipients)} {detail}",
|
||||
)
|
||||
continue
|
||||
self.context.response.metadata["dingtalk_sent_count"] += 1
|
||||
|
|
@ -117,6 +144,9 @@ class DingTalkMarkdownSendStep(BaseStep):
|
|||
sent_count = self.context.response.metadata["dingtalk_sent_count"]
|
||||
if failures:
|
||||
self.context.response.metadata["dingtalk_delivery_errors"] = failures
|
||||
raise RuntimeError(f"DingTalk Markdown delivery failed for {len(failures)} of {len(recipients)} recipients")
|
||||
raise RuntimeError(
|
||||
f"DingTalk Markdown delivery failed for {len(failures)} of {len(recipients)} recipients: "
|
||||
f"{'; '.join(failures)}",
|
||||
)
|
||||
self.logger.info(f"[{self.name}] DingTalk Markdown delivery complete sent={sent_count} total={len(recipients)}")
|
||||
return self.context.response
|
||||
|
|
|
|||
|
|
@ -98,6 +98,57 @@ async def test_markdown_send_without_conversations_is_a_noop(tmp_path):
|
|||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_markdown_send_surfaces_dingtalk_rejection_detail(tmp_path, monkeypatch):
|
||||
report = tmp_path / "daily" / "report.md"
|
||||
report.parent.mkdir()
|
||||
report.write_text(frontmatter.dumps(frontmatter.Post("# Report\n\nBody")), encoding="utf-8")
|
||||
|
||||
async def handler(_request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
400,
|
||||
json={
|
||||
"code": "InvalidmsgParam",
|
||||
"requestid": "01A0B51A-96E1-735D-A1A9-F043A281EC5B",
|
||||
"message": "Specified parameter msgParam is not valid.",
|
||||
},
|
||||
)
|
||||
|
||||
dingtalk_stream = importlib.import_module("dingtalk_stream")
|
||||
monkeypatch.setattr(
|
||||
dingtalk_stream.DingTalkStreamClient,
|
||||
"get_access_token",
|
||||
lambda _client: "access-token",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dingtalk_send.httpx,
|
||||
"AsyncHTTPTransport",
|
||||
lambda **kwargs: httpx.MockTransport(handler),
|
||||
)
|
||||
step = DingTalkMarkdownSendStep(
|
||||
app_context=ApplicationContext(workspace_dir=str(tmp_path)),
|
||||
app_key="app-key",
|
||||
app_secret="app-secret",
|
||||
robot_code="robot-code",
|
||||
conversation_ids="group-one",
|
||||
)
|
||||
step.logger = MagicMock()
|
||||
|
||||
detail = (
|
||||
"HTTP 400 code=InvalidmsgParam"
|
||||
" message=Specified parameter msgParam is not valid."
|
||||
" requestid=01A0B51A-96E1-735D-A1A9-F043A281EC5B"
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="code=InvalidmsgParam"):
|
||||
await step(RuntimeContext(markdown_path="daily/report.md"))
|
||||
|
||||
assert step.context.response.metadata["dingtalk_sent_count"] == 0
|
||||
assert step.context.response.metadata["dingtalk_delivery_errors"] == [f"recipient 1: {detail}"]
|
||||
warnings = "\n".join(call.args[0] for call in step.logger.warning.call_args_list)
|
||||
assert f"recipient=1/1 {detail}" in warnings
|
||||
assert all(value not in warnings for value in ("app-key", "app-secret", "robot-code", "group-one"))
|
||||
|
||||
|
||||
class _AgentWrapper(BaseAgentWrapper):
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue