cloudgpu 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,810 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import os
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+ from typing import Callable, Mapping, Optional
12
+
13
+ from cloudgpu.errors import (
14
+ AdapterError,
15
+ AuthFailedError,
16
+ AuthRequiredError,
17
+ TaskNotFoundError,
18
+ TaskRejectedError,
19
+ TaskUncertainError,
20
+ )
21
+ from cloudgpu.gongji_auth import build_headers, load_private_key
22
+ from cloudgpu.models import AdapterCapabilities, GpuOffer
23
+
24
+ Fetch = Callable[[str, str, dict, Optional[dict], float], object]
25
+
26
+ BASE_URL = "https://openapi.suanli.cn"
27
+ PATH = "/api/deployment/resource/search"
28
+ MARKET_URL = "https://www.gongjiyun.com"
29
+ DEFAULT_TOKEN_FILE = Path.home() / ".cloudgpu" / "gongji.token"
30
+ VERSION = "1.0.0"
31
+
32
+
33
+ class GongjiAdapter:
34
+ platform = "gongji"
35
+ BASE_URL = BASE_URL
36
+ PATH = PATH
37
+ MARKET_URL = MARKET_URL
38
+ capabilities = AdapterCapabilities(
39
+ read_only=True,
40
+ region=True,
41
+ price=True,
42
+ total=False,
43
+ )
44
+
45
+ def __init__(
46
+ self,
47
+ token: Optional[str] = None,
48
+ token_env: str = "CLOUDGPU_GONGJI_TOKEN",
49
+ token_file=None,
50
+ timeout: float = 15.0,
51
+ fetch: Optional[Fetch] = None,
52
+ env: Optional[Mapping[str, str]] = None,
53
+ clock=None,
54
+ private_key=None,
55
+ private_key_file=None,
56
+ version: str = VERSION,
57
+ ) -> None:
58
+ self._explicit_token = (token or "").strip()
59
+ self._token_env = token_env
60
+ self._token_file = (
61
+ Path(token_file).expanduser()
62
+ if token_file
63
+ else DEFAULT_TOKEN_FILE
64
+ )
65
+ self.timeout = timeout
66
+ self._fetch = fetch or _http_json
67
+ self._env = os.environ if env is None else env
68
+ self._clock = clock or (lambda: datetime.now(timezone.utc))
69
+ self.version = version
70
+ self._private_key = private_key
71
+ key_path = private_key_file
72
+ if key_path is None:
73
+ key_path = self._env.get(
74
+ "CLOUDGPU_GONGJI_KEY_FILE"
75
+ )
76
+ if key_path is None:
77
+ default_key = Path.home() / ".cloudgpu" / "gongji.key"
78
+ if default_key.exists():
79
+ key_path = default_key
80
+ if self._private_key is None and key_path:
81
+ self._private_key = load_private_key(key_path)
82
+
83
+ def _resolve_token(self) -> str:
84
+ if self._explicit_token:
85
+ return self._explicit_token
86
+
87
+ for name in (self._token_env, "GONGJI_TOKEN"):
88
+ value = (self._env.get(name) or "").strip()
89
+ if value:
90
+ return value
91
+
92
+ path = self._token_file
93
+ if path and path.exists():
94
+ try:
95
+ for line in path.read_text(encoding="utf-8").splitlines():
96
+ value = line.strip()
97
+ if value:
98
+ return value
99
+ except OSError:
100
+ raise AuthRequiredError(
101
+ f"读取 token 文件失败: {path}"
102
+ ) from None
103
+ return ""
104
+
105
+ def require_token(self) -> str:
106
+ token = self._resolve_token()
107
+ if not token:
108
+ raise AuthRequiredError(
109
+ "缺少共绩算力 token。浏览器登录 gongjiyun.com → "
110
+ "头像 → API 密钥 → 简易模式 → 新建,复制 token 后写入 "
111
+ f"{self._token_file}(chmod 600)或设置 "
112
+ f"{self._token_env}"
113
+ )
114
+ return token
115
+
116
+ def _headers(self, path: str, body: str = "{}") -> dict:
117
+ token = self.require_token()
118
+ timestamp = int(self._clock().timestamp() * 1000)
119
+ return build_headers(
120
+ path=path,
121
+ token=token,
122
+ version=self.version,
123
+ timestamp=timestamp,
124
+ body=body,
125
+ private_key=self._private_key,
126
+ )
127
+
128
+ def _request(
129
+ self,
130
+ method: str,
131
+ path: str,
132
+ params=None,
133
+ payload=None,
134
+ ):
135
+ body = (
136
+ "{}"
137
+ if payload is None
138
+ else json.dumps(
139
+ payload,
140
+ ensure_ascii=False,
141
+ separators=(",", ":"),
142
+ )
143
+ )
144
+ sign_path = path
145
+ if method == "GET" and params:
146
+ sign_path = (
147
+ path + "?" + urllib.parse.urlencode(params)
148
+ )
149
+ url = self.BASE_URL + sign_path
150
+ else:
151
+ url = self.BASE_URL + path
152
+ try:
153
+ response = self._fetch(
154
+ method,
155
+ url,
156
+ self._headers(sign_path, body),
157
+ payload,
158
+ self.timeout,
159
+ )
160
+ except AdapterError:
161
+ raise
162
+ except Exception as exc:
163
+ raise AdapterError(
164
+ f"请求共绩失败: {type(exc).__name__}"
165
+ ) from None
166
+ return response
167
+
168
+ def _fetch_resources(self) -> list:
169
+ params = {
170
+ "task_type": "Deployment",
171
+ "device_type": "GpuDevice",
172
+ }
173
+ return _validate_response(
174
+ self._request("GET", self.PATH, params=params)
175
+ )
176
+
177
+ def list_resources(
178
+ self,
179
+ *,
180
+ gpu_model=None,
181
+ region=None,
182
+ min_free: int = 1,
183
+ max_price=None,
184
+ min_vram_gb=None,
185
+ min_ram_gb=None,
186
+ ) -> list:
187
+ if min_free < 0:
188
+ raise ValueError("min_free 不能为负数")
189
+ for name, value in (
190
+ ("max_price", max_price),
191
+ ("min_vram_gb", min_vram_gb),
192
+ ("min_ram_gb", min_ram_gb),
193
+ ):
194
+ if value is not None and value < 0:
195
+ raise ValueError(f"{name} 不能为负数")
196
+
197
+ checked_at = _format_time(self._clock())
198
+ offers = []
199
+ for device in _merge_devices(self._fetch_resources()):
200
+ gpu_name = device.get("gpu_name")
201
+ if not isinstance(gpu_name, str) or not gpu_name:
202
+ raise AdapterError("共绩响应格式异常: gpu_name 非法")
203
+ gpu_count = _as_int(
204
+ device.get("gpu_count"), "gpu_count", gpu_name
205
+ )
206
+ if gpu_count <= 0:
207
+ raise AdapterError(
208
+ f"共绩响应格式异常: {gpu_name}.gpu_count 非法"
209
+ )
210
+ gpu_memory = _as_int(
211
+ device.get("gpu_memory"), "gpu_memory", gpu_name
212
+ )
213
+ cpu_cores = _as_int(
214
+ device.get("cpu_cores", 0), "cpu_cores", gpu_name
215
+ )
216
+ memory = _as_int(
217
+ device.get("memory", 0), "memory", gpu_name
218
+ )
219
+ if gpu_memory < 0 or cpu_cores < 0 or memory < 0:
220
+ raise AdapterError(
221
+ f"共绩响应格式异常: {gpu_name} 资源字段为负"
222
+ )
223
+
224
+ gpu_memory_gb = round(gpu_memory / 1024)
225
+ memory_gb = round(memory / 1024, 1)
226
+ ram_per_gpu_gb = round(memory / 1024 / gpu_count, 1)
227
+ label = (
228
+ f"{gpu_name} x{gpu_count} "
229
+ f"({gpu_memory_gb}G/{cpu_cores}C/{memory_gb:g}G)"
230
+ )
231
+
232
+ regions = device.get("regions")
233
+ if not isinstance(regions, list):
234
+ raise AdapterError(
235
+ f"共绩响应格式异常: {gpu_name}.regions 不是数组"
236
+ )
237
+
238
+ for item in regions:
239
+ if not isinstance(item, dict):
240
+ raise AdapterError(
241
+ f"共绩响应格式异常: {gpu_name} 地区不是对象"
242
+ )
243
+ region_name = item.get("region_name") or item.get(
244
+ "region"
245
+ )
246
+ if not isinstance(region_name, str) or not region_name:
247
+ raise AdapterError(
248
+ f"共绩响应格式异常: {gpu_name} 地区名缺失"
249
+ )
250
+ inventory = _as_int(
251
+ item.get("inventory"), "inventory", region_name
252
+ )
253
+ if inventory < 0:
254
+ raise AdapterError(
255
+ f"共绩响应格式异常: {region_name}.inventory 为负"
256
+ )
257
+ raw_price = item.get("price")
258
+ raw_discount = item.get("discount_price")
259
+ price_value = (
260
+ None
261
+ if raw_price in (None, "")
262
+ else _as_float(
263
+ raw_price, "price", region_name
264
+ )
265
+ )
266
+ discount_value = (
267
+ None
268
+ if raw_discount in (None, "", 0)
269
+ else _as_float(
270
+ raw_discount,
271
+ "discount_price",
272
+ region_name,
273
+ )
274
+ )
275
+ price_raw = (
276
+ discount_value
277
+ if discount_value is not None
278
+ else price_value
279
+ )
280
+ price_per_hour = (
281
+ None
282
+ if price_raw is None
283
+ else price_raw * 3600 / 1000000
284
+ )
285
+ mark = item.get("mark")
286
+ if mark is not None and not isinstance(mark, dict):
287
+ raise AdapterError(
288
+ f"共绩响应格式异常: {region_name}.mark 非法"
289
+ )
290
+
291
+ offer = GpuOffer(
292
+ platform=self.platform,
293
+ service_kind="region",
294
+ gpu_model=label,
295
+ display_name=label,
296
+ description=device.get("device_name") or "",
297
+ gpu_memory_gb=gpu_memory_gb,
298
+ free=inventory,
299
+ total=None,
300
+ region=region_name,
301
+ machine_id=None,
302
+ price_per_hour=price_per_hour,
303
+ charge_type=None,
304
+ url=self.MARKET_URL,
305
+ checked_at=checked_at,
306
+ extra={
307
+ "gpu_count": gpu_count,
308
+ "gpu_memory_mb": gpu_memory,
309
+ "cpu_cores": cpu_cores,
310
+ "memory_mb": memory,
311
+ "memory_gb": memory_gb,
312
+ "ram_per_gpu_gb": ram_per_gpu_gb,
313
+ "region_code": item.get("region"),
314
+ "mark": mark,
315
+ "price_raw": item.get("price"),
316
+ "discount_price_raw": item.get(
317
+ "discount_price"
318
+ ),
319
+ "raw": dict(item),
320
+ },
321
+ )
322
+ if not _matches_filters(
323
+ offer,
324
+ gpu_model=gpu_model,
325
+ region=region,
326
+ min_free=min_free,
327
+ max_price=max_price,
328
+ min_vram_gb=min_vram_gb,
329
+ min_ram_gb=min_ram_gb,
330
+ ):
331
+ continue
332
+ offers.append(offer)
333
+
334
+ offers.sort(
335
+ key=lambda offer: (
336
+ offer.price_per_hour is None,
337
+ offer.price_per_hour or 0,
338
+ offer.gpu_model,
339
+ offer.region or "",
340
+ )
341
+ )
342
+ return offers
343
+
344
+ def list_models(self) -> list:
345
+ offers = self.list_resources(min_free=0)
346
+ models = {}
347
+ for offer in offers:
348
+ entry = models.setdefault(
349
+ offer.gpu_model,
350
+ {"name": offer.gpu_model, "count": 0, "min_price": None},
351
+ )
352
+ entry["count"] += 1
353
+ if offer.price_per_hour is not None and (
354
+ entry["min_price"] is None
355
+ or offer.price_per_hour < entry["min_price"]
356
+ ):
357
+ entry["min_price"] = offer.price_per_hour
358
+ return sorted(models.values(), key=lambda item: item["name"])
359
+
360
+ def list_regions(self) -> list:
361
+ offers = self.list_resources(min_free=0)
362
+ counts = {}
363
+ for offer in offers:
364
+ name = offer.region or "未知"
365
+ counts[name] = counts.get(name, 0) + 1
366
+ return [
367
+ {"name": name, "count": count}
368
+ for name, count in sorted(counts.items())
369
+ ]
370
+
371
+ def list_tasks(
372
+ self,
373
+ *,
374
+ status: str = "Running,Pending,Paused",
375
+ page_size: int = 20,
376
+ max_pages: int = 20,
377
+ ) -> list:
378
+ if not isinstance(status, str) or not status:
379
+ raise ValueError("status 不能为空")
380
+ if page_size < 1 or max_pages < 1:
381
+ raise ValueError("page_size/max_pages 必须大于 0")
382
+ page = 1
383
+ rows = []
384
+ seen = set()
385
+ while True:
386
+ data = _validate_task_data(
387
+ self._request(
388
+ "GET",
389
+ "/api/deployment/task/search",
390
+ params={
391
+ "type": "Deployment",
392
+ "status": status,
393
+ "page": page,
394
+ "page_size": page_size,
395
+ },
396
+ )
397
+ )
398
+ items = data.get("results")
399
+ if not isinstance(items, list):
400
+ raise AdapterError(
401
+ "共绩任务响应异常: results 不是数组"
402
+ )
403
+ for index, item in enumerate(items):
404
+ if not isinstance(item, dict):
405
+ raise AdapterError(
406
+ f"共绩任务响应异常: results[{index}] 不是对象"
407
+ )
408
+ task_id = item.get("task_id")
409
+ if (
410
+ isinstance(task_id, bool)
411
+ or not isinstance(task_id, int)
412
+ or task_id <= 0
413
+ ):
414
+ raise AdapterError(
415
+ f"共绩任务响应异常: task_id 非法"
416
+ )
417
+ if task_id in seen:
418
+ continue
419
+ seen.add(task_id)
420
+ rows.append(dict(item))
421
+ if not items or len(items) < page_size:
422
+ break
423
+ if page >= max_pages:
424
+ raise AdapterError(
425
+ "共绩任务列表分页超过 max_pages"
426
+ )
427
+ page += 1
428
+ return rows
429
+
430
+ def task_detail(self, task_id: int) -> dict:
431
+ _validate_task_id(task_id)
432
+ data = _validate_task_data(
433
+ self._request(
434
+ "GET",
435
+ "/api/deployment/task/detail",
436
+ params={"task_id": task_id},
437
+ )
438
+ )
439
+ if not data:
440
+ raise TaskNotFoundError(
441
+ f"共绩任务不存在: {task_id}"
442
+ )
443
+ return data
444
+
445
+ def create_task(
446
+ self,
447
+ *,
448
+ task_name: str,
449
+ image: str,
450
+ ports,
451
+ mark: str,
452
+ resource: dict,
453
+ env=None,
454
+ command=None,
455
+ args=None,
456
+ ) -> int:
457
+ if not isinstance(task_name, str) or not task_name:
458
+ raise ValueError("task_name 不能为空")
459
+ if not isinstance(image, str) or not image:
460
+ raise ValueError("image 不能为空")
461
+ if not isinstance(mark, str) or not mark:
462
+ raise ValueError("mark 不能为空")
463
+ if not isinstance(resource, dict):
464
+ raise ValueError("resource 必须是对象")
465
+ port_list = [int(port) for port in ports]
466
+ if not port_list or any(
467
+ port <= 0 or port > 65535 for port in port_list
468
+ ):
469
+ raise ValueError("ports 非法")
470
+
471
+ service = {
472
+ "service_name": task_name,
473
+ "service_image": image,
474
+ "remote_ports": [
475
+ {"service_port": port} for port in port_list
476
+ ],
477
+ }
478
+ if env:
479
+ service["env"] = env
480
+ if command is not None or args is not None:
481
+ service["start_script_v2"] = {
482
+ "command": command,
483
+ "args": args or [],
484
+ }
485
+ body = {
486
+ "task_type": "Deployment",
487
+ "task_name": task_name,
488
+ "points": 1,
489
+ "resources": [
490
+ {"mark": mark, "resource": dict(resource)}
491
+ ],
492
+ "services": [service],
493
+ }
494
+ try:
495
+ response = self._request(
496
+ "POST",
497
+ "/api/deployment/task/create",
498
+ payload=body,
499
+ )
500
+ except AdapterError as exc:
501
+ raise TaskUncertainError(str(exc)) from None
502
+ data = _validate_task_data(response, uncertain=True)
503
+ task_id = data.get("task_id") if isinstance(data, dict) else None
504
+ if (
505
+ isinstance(task_id, bool)
506
+ or not isinstance(task_id, int)
507
+ or task_id <= 0
508
+ ):
509
+ raise TaskUncertainError(
510
+ "共绩创建任务响应缺少 task_id"
511
+ )
512
+ return task_id
513
+
514
+ def pause_task(self, task_id: int) -> dict:
515
+ return self._task_action(
516
+ "/api/deployment/task/pause", task_id
517
+ )
518
+
519
+ def recover_task(self, task_id: int) -> dict:
520
+ return self._task_action(
521
+ "/api/deployment/task/recover", task_id
522
+ )
523
+
524
+ def stop_task(self, task_id: int) -> dict:
525
+ return self._task_action(
526
+ "/api/deployment/task/stop", task_id
527
+ )
528
+
529
+ def _task_action(self, path: str, task_id: int) -> dict:
530
+ _validate_task_id(task_id)
531
+ return _validate_task_data(
532
+ self._request(
533
+ "POST", path, payload={"task_id": task_id}
534
+ )
535
+ )
536
+
537
+
538
+ def _validate_task_id(task_id: int) -> None:
539
+ if (
540
+ isinstance(task_id, bool)
541
+ or not isinstance(task_id, int)
542
+ or task_id <= 0
543
+ ):
544
+ raise ValueError("task_id 必须是正整数")
545
+
546
+
547
+ def _validate_task_data(response, uncertain: bool = False) -> dict:
548
+ if not isinstance(response, dict):
549
+ if uncertain:
550
+ raise TaskUncertainError(
551
+ "共绩任务响应不是对象"
552
+ )
553
+ raise AdapterError("共绩任务响应格式异常: 顶层不是对象")
554
+ code = response.get("code")
555
+ code_text = "" if code is None else str(code)
556
+ if code_text not in ("0000", "200"):
557
+ message = str(
558
+ response.get("message") or response.get("msg") or ""
559
+ )
560
+ lower = message.lower()
561
+ if any(
562
+ word in lower
563
+ for word in ("token", "expired", "invalid", "sign", "auth")
564
+ ):
565
+ raise AuthFailedError(
566
+ f"共绩鉴权失败: {message}"
567
+ if message
568
+ else "共绩鉴权失败"
569
+ )
570
+ raise TaskRejectedError(
571
+ f"共绩返回错误 code={code_text}: {message}",
572
+ code=code_text,
573
+ )
574
+ data = response.get("data")
575
+ if data is None:
576
+ return {}
577
+ if not isinstance(data, dict):
578
+ if uncertain:
579
+ raise TaskUncertainError(
580
+ "共绩任务响应 data 不是对象"
581
+ )
582
+ raise AdapterError(
583
+ "共绩任务响应格式异常: data 不是对象"
584
+ )
585
+ return data
586
+
587
+
588
+ def _merge_devices(results) -> list:
589
+ merged = {}
590
+ order = []
591
+ for device in results:
592
+ if not isinstance(device, dict):
593
+ raise AdapterError(
594
+ "共绩响应格式异常: results 条目不是对象"
595
+ )
596
+ regions = device.get("regions")
597
+ if not isinstance(regions, list):
598
+ raise AdapterError(
599
+ "共绩响应格式异常: results.regions 不是数组"
600
+ )
601
+ key = (
602
+ device.get("gpu_name"),
603
+ device.get("gpu_count"),
604
+ device.get("gpu_memory"),
605
+ device.get("cpu_cores", 0),
606
+ device.get("memory", 0),
607
+ )
608
+ if key not in merged:
609
+ copy_device = dict(device)
610
+ copy_device["regions"] = []
611
+ merged[key] = copy_device
612
+ order.append(key)
613
+
614
+ target = merged[key]
615
+ seen = {
616
+ _region_key(region) for region in target["regions"]
617
+ }
618
+ for region in regions:
619
+ if not isinstance(region, dict):
620
+ raise AdapterError(
621
+ "共绩响应格式异常: 地区条目不是对象"
622
+ )
623
+ region_key = _region_key(region)
624
+ if region_key in seen:
625
+ continue
626
+ target["regions"].append(dict(region))
627
+ seen.add(region_key)
628
+ return [merged[key] for key in order]
629
+
630
+
631
+ def _region_key(region: dict):
632
+ mark = region.get("mark")
633
+ mark_value = mark.get("mark") if isinstance(mark, dict) else mark
634
+ return (region.get("region"), mark_value)
635
+
636
+
637
+ def _validate_response(response) -> list:
638
+ if not isinstance(response, dict):
639
+ raise AdapterError("共绩响应格式异常: 顶层不是对象")
640
+ code = response.get("code")
641
+ code_text = "" if code is None else str(code)
642
+ if code_text not in ("0000", "200"):
643
+ message = str(
644
+ response.get("message") or response.get("msg") or ""
645
+ )
646
+ lower = message.lower()
647
+ if any(
648
+ word in lower
649
+ for word in ("token", "expired", "invalid", "sign", "auth")
650
+ ):
651
+ raise AuthFailedError(
652
+ f"共绩鉴权失败: {message}" if message else "共绩鉴权失败"
653
+ )
654
+ raise AdapterError(
655
+ f"共绩返回错误 code={code_text}: {message}"
656
+ )
657
+ data = response.get("data")
658
+ if not isinstance(data, dict):
659
+ raise AdapterError("共绩响应格式异常: data 不是对象")
660
+ results = data.get("results")
661
+ if not isinstance(results, list):
662
+ raise AdapterError("共绩响应格式异常: results 不是数组")
663
+ return results
664
+
665
+
666
+ def _matches_filters(
667
+ offer,
668
+ *,
669
+ gpu_model,
670
+ region,
671
+ min_free,
672
+ max_price,
673
+ min_vram_gb,
674
+ min_ram_gb,
675
+ ) -> bool:
676
+ if gpu_model:
677
+ haystack = f"{offer.gpu_model} {offer.display_name}".casefold()
678
+ if gpu_model.casefold() not in haystack:
679
+ return False
680
+ if region:
681
+ region_code = (offer.extra or {}).get("region_code") or ""
682
+ haystack = f"{offer.region or ''} {region_code}".casefold()
683
+ if region.casefold() not in haystack:
684
+ return False
685
+ if offer.free < min_free:
686
+ return False
687
+ if max_price is not None:
688
+ if (
689
+ offer.price_per_hour is None
690
+ or offer.price_per_hour > max_price
691
+ ):
692
+ return False
693
+ if min_vram_gb is not None:
694
+ if (
695
+ offer.gpu_memory_gb is None
696
+ or offer.gpu_memory_gb < min_vram_gb
697
+ ):
698
+ return False
699
+ if min_ram_gb is not None:
700
+ ram = (offer.extra or {}).get("ram_per_gpu_gb")
701
+ if ram is None or ram < min_ram_gb:
702
+ return False
703
+ return True
704
+
705
+
706
+ def _as_int(value, field: str, context: str) -> int:
707
+ if isinstance(value, bool):
708
+ raise AdapterError(
709
+ f"共绩响应格式异常: {context}.{field} 非法"
710
+ )
711
+ if isinstance(value, int):
712
+ return value
713
+ if isinstance(value, float) and value.is_integer():
714
+ return int(value)
715
+ if isinstance(value, str):
716
+ try:
717
+ number = float(value.strip())
718
+ except ValueError:
719
+ raise AdapterError(
720
+ f"共绩响应格式异常: {context}.{field} 非法"
721
+ ) from None
722
+ if not number.is_integer():
723
+ raise AdapterError(
724
+ f"共绩响应格式异常: {context}.{field} 非法"
725
+ )
726
+ return int(number)
727
+ raise AdapterError(
728
+ f"共绩响应格式异常: {context}.{field} 非法"
729
+ )
730
+
731
+
732
+ def _as_float(value, field: str, context: str) -> float:
733
+ if isinstance(value, bool):
734
+ raise AdapterError(
735
+ f"共绩响应格式异常: {context}.{field} 非法"
736
+ )
737
+ if isinstance(value, (int, float)):
738
+ number = float(value)
739
+ elif isinstance(value, str):
740
+ try:
741
+ number = float(value.strip())
742
+ except ValueError:
743
+ raise AdapterError(
744
+ f"共绩响应格式异常: {context}.{field} 非法"
745
+ ) from None
746
+ else:
747
+ raise AdapterError(
748
+ f"共绩响应格式异常: {context}.{field} 非法"
749
+ )
750
+ if not math.isfinite(number):
751
+ raise AdapterError(
752
+ f"共绩响应格式异常: {context}.{field} 非法"
753
+ )
754
+ return number
755
+
756
+
757
+ def _format_time(value: datetime) -> str:
758
+ if value.tzinfo is None:
759
+ value = value.replace(tzinfo=timezone.utc)
760
+ return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
761
+
762
+
763
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
764
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
765
+ raise AdapterError(
766
+ f"共绩返回重定向 HTTP {code},已拒绝跟随"
767
+ )
768
+
769
+
770
+ def _http_json(
771
+ method: str,
772
+ url: str,
773
+ headers: dict,
774
+ payload: Optional[dict],
775
+ timeout: float,
776
+ ) -> object:
777
+ body = None
778
+ if payload is not None:
779
+ body = json.dumps(
780
+ payload,
781
+ ensure_ascii=False,
782
+ separators=(",", ":"),
783
+ ).encode("utf-8")
784
+
785
+ request = urllib.request.Request(
786
+ url,
787
+ data=body,
788
+ headers=headers,
789
+ method=method,
790
+ )
791
+ opener = urllib.request.build_opener(_NoRedirect)
792
+ try:
793
+ with opener.open(request, timeout=timeout) as response:
794
+ raw = response.read()
795
+ except urllib.error.HTTPError as exc:
796
+ if exc.code in (401, 403):
797
+ raise AuthFailedError("共绩登录态失效或无权访问") from None
798
+ if exc.code == 429:
799
+ raise AdapterError("共绩请求被限流") from None
800
+ raise AdapterError(
801
+ f"请求共绩失败: HTTP {exc.code}"
802
+ ) from None
803
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
804
+ reason = getattr(exc, "reason", None) or type(exc).__name__
805
+ raise AdapterError(f"请求共绩失败: {reason}") from None
806
+
807
+ try:
808
+ return json.loads(raw.decode("utf-8"))
809
+ except (UnicodeDecodeError, json.JSONDecodeError):
810
+ raise AdapterError("共绩响应不是合法 JSON") from None