Merged
fix:worksapce.usage接口5分钟定时请求刷新ASpod老化时间问题 #485
hjh0606Add on 2 days ago
fix:worksapce.usage接口5分钟定时请求刷新ASpod老化时间问题 #485
Merged
Total: 4 files changed+241-6
| @@ -14,6 +14,7 @@ from typing import Any | |||
| 14 | from agent_gateway.enterprise import is_enterprise | 14 | from agent_gateway.enterprise import is_enterprise |
| 15 | from agent_gateway.enterprise.capabilities.workspace.quota import ( | 15 | from agent_gateway.enterprise.capabilities.workspace.quota import ( |
| 16 | disabled_usage_payload, | 16 | disabled_usage_payload, |
| 17 | + get_cached_used_bytes, | ||
| 17 | resolve_quota_snapshot, | 18 | resolve_quota_snapshot, |
| 18 | snapshot_to_dict, | 19 | snapshot_to_dict, |
| 19 | upsert_usage_cache, | 20 | upsert_usage_cache, |
| @@ -451,6 +452,18 @@ def _local_download_payload(params: dict[str, Any], relative_path: Any) -> dict[ | |||
| 451 | } | 452 | } |
| 452 | 453 | ||
| 453 | 454 | ||
| 455 | +def _force_refresh_requested(params: dict[str, Any] | None) -> bool: | ||
| 456 | + """``force_refresh`` 是否要求绕过缓存重测用量。""" | ||
| 457 | + if not isinstance(params, dict): | ||
| 458 | + return False | ||
| 459 | + raw = params.get("force_refresh") | ||
| 460 | + if raw is True or raw == 1: | ||
| 461 | + return True | ||
| 462 | + if isinstance(raw, str) and raw.strip().lower() in {"1", "true", "yes", "on"}: | ||
| 463 | + return True | ||
| 464 | + return False | ||
| 465 | + | ||
| 466 | + | ||
| 454 | def _local_usage_bytes(params: dict[str, Any]) -> int: | 467 | def _local_usage_bytes(params: dict[str, Any]) -> int: |
| 455 | """同步用量读取(含可能的 du);须在 worker 线程调用。""" | 468 | """同步用量读取(含可能的 du);须在 worker 线程调用。""" |
| 456 | ( | 469 | ( |
| @@ -463,11 +476,7 @@ def _local_usage_bytes(params: dict[str, Any]) -> int: | |||
| 463 | ) = _import_local_workspace() | 476 | ) = _import_local_workspace() |
| 464 | svc = _local_service(params) | 477 | svc = _local_service(params) |
| 465 | uid, gid, bid, _aid = _identity_from_params(params) | 478 | uid, gid, bid, _aid = _identity_from_params(params) |
| 466 | - raw = params.get("force_refresh") | 479 | + if _force_refresh_requested(params): |
| 467 | - force = raw is True or raw == 1 | ||
| 468 | - if isinstance(raw, str) and raw.strip().lower() in {"1", "true", "yes", "on"}: | ||
| 469 | - force = True | ||
| 470 | - if force: | ||
| 471 | return measure_and_cache( | 480 | return measure_and_cache( |
| 472 | svc.tenant_root, user_id=uid, group_id=gid, bot_id=bid | 481 | svc.tenant_root, user_id=uid, group_id=gid, bot_id=bid |
| 473 | ) | 482 | ) |
| @@ -625,7 +634,7 @@ def register_workspace_web_methods(channel: Any, *, agent_client: Any) -> None: | |||
| 625 | async def _usage(ws, req_id, params, session_id, user_id=None): | 634 | async def _usage(ws, req_id, params, session_id, user_id=None): |
| 626 | p = dict(params) if isinstance(params, dict) else {} | 635 | p = dict(params) if isinstance(params, dict) else {} |
| 627 | try: | 636 | try: |
| 628 | - uid, gid, bid, _aid = _bind_trusted_identity(ws, p, user_id=user_id) | 637 | + uid, gid, bid, aid = _bind_trusted_identity(ws, p, user_id=user_id) |
| 629 | except WorkspaceIdentityError as exc: | 638 | except WorkspaceIdentityError as exc: |
| 630 | await _reject_identity(channel, ws, req_id, exc) | 639 | await _reject_identity(channel, ws, req_id, exc) |
| 631 | return | 640 | return |
| @@ -639,7 +648,31 @@ def register_workspace_web_methods(channel: Any, *, agent_client: Any) -> None: | |||
| 639 | ) | 648 | ) |
| 640 | return | 649 | return |
| 641 | try: | 650 | try: |
| 651 | + force_refresh = _force_refresh_requested(p) | ||
| 642 | if not _use_local_workspace(): | 652 | if not _use_local_workspace(): |
| 653 | + # 企业版:定时横幅轮询默认读 Gateway 缓存,避免 route/touch 干扰 | ||
| 654 | + # Pod 空闲回收;仅 force_refresh 或缓存未命中时才 forward AS。 | ||
| 655 | + if not force_refresh: | ||
| 656 | + cached = await get_cached_used_bytes( | ||
| 657 | + user_id=uid, group_id=gid, bot_id=bid, | ||
| 658 | + ) | ||
| 659 | + if cached is not None: | ||
| 660 | + snap = await resolve_quota_snapshot( | ||
| 661 | + cached, | ||
| 662 | + user_id=uid, | ||
| 663 | + group_id=gid, | ||
| 664 | + bot_id=bid, | ||
| 665 | + agent_id=aid, | ||
| 666 | + ) | ||
| 667 | + out = snapshot_to_dict( | ||
| 668 | + snap, | ||
| 669 | + user_id=uid, | ||
| 670 | + group_id=gid, | ||
| 671 | + bot_id=bid, | ||
| 672 | + agent_id=aid, | ||
| 673 | + ) | ||
| 674 | + await channel.send_response(ws, req_id, ok=True, payload=out) | ||
| 675 | + return | ||
| 643 | ok, payload, err, code = await _forward_to_agent( | 676 | ok, payload, err, code = await _forward_to_agent( |
| 644 | _fwd( | 677 | _fwd( |
| 645 | ws=ws, | 678 | ws=ws, |
| @@ -11,6 +11,7 @@ from agent_gateway.enterprise.capabilities.workspace.quota import ( | |||
| 11 | compute_quota_status, | 11 | compute_quota_status, |
| 12 | disabled_usage_payload, | 12 | disabled_usage_payload, |
| 13 | fallback_limit_bytes, | 13 | fallback_limit_bytes, |
| 14 | + get_cached_used_bytes, | ||
| 14 | list_enabled_policies, | 15 | list_enabled_policies, |
| 15 | pick_policy, | 16 | pick_policy, |
| 16 | resolve_quota_snapshot, | 17 | resolve_quota_snapshot, |
| @@ -25,6 +26,7 @@ __all__ = [ | |||
| 25 | "compute_quota_status", | 26 | "compute_quota_status", |
| 26 | "disabled_usage_payload", | 27 | "disabled_usage_payload", |
| 27 | "fallback_limit_bytes", | 28 | "fallback_limit_bytes", |
| 29 | + "get_cached_used_bytes", | ||
| 28 | "list_enabled_policies", | 30 | "list_enabled_policies", |
| 29 | "pick_policy", | 31 | "pick_policy", |
| 30 | "resolve_quota_snapshot", | 32 | "resolve_quota_snapshot", |
| @@ -284,6 +284,46 @@ async def resolve_quota_snapshot( | |||
| 284 | ) | 284 | ) |
| 285 | 285 | ||
| 286 | 286 | ||
| 287 | +async def get_cached_used_bytes( | ||
| 288 | + *, | ||
| 289 | + user_id: str, | ||
| 290 | + group_id: str, | ||
| 291 | + bot_id: str, | ||
| 292 | +) -> int | None: | ||
| 293 | + """读 Gateway ``workspace_quota_usage`` 缓存;无行 / 未装配 / 非法值返回 ``None``。 | ||
| 294 | + | ||
| 295 | + 供企业版 ``workspace.usage`` 轮询走缓存,避免每次 forward 到 AS 触发 | ||
| 296 | + Runtime ``route``/``touch``、干扰空闲 Pod 的 ``pod_ttl`` 计时。 | ||
| 297 | + """ | ||
| 298 | + try: | ||
| 299 | + from agent_gateway.config.enterprise.access import ( | ||
| 300 | + get_enterprise_record_repository, | ||
| 301 | + ) | ||
| 302 | + except Exception: # noqa: BLE001 | ||
| 303 | + return None | ||
| 304 | + repo = get_enterprise_record_repository("workspace_quota_usage") | ||
| 305 | + if repo is None: | ||
| 306 | + return None | ||
| 307 | + | ||
| 308 | + uid = str(user_id or "").strip() | ||
| 309 | + gid = str(group_id or "").strip() | ||
| 310 | + bid = str(bot_id or "").strip() | ||
| 311 | + if not uid or not bid: | ||
| 312 | + return None | ||
| 313 | + key = {"user_id": uid, "group_id": gid, "bot_id": bid} | ||
| 314 | + try: | ||
| 315 | + existing = await repo.get(key) | ||
| 316 | + except Exception as exc: # noqa: BLE001 | ||
| 317 | + logger.warning("[workspace.usage] read cache failed: %s", exc) | ||
| 318 | + return None | ||
| 319 | + if not isinstance(existing, dict): | ||
| 320 | + return None | ||
| 321 | + raw = existing.get("used_bytes") | ||
| 322 | + if isinstance(raw, bool) or not isinstance(raw, int) or raw < 0: | ||
| 323 | + return None | ||
| 324 | + return raw | ||
| 325 | + | ||
| 326 | + | ||
| 287 | async def upsert_usage_cache( | 327 | async def upsert_usage_cache( |
| 288 | *, | 328 | *, |
| 289 | user_id: str, | 329 | user_id: str, |
| @@ -0,0 +1,160 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | + | ||
| 3 | +"""workspace.usage 企业版缓存优先:轮询不 forward AS / force_refresh 才测盘。""" | ||
| 4 | + | ||
| 5 | +from __future__ import annotations | ||
| 6 | + | ||
| 7 | +from types import SimpleNamespace | ||
| 8 | +from unittest.mock import AsyncMock | ||
| 9 | + | ||
| 10 | +import pytest | ||
| 11 | + | ||
| 12 | +from agent_gateway.channel_manager.web.web_method_register import workspace as ws_mod | ||
| 13 | +from agent_gateway.enterprise.capabilities.workspace import quota as quota_mod | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +@pytest.mark.parametrize( | ||
| 17 | + ("params", "expected"), | ||
| 18 | + [ | ||
| 19 | + ({}, False), | ||
| 20 | + ({"force_refresh": True}, True), | ||
| 21 | + ({"force_refresh": 1}, True), | ||
| 22 | + ({"force_refresh": "true"}, True), | ||
| 23 | + ({"force_refresh": "yes"}, True), | ||
| 24 | + ({"force_refresh": "0"}, False), | ||
| 25 | + ({"force_refresh": False}, False), | ||
| 26 | + (None, False), | ||
| 27 | + ], | ||
| 28 | +) | ||
| 29 | +def test_force_refresh_requested(params, expected): | ||
| 30 | + assert ws_mod._force_refresh_requested(params) is expected | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +@pytest.mark.asyncio | ||
| 34 | +async def test_get_cached_used_bytes_returns_row(monkeypatch): | ||
| 35 | + import agent_gateway.config.enterprise.access as access | ||
| 36 | + | ||
| 37 | + repo = SimpleNamespace( | ||
| 38 | + get=AsyncMock(return_value={"used_bytes": 32681984, "user_id": "u"}), | ||
| 39 | + ) | ||
| 40 | + monkeypatch.setattr( | ||
| 41 | + access, | ||
| 42 | + "get_enterprise_record_repository", | ||
| 43 | + lambda _name: repo, | ||
| 44 | + ) | ||
| 45 | + | ||
| 46 | + used = await quota_mod.get_cached_used_bytes( | ||
| 47 | + user_id="u", group_id="g", bot_id="b", | ||
| 48 | + ) | ||
| 49 | + assert used == 32681984 | ||
| 50 | + repo.get.assert_awaited_once_with( | ||
| 51 | + {"user_id": "u", "group_id": "g", "bot_id": "b"}, | ||
| 52 | + ) | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +@pytest.mark.asyncio | ||
| 56 | +async def test_get_cached_used_bytes_miss(monkeypatch): | ||
| 57 | + import agent_gateway.config.enterprise.access as access | ||
| 58 | + | ||
| 59 | + repo = SimpleNamespace(get=AsyncMock(return_value=None)) | ||
| 60 | + monkeypatch.setattr( | ||
| 61 | + access, | ||
| 62 | + "get_enterprise_record_repository", | ||
| 63 | + lambda _name: repo, | ||
| 64 | + ) | ||
| 65 | + assert ( | ||
| 66 | + await quota_mod.get_cached_used_bytes(user_id="u", group_id="g", bot_id="b") | ||
| 67 | + ) is None | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +@pytest.mark.asyncio | ||
| 71 | +async def test_get_cached_used_bytes_rejects_invalid(monkeypatch): | ||
| 72 | + import agent_gateway.config.enterprise.access as access | ||
| 73 | + | ||
| 74 | + repo = SimpleNamespace(get=AsyncMock(return_value={"used_bytes": -1})) | ||
| 75 | + monkeypatch.setattr( | ||
| 76 | + access, | ||
| 77 | + "get_enterprise_record_repository", | ||
| 78 | + lambda _name: repo, | ||
| 79 | + ) | ||
| 80 | + assert ( | ||
| 81 | + await quota_mod.get_cached_used_bytes(user_id="u", group_id="g", bot_id="b") | ||
| 82 | + ) is None | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +@pytest.mark.asyncio | ||
| 86 | +async def test_enterprise_usage_serves_cache_without_forward(monkeypatch): | ||
| 87 | + """有缓存且无 force_refresh 时,企业版 usage 不得 forward 到 AS。""" | ||
| 88 | + forwarded: list[object] = [] | ||
| 89 | + | ||
| 90 | + async def boom_forward(*_a, **_k): | ||
| 91 | + forwarded.append(1) | ||
| 92 | + raise AssertionError("must not forward when cache hits") | ||
| 93 | + | ||
| 94 | + monkeypatch.setattr(ws_mod, "_use_local_workspace", lambda: False) | ||
| 95 | + monkeypatch.setattr(ws_mod, "is_workspace_quota_enabled", lambda: True) | ||
| 96 | + monkeypatch.setattr(ws_mod, "_forward_to_agent", boom_forward) | ||
| 97 | + monkeypatch.setattr( | ||
| 98 | + ws_mod, | ||
| 99 | + "get_cached_used_bytes", | ||
| 100 | + AsyncMock(return_value=32681984), | ||
| 101 | + ) | ||
| 102 | + monkeypatch.setattr( | ||
| 103 | + ws_mod, | ||
| 104 | + "resolve_quota_snapshot", | ||
| 105 | + AsyncMock( | ||
| 106 | + return_value=SimpleNamespace( | ||
| 107 | + used_bytes=32681984, | ||
| 108 | + limit_bytes=10 * 1024**4, | ||
| 109 | + percent=0.0003, | ||
| 110 | + status="ok", | ||
| 111 | + source_policy_id="local_default", | ||
| 112 | + unlimited=False, | ||
| 113 | + ) | ||
| 114 | + ), | ||
| 115 | + ) | ||
| 116 | + monkeypatch.setattr( | ||
| 117 | + ws_mod, | ||
| 118 | + "snapshot_to_dict", | ||
| 119 | + lambda snap, **kw: { | ||
| 120 | + "used_bytes": snap.used_bytes, | ||
| 121 | + "limit_bytes": snap.limit_bytes, | ||
| 122 | + "percent": snap.percent, | ||
| 123 | + "status": snap.status, | ||
| 124 | + "source_policy_id": snap.source_policy_id, | ||
| 125 | + "unlimited": snap.unlimited, | ||
| 126 | + "quota_enabled": True, | ||
| 127 | + **kw, | ||
| 128 | + }, | ||
| 129 | + ) | ||
| 130 | + monkeypatch.setattr( | ||
| 131 | + ws_mod, | ||
| 132 | + "_bind_trusted_identity", | ||
| 133 | + lambda *_a, **_k: ("u", "g", "b", ""), | ||
| 134 | + ) | ||
| 135 | + | ||
| 136 | + sent: list[dict] = [] | ||
| 137 | + | ||
| 138 | + async def fake_send_response(_ws, _rid, **kwargs): | ||
| 139 | + sent.append(kwargs) | ||
| 140 | + | ||
| 141 | + handler_box: dict[str, object] = {} | ||
| 142 | + | ||
| 143 | + def capture_register(method, handler): | ||
| 144 | + handler_box[method] = handler | ||
| 145 | + | ||
| 146 | + # register 闭包捕获的是同一个 channel;send_response 必须挂在其上。 | ||
| 147 | + channel = SimpleNamespace( | ||
| 148 | + register_method=capture_register, | ||
| 149 | + send_response=fake_send_response, | ||
| 150 | + ) | ||
| 151 | + ws_mod.register_workspace_web_methods(channel, agent_client=object()) | ||
| 152 | + # ReqMethod.value is the wire method name. | ||
| 153 | + usage = handler_box.get("workspace.usage") or next(iter(handler_box.values())) | ||
| 154 | + assert callable(usage) | ||
| 155 | + await usage(object(), "r1", {"session_id": "s1"}, "s1", user_id="u") | ||
| 156 | + | ||
| 157 | + assert forwarded == [] | ||
| 158 | + assert len(sent) == 1 | ||
| 159 | + assert sent[0]["ok"] is True | ||
| 160 | + assert sent[0]["payload"]["used_bytes"] == 32681984 | ||
🟡 Medium Priority
变更行:quota.py 新增
get_cached_used_bytes(319-324 行)只校验used_bytes类型/非负,完全忽略行内已有的reported_at,也没有任何 TTL 上限;workspace.py 655-675 行据此直接返回。影响链路:改动前企业版每次
workspace.usage都会 forward 到 AS 取实时值;改动后只要workspace_quota_usage里有行就永久返回该行。而该表仅由 Gateway 侧workspace.tree(611)、entries.delete(764/776)、_usage_payload_from_used(534) 写入,workspace.usage轮询本身不再刷新(缓存命中分支跳过了 upsert,也跳过 forward)。失败模式:Agent 在 Pod 内自行写入/清理工作区文件(唯一不经过 Gateway 的路径)后,缓存既不更新也不过期,前端 5 分钟轮询会一直拿到旧值:①旧值偏高(例如已清理但缓存仍是接近上限)→ 响应
status="block"、percent≈100,前端按 block 状态会隐藏/阻断上传入口,用户实际空间充裕却无法上传,直到手动 force_refresh;②旧值偏低 → 接近配额告警/block 完全不提示,用户在写入时被 AS 侧硬拦。该偏差在没有 TTL 的情况下无上限,属于本改动引入的功能性回退(原实现每次都拿实时值)。建议:在
get_cached_used_bytes中增加基于reported_at的新鲜度上限(例如模块常量_CACHE_MAX_AGE_SECONDS,可取 300~900 秒并允许环境变量覆盖):解析existing.get("reported_at"),兼容 naive datetime(视为 UTC),若(_utc_now() - reported_at).total_seconds() > _CACHE_MAX_AGE_SECONDS则返回None,让调用方回落 forward,从而把"读缓存"限定为"仅读较新的缓存",过期后仍能刷新一次真实用量。