-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathclient.py
More file actions
971 lines (817 loc) · 31.7 KB
/
Copy pathclient.py
File metadata and controls
971 lines (817 loc) · 31.7 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
"""
This file is auto generated by the code generation script.
Do not modify this file manually.
Use the `make codegen` command to regenerate.
当前文件为自动生成的控制 API 客户端代码。请勿手动修改此文件。
使用 `make codegen` 命令重新生成。
source: agentrun/sandbox/__client_async_template.py
Sandbox客户端模板 / Sandbox Client Template
此模板用于生成沙箱客户端代码。
This template is used to generate sandbox client code.
"""
import time
from typing import Any, Dict, List, Optional, TYPE_CHECKING
from alibabacloud_agentrun20250910.models import (
CreateTemplateInput,
ListSandboxesRequest,
ListTemplatesRequest,
UpdateTemplateInput,
)
from agentrun.sandbox.api import SandboxControlAPI, SandboxDataAPI
from agentrun.sandbox.model import (
ListSandboxesInput,
ListSandboxesOutput,
NASConfig,
OSSMountConfig,
PageableInput,
PolarFsConfig,
TemplateInput,
)
from agentrun.utils.config import Config
from agentrun.utils.exception import (
AgentRunError,
ClientError,
ResourceNotExistError,
)
from .sandbox import Sandbox
if TYPE_CHECKING:
from agentrun.sandbox.template import Template
class SandboxClient:
"""Sandbox 客户端 / Sandbox Client
用于管理 Sandbox 和 Template。
Used for managing Sandboxes and Templates.
"""
def __init__(self, config: Optional[Config] = None):
"""初始化 Sandbox 客户端 / Initialize Sandbox client
Args:
config: 配置对象,可选 / Configuration object, optional
"""
self.__control_api = SandboxControlAPI(config=config)
self.__sandbox_data_api = SandboxDataAPI(config=config)
async def _wait_template_ready_async(
self,
template_name: str,
config: Optional[Config] = None,
interval_seconds: int = 5,
timeout_seconds: int = 300,
) -> "Template":
"""Wait for Template to be ready (async)
Args:
template_name: Template name
config: Config object
interval_seconds: Polling interval in seconds
timeout_seconds: Timeout in seconds
Returns:
Template: Ready Template object
Raises:
TimeoutError: Timeout error
ClientError: Client error
"""
import asyncio
start_time = time.time()
while True:
template = await self.get_template_async(
template_name, config=config
)
# Check if ready
if template.status == "READY":
return template
# Check if failed
if (
template.status == "CREATE_FAILED"
or template.status == "UPDATE_FAILED"
):
raise AgentRunError(
f"Template {template_name} creation failed, status:"
f" {template.status}"
)
# Check timeout
if time.time() - start_time > timeout_seconds:
raise TimeoutError(
f"Timeout waiting for Template {template_name} to be ready,"
f" current status: {template.status}"
)
await asyncio.sleep(interval_seconds)
def _wait_template_ready(
self,
template_name: str,
config: Optional[Config] = None,
interval_seconds: int = 5,
timeout_seconds: int = 300,
) -> "Template":
"""Wait for Template to be ready (async)
Args:
template_name: Template name
config: Config object
interval_seconds: Polling interval in seconds
timeout_seconds: Timeout in seconds
Returns:
Template: Ready Template object
Raises:
TimeoutError: Timeout error
ClientError: Client error
"""
start_time = time.time()
while True:
template = self.get_template(template_name, config=config)
# Check if ready
if template.status == "READY":
return template
# Check if failed
if (
template.status == "CREATE_FAILED"
or template.status == "UPDATE_FAILED"
):
raise AgentRunError(
f"Template {template_name} creation failed, status:"
f" {template.status}"
)
# Check timeout
if time.time() - start_time > timeout_seconds:
raise TimeoutError(
f"Timeout waiting for Template {template_name} to be ready,"
f" current status: {template.status}"
)
time.sleep(interval_seconds)
async def create_template_async(
self, input: TemplateInput, config: Optional[Config] = None
) -> "Template":
"""创建 Template(异步)
Args:
input: Template 配置
config: 配置对象
Returns:
Template: 创建的 Template 对象
Raises:
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
# 转换为 SDK 需要的格式
sdk_input = CreateTemplateInput().from_map(
input.model_dump(by_alias=True)
)
result = await self.__control_api.create_template_async(
sdk_input, config=config
)
template = Template.from_inner_object(result)
# Poll and wait for Template to be ready
template = await self._wait_template_ready_async(
template.template_name or "", config=config
)
return template
def create_template(
self, input: TemplateInput, config: Optional[Config] = None
) -> "Template":
"""创建 Template(同步)
Args:
input: Template 配置
config: 配置对象
Returns:
Template: 创建的 Template 对象
Raises:
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
# 转换为 SDK 需要的格式
sdk_input = CreateTemplateInput().from_map(
input.model_dump(by_alias=True)
)
result = self.__control_api.create_template(sdk_input, config=config)
template = Template.from_inner_object(result)
# Poll and wait for Template to be ready
template = self._wait_template_ready(
template.template_name or "", config=config
)
return template
async def delete_template_async(
self, template_name: str, config: Optional[Config] = None
) -> "Template":
"""删除 Template(异步)
Args:
template_name: Template 名称
config: 配置对象
Returns:
Template: 删除的 Template 对象
Raises:
ResourceNotExistError: Template 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
try:
result = await self.__control_api.delete_template_async(
template_name, config=config
)
return Template.from_inner_object(result)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Template", template_name) from e
raise e
def delete_template(
self, template_name: str, config: Optional[Config] = None
) -> "Template":
"""删除 Template(同步)
Args:
template_name: Template 名称
config: 配置对象
Returns:
Template: 删除的 Template 对象
Raises:
ResourceNotExistError: Template 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
try:
result = self.__control_api.delete_template(
template_name, config=config
)
return Template.from_inner_object(result)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Template", template_name) from e
raise e
async def update_template_async(
self,
template_name: str,
input: TemplateInput,
config: Optional[Config] = None,
) -> "Template":
"""更新 Template(异步)
Args:
template_name: Template 名称
input: Template 更新配置
config: 配置对象
Returns:
Template: 更新后的 Template 对象
Raises:
ResourceNotExistError: Template 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
try:
# 转换为 SDK 需要的格式
sdk_input = UpdateTemplateInput().from_map(
input.model_dump(by_alias=True, exclude_none=True)
)
result = await self.__control_api.update_template_async(
template_name, sdk_input, config=config
)
return Template.from_inner_object(result)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Template", template_name) from e
raise e
def update_template(
self,
template_name: str,
input: TemplateInput,
config: Optional[Config] = None,
) -> "Template":
"""更新 Template(同步)
Args:
template_name: Template 名称
input: Template 更新配置
config: 配置对象
Returns:
Template: 更新后的 Template 对象
Raises:
ResourceNotExistError: Template 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
try:
# 转换为 SDK 需要的格式
sdk_input = UpdateTemplateInput().from_map(
input.model_dump(by_alias=True, exclude_none=True)
)
result = self.__control_api.update_template(
template_name, sdk_input, config=config
)
return Template.from_inner_object(result)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Template", template_name) from e
raise e
async def get_template_async(
self, template_name: str, config: Optional[Config] = None
) -> "Template":
"""获取 Template(异步)
Args:
template_name: Template 名称
config: 配置对象
Returns:
Template: Template 对象
Raises:
ResourceNotExistError: Template 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
try:
result = await self.__control_api.get_template_async(
template_name, config=config
)
return Template.from_inner_object(result)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Template", template_name) from e
raise e
def get_template(
self, template_name: str, config: Optional[Config] = None
) -> "Template":
"""获取 Template(同步)
Args:
template_name: Template 名称
config: 配置对象
Returns:
Template: Template 对象
Raises:
ResourceNotExistError: Template 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
try:
result = self.__control_api.get_template(
template_name, config=config
)
return Template.from_inner_object(result)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Template", template_name) from e
raise e
async def list_templates_async(
self,
input: Optional[PageableInput] = None,
config: Optional[Config] = None,
) -> List["Template"]:
"""枚举 Templates(异步)
Args:
input: 分页配置
config: 配置对象
Returns:
List[Template]: Template 列表
Raises:
ClientError: 客户端错误
ServerError: 服务器错误
TimeoutError: Timeout waiting for Template to be ready
"""
from agentrun.sandbox.template import Template
if input is None:
input = PageableInput()
# 转换为 SDK 需要的格式
sdk_input = ListTemplatesRequest().from_map(
input.model_dump(by_alias=True)
)
results = await self.__control_api.list_templates_async(
sdk_input, config=config
)
return (
[Template.from_inner_object(item) for item in results.items]
if results.items
else []
)
def list_templates(
self,
input: Optional[PageableInput] = None,
config: Optional[Config] = None,
) -> List["Template"]:
"""枚举 Templates(同步)
Args:
input: 分页配置
config: 配置对象
Returns:
List[Template]: Template 列表
Raises:
ClientError: 客户端错误
ServerError: 服务器错误
TimeoutError: Timeout waiting for Template to be ready
"""
from agentrun.sandbox.template import Template
if input is None:
input = PageableInput()
# 转换为 SDK 需要的格式
sdk_input = ListTemplatesRequest().from_map(
input.model_dump(by_alias=True)
)
results = self.__control_api.list_templates(sdk_input, config=config)
return (
[Template.from_inner_object(item) for item in results.items]
if results.items
else []
)
async def create_sandbox_async(
self,
template_name: str,
sandbox_idle_timeout_seconds: Optional[int] = 600,
sandbox_id: Optional[str] = None,
nas_config: Optional[NASConfig] = None,
oss_mount_config: Optional[OSSMountConfig] = None,
polar_fs_config: Optional[PolarFsConfig] = None,
config: Optional[Config] = None,
) -> Sandbox:
"""创建 Sandbox(异步) / Create Sandbox (async)
Args:
template_name: 模板名称 / Template name
sandbox_idle_timeout_seconds: 沙箱空闲超时时间(秒) / Sandbox idle timeout (seconds)
sandbox_id: 沙箱 ID(可选,用户可指定) / Sandbox ID (optional, user can specify)
nas_config: NAS 配置 / NAS configuration
oss_mount_config: OSS 挂载配置 / OSS mount configuration
polar_fs_config: PolarFS 配置 / PolarFS configuration
config: 配置对象 / Config object
Returns:
Sandbox: 创建的 Sandbox 对象 / Created Sandbox object
Raises:
ClientError: 客户端错误 / Client error
ServerError: 服务器错误 / Server error
"""
# 将配置对象转换为字典格式
nas_config_dict: Optional[Dict[str, Any]] = None
if nas_config is not None:
nas_config_dict = nas_config.model_dump(by_alias=True)
oss_mount_config_dict: Optional[Dict[str, Any]] = None
if oss_mount_config is not None:
oss_mount_config_dict = oss_mount_config.model_dump(by_alias=True)
polar_fs_config_dict: Optional[Dict[str, Any]] = None
if polar_fs_config is not None:
polar_fs_config_dict = polar_fs_config.model_dump(by_alias=True)
result = await self.__sandbox_data_api.create_sandbox_async(
template_name=template_name,
sandbox_idle_timeout_seconds=sandbox_idle_timeout_seconds,
sandbox_id=sandbox_id,
nas_config=nas_config_dict,
oss_mount_config=oss_mount_config_dict,
polar_fs_config=polar_fs_config_dict,
config=config,
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to create sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
def create_sandbox(
self,
template_name: str,
sandbox_idle_timeout_seconds: Optional[int] = 600,
sandbox_id: Optional[str] = None,
nas_config: Optional[NASConfig] = None,
oss_mount_config: Optional[OSSMountConfig] = None,
polar_fs_config: Optional[PolarFsConfig] = None,
config: Optional[Config] = None,
) -> Sandbox:
"""创建 Sandbox(同步) / Create Sandbox (async)
Args:
template_name: 模板名称 / Template name
sandbox_idle_timeout_seconds: 沙箱空闲超时时间(秒) / Sandbox idle timeout (seconds)
sandbox_id: 沙箱 ID(可选,用户可指定) / Sandbox ID (optional, user can specify)
nas_config: NAS 配置 / NAS configuration
oss_mount_config: OSS 挂载配置 / OSS mount configuration
polar_fs_config: PolarFS 配置 / PolarFS configuration
config: 配置对象 / Config object
Returns:
Sandbox: 创建的 Sandbox 对象 / Created Sandbox object
Raises:
ClientError: 客户端错误 / Client error
ServerError: 服务器错误 / Server error
"""
# 将配置对象转换为字典格式
nas_config_dict: Optional[Dict[str, Any]] = None
if nas_config is not None:
nas_config_dict = nas_config.model_dump(by_alias=True)
oss_mount_config_dict: Optional[Dict[str, Any]] = None
if oss_mount_config is not None:
oss_mount_config_dict = oss_mount_config.model_dump(by_alias=True)
polar_fs_config_dict: Optional[Dict[str, Any]] = None
if polar_fs_config is not None:
polar_fs_config_dict = polar_fs_config.model_dump(by_alias=True)
result = self.__sandbox_data_api.create_sandbox(
template_name=template_name,
sandbox_idle_timeout_seconds=sandbox_idle_timeout_seconds,
sandbox_id=sandbox_id,
nas_config=nas_config_dict,
oss_mount_config=oss_mount_config_dict,
polar_fs_config=polar_fs_config_dict,
config=config,
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to create sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
async def stop_sandbox_async(
self, sandbox_id: str, config: Optional[Config] = None
) -> Sandbox:
"""停止 Sandbox(异步)
Args:
sandbox_id: Sandbox ID
config: 配置对象
Returns:
Sandbox: 停止后的 Sandbox 对象
Raises:
ResourceNotExistError: Sandbox 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
try:
result = await self.__sandbox_data_api.stop_sandbox_async(
sandbox_id, config=config
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to stop sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Sandbox", sandbox_id) from e
raise e
def stop_sandbox(
self, sandbox_id: str, config: Optional[Config] = None
) -> Sandbox:
"""停止 Sandbox(同步)
Args:
sandbox_id: Sandbox ID
config: 配置对象
Returns:
Sandbox: 停止后的 Sandbox 对象
Raises:
ResourceNotExistError: Sandbox 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
try:
result = self.__sandbox_data_api.stop_sandbox(
sandbox_id, config=config
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to stop sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Sandbox", sandbox_id) from e
raise e
async def delete_sandbox_async(
self, sandbox_id: str, config: Optional[Config] = None
) -> Sandbox:
"""删除 Sandbox(异步)
Args:
sandbox_id: Sandbox ID
config: 配置对象
Returns:
Sandbox: 停止后的 Sandbox 对象
Raises:
ResourceNotExistError: Sandbox 不存在(包括 HTTP 404 与数据面业务层
not-found 两种情形)。调用方可 catch 此异常实现幂等删除。
Sandbox does not exist (covers both HTTP 404 and data-plane
business-level not-found). Callers can catch this exception
for idempotent delete logic.
ClientError: 客户端错误
ServerError: 服务器错误
"""
try:
result = await self.__sandbox_data_api.delete_sandbox_async(
sandbox_id, config=config
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
message = result.get("message", "")
# 数据面报告 sandbox 不存在时,与 HTTP 404 路径保持一致,
# 统一抛出 ResourceNotExistError,方便调用方幂等处理。
# When the data plane reports sandbox not found, raise
# ResourceNotExistError for consistency with the HTTP 404 path.
# Callers can catch ResourceNotExistError to implement idempotent
# deletion (e.g. when TERMINATED instances still appear in list
# results but have already been removed from the data plane).
# Note: long-term the server should return a stable error_code
# (e.g. SandboxNotFound) so the SDK can match on that instead
# of a message string.
if "sandbox not found" in message.lower():
raise ResourceNotExistError("Sandbox", sandbox_id)
raise ClientError(
status_code=0,
message=(
f"Failed to stop sandbox: {message or 'Unknown error'}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Sandbox", sandbox_id) from e
raise e
def delete_sandbox(
self, sandbox_id: str, config: Optional[Config] = None
) -> Sandbox:
"""删除 Sandbox(同步)
Args:
sandbox_id: Sandbox ID
config: 配置对象
Returns:
Sandbox: 停止后的 Sandbox 对象
Raises:
ResourceNotExistError: Sandbox 不存在(包括 HTTP 404 与数据面业务层
not-found 两种情形)。调用方可 catch 此异常实现幂等删除。
Sandbox does not exist (covers both HTTP 404 and data-plane
business-level not-found). Callers can catch this exception
for idempotent delete logic.
ClientError: 客户端错误
ServerError: 服务器错误
"""
try:
result = self.__sandbox_data_api.delete_sandbox(
sandbox_id, config=config
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
message = result.get("message", "")
# 数据面报告 sandbox 不存在时,与 HTTP 404 路径保持一致,
# 统一抛出 ResourceNotExistError,方便调用方幂等处理。
# When the data plane reports sandbox not found, raise
# ResourceNotExistError for consistency with the HTTP 404 path.
# Callers can catch ResourceNotExistError to implement idempotent
# deletion (e.g. when TERMINATED instances still appear in list
# results but have already been removed from the data plane).
# Note: long-term the server should return a stable error_code
# (e.g. SandboxNotFound) so the SDK can match on that instead
# of a message string.
if "sandbox not found" in message.lower():
raise ResourceNotExistError("Sandbox", sandbox_id)
raise ClientError(
status_code=0,
message=(
f"Failed to stop sandbox: {message or 'Unknown error'}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Sandbox", sandbox_id) from e
raise e
async def get_sandbox_async(
self,
sandbox_id: str,
config: Optional[Config] = None,
) -> Sandbox:
"""获取 Sandbox(异步)
Args:
sandbox_id: Sandbox ID
config: 配置对象
Returns:
Sandbox: Sandbox 对象
Raises:
ResourceNotExistError: Sandbox 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
try:
result = await self.__sandbox_data_api.get_sandbox_async(
sandbox_id, config=config
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to get sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Sandbox", sandbox_id) from e
raise e
def get_sandbox(
self,
sandbox_id: str,
config: Optional[Config] = None,
) -> Sandbox:
"""获取 Sandbox(同步)
Args:
sandbox_id: Sandbox ID
config: 配置对象
Returns:
Sandbox: Sandbox 对象
Raises:
ResourceNotExistError: Sandbox 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
try:
result = self.__sandbox_data_api.get_sandbox(
sandbox_id, config=config
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to get sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Sandbox", sandbox_id) from e
raise e
async def list_sandboxes_async(
self,
input: Optional[ListSandboxesInput] = None,
config: Optional[Config] = None,
) -> ListSandboxesOutput:
"""枚举 Sandboxes(异步)
Args:
input: 分页配置
config: 配置对象
Returns:
List[Sandbox]: Sandbox 列表
Raises:
ClientError: 客户端错误
ServerError: 服务器错误
"""
if input is None:
input = ListSandboxesInput()
# 转换为 SDK 需要的格式
sdk_input = ListSandboxesRequest().from_map(
input.model_dump(by_alias=True)
)
results = await self.__control_api.list_sandboxes_async(
sdk_input, config=config
)
return ListSandboxesOutput(
sandboxes=[
Sandbox.from_inner_object(item) for item in results.items
],
next_token=results.next_token,
)
def list_sandboxes(
self,
input: Optional[ListSandboxesInput] = None,
config: Optional[Config] = None,
) -> ListSandboxesOutput:
"""枚举 Sandboxes(同步)
Args:
input: 分页配置
config: 配置对象
Returns:
List[Sandbox]: Sandbox 列表
Raises:
ClientError: 客户端错误
ServerError: 服务器错误
"""
if input is None:
input = ListSandboxesInput()
# 转换为 SDK 需要的格式
sdk_input = ListSandboxesRequest().from_map(
input.model_dump(by_alias=True)
)
results = self.__control_api.list_sandboxes(sdk_input, config=config)
return ListSandboxesOutput(
sandboxes=[
Sandbox.from_inner_object(item) for item in results.items
],
next_token=results.next_token,
)