-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path_workspace.py
More file actions
246 lines (202 loc) · 8.03 KB
/
_workspace.py
File metadata and controls
246 lines (202 loc) · 8.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""Workspace 名称解析助手 / Workspace Name Resolution Helper
提供 ``workspace_name -> workspace_id`` 的解析能力,供 ``AgentRuntimeClient``
在 ``create`` / ``list`` 等场景下自动转换用户传入的工作空间名称。
The official AgentRun API only accepts ``workspace_id``. The SDK exposes a
convenience field ``workspace_name``; this module wraps ``list_workspaces``
to look the id up by name (exact match, with a simple in-memory cache).
"""
from typing import Dict, List, Optional, Tuple
from alibabacloud_agentrun20250910.models import (
ListWorkspacesRequest,
Workspace,
)
from alibabacloud_tea_openapi.exceptions._client import ClientException
from alibabacloud_tea_openapi.exceptions._server import ServerException
import pydash
from agentrun.utils.config import Config
from agentrun.utils.control_api import ControlAPI
from agentrun.utils.exception import (
ClientError,
ResourceNotExistError,
ServerError,
)
# Cache key 为 (access_key_id, region_id, name),避免不同账号/地域串号。
# Value 为解析得到的 workspace_id。
_RESOLVE_CACHE: Dict[Tuple[str, str, str], str] = {}
# 翻页参数:ListWorkspaces 的 name= 参数在服务端可能是 prefix/fuzzy 匹配,
# 单页 50 条不足以覆盖海量同前缀场景,因此累积所有页再做 exact match。
_PAGE_SIZE = 50
# 安全上限:避免上游异常导致死循环;20 页 × 50 条 = 1000 个候选,
# 同名 / 同前缀 workspace 远超该值的概率极低。
_MAX_PAGES = 20
def _cache_key(cfg: Config, name: str) -> Tuple[str, str, str]:
return (
cfg.get_access_key_id() or "",
cfg.get_region_id() or "",
name,
)
def _pick_exact_match(
workspaces: List[Workspace], name: str
) -> Optional[Workspace]:
matches = [w for w in workspaces if w.name == name]
if len(matches) > 1:
raise ValueError(
f"Workspace name {name!r} is ambiguous: matched"
f" {len(matches)} workspaces; please use workspace_id instead."
)
return matches[0] if matches else None
def _raise_for_tea_exception(e: Exception) -> None:
if isinstance(e, ClientException):
raise ClientError(
e.status_code,
pydash.get(e, "data.message", pydash.get(e, "message", "")),
pydash.get(e, "data.requestId", ""),
pydash.get(e, "data.code", ""),
) from e
if isinstance(e, ServerException):
raise ServerError(
e.status_code,
pydash.get(e, "data.message", pydash.get(e, "message", "")),
pydash.get(e, "data.requestId", ""),
pydash.get(e, "data.code", ""),
) from e
class _WorkspaceResolver(ControlAPI):
"""轻量封装:复用 ControlAPI 拿底层 AgentRun client。"""
def resolve(self, name: str, config: Optional[Config] = None) -> str:
if not name:
raise ValueError("workspace_name must be non-empty")
cfg = Config.with_configs(self.config, config)
cache_key = _cache_key(cfg, name)
if cache_key in _RESOLVE_CACHE:
return _RESOLVE_CACHE[cache_key]
ws = self._lookup_sync(name, config)
if ws is None:
raise ResourceNotExistError("Workspace", name)
assert ws.workspace_id is not None
_RESOLVE_CACHE[cache_key] = ws.workspace_id
return ws.workspace_id
async def resolve_async(
self, name: str, config: Optional[Config] = None
) -> str:
if not name:
raise ValueError("workspace_name must be non-empty")
cfg = Config.with_configs(self.config, config)
cache_key = _cache_key(cfg, name)
if cache_key in _RESOLVE_CACHE:
return _RESOLVE_CACHE[cache_key]
ws = await self._lookup_async(name, config)
if ws is None:
raise ResourceNotExistError("Workspace", name)
assert ws.workspace_id is not None
_RESOLVE_CACHE[cache_key] = ws.workspace_id
return ws.workspace_id
# --- internal -----------------------------------------------------------
def _lookup_sync(
self, name: str, config: Optional[Config] = None
) -> Optional[Workspace]:
client = self._get_client(config)
accumulated: List[Workspace] = []
page_number = 1
try:
while page_number <= _MAX_PAGES:
response = client.list_workspaces(
ListWorkspacesRequest(
name=name,
page_size=str(_PAGE_SIZE),
page_number=str(page_number),
)
)
workspaces = (
getattr(
getattr(response.body, "data", None),
"workspaces",
None,
)
or []
)
if not workspaces:
break
accumulated.extend(workspaces)
if len(workspaces) < _PAGE_SIZE:
break
page_number += 1
except (ClientException, ServerException) as e:
_raise_for_tea_exception(e)
raise
return _pick_exact_match(accumulated, name)
async def _lookup_async(
self, name: str, config: Optional[Config] = None
) -> Optional[Workspace]:
client = self._get_client(config)
accumulated: List[Workspace] = []
page_number = 1
try:
while page_number <= _MAX_PAGES:
response = await client.list_workspaces_async(
ListWorkspacesRequest(
name=name,
page_size=str(_PAGE_SIZE),
page_number=str(page_number),
)
)
workspaces = (
getattr(
getattr(response.body, "data", None),
"workspaces",
None,
)
or []
)
if not workspaces:
break
accumulated.extend(workspaces)
if len(workspaces) < _PAGE_SIZE:
break
page_number += 1
except (ClientException, ServerException) as e:
_raise_for_tea_exception(e)
raise
return _pick_exact_match(accumulated, name)
def resolve_workspace_id_by_name(
name: str, config: Optional[Config] = None
) -> str:
"""同步:根据 workspace name 解析出 workspace_id。
Raises:
ValueError: ``name`` 为空,或在该账号下存在重名 workspace。
ResourceNotExistError: 该账号下未找到同名 workspace。
"""
return _WorkspaceResolver(config).resolve(name, config)
async def resolve_workspace_id_by_name_async(
name: str, config: Optional[Config] = None
) -> str:
"""异步:根据 workspace name 解析出 workspace_id。"""
return await _WorkspaceResolver(config).resolve_async(name, config)
def resolve_workspace_ids_by_names(
names: str, config: Optional[Config] = None
) -> str:
"""同步:将逗号分隔的多个 workspace 名称解析为逗号分隔的 workspace_id 列表。"""
return ",".join(
resolve_workspace_id_by_name(n.strip(), config)
for n in names.split(",")
if n.strip()
)
async def resolve_workspace_ids_by_names_async(
names: str, config: Optional[Config] = None
) -> str:
"""异步:将逗号分隔的多个 workspace 名称解析为逗号分隔的 workspace_id 列表。"""
out: List[str] = []
for n in names.split(","):
n = n.strip()
if not n:
continue
out.append(await resolve_workspace_id_by_name_async(n, config))
return ",".join(out)
def _clear_cache_for_tests() -> None:
"""仅供单测使用:清空内部解析缓存。"""
_RESOLVE_CACHE.clear()
__all__ = [
"resolve_workspace_id_by_name",
"resolve_workspace_id_by_name_async",
"resolve_workspace_ids_by_names",
"resolve_workspace_ids_by_names_async",
]