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,521 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+ from datetime import datetime, timezone
9
+ from typing import Callable, Optional
10
+
11
+ from cloudgpu.errors import AdapterError
12
+ from cloudgpu.models import AdapterCapabilities, GpuOffer
13
+
14
+ Fetch = Callable[[str, str, dict, Optional[dict], float], object]
15
+
16
+ BASE_URL = "https://matpool.com/api/machines"
17
+ MARKET_URL = "https://matpool.com/host-market/gpu"
18
+ DOMAIN_NAMES = {
19
+ 0: "1区",
20
+ 11: "亚太2区",
21
+ 13: "13区",
22
+ 16: "16区",
23
+ 17: "17区",
24
+ }
25
+
26
+
27
+ class MatpoolAdapter:
28
+ platform = "matpool"
29
+ BASE_URL = BASE_URL
30
+ MARKET_URL = MARKET_URL
31
+ capabilities = AdapterCapabilities(
32
+ read_only=True,
33
+ machine_level=True,
34
+ region=True,
35
+ price=True,
36
+ total=True,
37
+ )
38
+
39
+ def __init__(
40
+ self,
41
+ timeout: float = 15.0,
42
+ fetch: Optional[Fetch] = None,
43
+ clock=None,
44
+ ) -> None:
45
+ self.timeout = timeout
46
+ self._fetch = fetch or _http_json
47
+ self._clock = clock or (lambda: datetime.now(timezone.utc))
48
+
49
+ def list_machines(
50
+ self,
51
+ *,
52
+ gpu_model=None,
53
+ region=None,
54
+ min_free: int = 1,
55
+ max_price=None,
56
+ min_vram_gb=None,
57
+ min_ram_gb=None,
58
+ page_size: int = 100,
59
+ max_pages: int = 20,
60
+ ) -> list:
61
+ if page_size < 1:
62
+ raise ValueError("page_size 必须大于 0")
63
+ if max_pages < 1:
64
+ raise ValueError("max_pages 必须大于 0")
65
+ if min_free < 0:
66
+ raise ValueError("min_free 不能为负数")
67
+ for name, value in (
68
+ ("max_price", max_price),
69
+ ("min_vram_gb", min_vram_gb),
70
+ ("min_ram_gb", min_ram_gb),
71
+ ):
72
+ if value is not None and value < 0:
73
+ raise ValueError(f"{name} 不能为负数")
74
+
75
+ items, total, num_pages = self._fetch_page(1, page_size)
76
+ if num_pages > max_pages:
77
+ raise AdapterError(
78
+ f"矩池云共 {total} 台,分页 {num_pages} 超过上限 {max_pages}"
79
+ )
80
+
81
+ all_items = list(items)
82
+ for page_number in range(2, num_pages + 1):
83
+ next_items, next_total, _ = self._fetch_page(
84
+ page_number, page_size
85
+ )
86
+ if next_total != total:
87
+ raise AdapterError("矩池云分页期间总数发生变化")
88
+ all_items.extend(next_items)
89
+
90
+ if len(all_items) != total:
91
+ raise AdapterError(
92
+ f"矩池云分页结果不完整:预期 {total} 台,实得 "
93
+ f"{len(all_items)} 台"
94
+ )
95
+
96
+ seen = set()
97
+ for item in all_items:
98
+ if not isinstance(item, dict):
99
+ raise AdapterError("矩池云响应格式异常: 机器不是对象")
100
+ agent_id = item.get("agentId")
101
+ if isinstance(agent_id, bool) or not isinstance(
102
+ agent_id, (int, str)
103
+ ):
104
+ raise AdapterError("矩池云响应格式异常: agentId 非法")
105
+ key = str(agent_id)
106
+ if not key:
107
+ raise AdapterError("矩池云响应格式异常: agentId 为空")
108
+ if key in seen:
109
+ raise AdapterError(
110
+ f"矩池云分页出现重复机器 {key}"
111
+ )
112
+ seen.add(key)
113
+
114
+ checked_at = _format_time(self._clock())
115
+ offers = []
116
+ for item in all_items:
117
+ offer = self._machine_offer(item, checked_at)
118
+ if not _matches_filters(
119
+ offer,
120
+ gpu_model=gpu_model,
121
+ region=region,
122
+ min_free=min_free,
123
+ max_price=max_price,
124
+ min_vram_gb=min_vram_gb,
125
+ min_ram_gb=min_ram_gb,
126
+ ):
127
+ continue
128
+ offers.append(offer)
129
+
130
+ offers.sort(
131
+ key=lambda offer: (
132
+ offer.price_per_hour is None,
133
+ offer.price_per_hour or 0,
134
+ offer.gpu_model,
135
+ offer.region or "",
136
+ offer.machine_id or "",
137
+ )
138
+ )
139
+ return offers
140
+
141
+ def _fetch_page(self, page_number: int, page_size: int):
142
+ params = {"page": page_number, "per_page": page_size}
143
+ url = f"{self.BASE_URL}?{urllib.parse.urlencode(params)}"
144
+ headers = {
145
+ "User-Agent": "cloudgpu/0.1",
146
+ "Referer": "https://matpool.com/host-market/gpu",
147
+ "Accept": "application/json",
148
+ }
149
+ try:
150
+ response = self._fetch(
151
+ "GET", url, headers, None, self.timeout
152
+ )
153
+ except AdapterError:
154
+ raise
155
+ except Exception as exc:
156
+ raise AdapterError(
157
+ f"请求矩池云失败: {type(exc).__name__}"
158
+ ) from None
159
+ return _validate_page(response)
160
+
161
+ def _machine_offer(self, item, checked_at: str) -> GpuOffer:
162
+ agent_id = _as_int(item.get("agentId"), "agentId", "machine")
163
+ if "domain" not in item:
164
+ raise AdapterError(
165
+ f"矩池云响应格式异常: {agent_id}.domain 缺失"
166
+ )
167
+ domain = _as_int(
168
+ item.get("domain"), "domain", str(agent_id)
169
+ )
170
+ gpu = item.get("gpu") or {}
171
+ if not isinstance(gpu, dict):
172
+ raise AdapterError(
173
+ f"矩池云响应格式异常: {agent_id}.gpu 非法"
174
+ )
175
+ available = _as_int(
176
+ gpu.get("available"), "gpu.available", str(agent_id)
177
+ )
178
+ total = _as_int(
179
+ gpu.get("total"), "gpu.total", str(agent_id)
180
+ )
181
+ if available < 0 or total < 0 or available > total:
182
+ raise AdapterError(
183
+ f"矩池云响应格式异常: {agent_id}.gpu 数量非法"
184
+ )
185
+
186
+ hardware = item.get("hardware") or {}
187
+ if not isinstance(hardware, dict):
188
+ raise AdapterError(
189
+ f"矩池云响应格式异常: {agent_id}.hardware 非法"
190
+ )
191
+ gpu_info = hardware.get("gpu") or {}
192
+ machine_info = hardware.get("machine") or {}
193
+ if not isinstance(gpu_info, dict) or not isinstance(
194
+ machine_info, dict
195
+ ):
196
+ raise AdapterError(
197
+ f"矩池云响应格式异常: {agent_id}.hardware 子字段非法"
198
+ )
199
+
200
+ gpu_name = gpu_info.get("gpuName")
201
+ if not isinstance(gpu_name, str) or not gpu_name:
202
+ raise AdapterError(
203
+ f"矩池云响应格式异常: {agent_id}.gpuName 非法"
204
+ )
205
+ gpu_ram = _as_int(
206
+ gpu_info.get("gpuRamMB"), "gpuRamMB", gpu_name
207
+ )
208
+ if gpu_ram < 0:
209
+ raise AdapterError(
210
+ f"矩池云响应格式异常: {gpu_name}.gpuRamMB 为负"
211
+ )
212
+
213
+ cpu_name = machine_info.get("cpuName")
214
+ if cpu_name is not None and not isinstance(cpu_name, str):
215
+ raise AdapterError(
216
+ f"矩池云响应格式异常: {agent_id}.cpuName 非法"
217
+ )
218
+ cpu_cores = _as_int(
219
+ machine_info.get("totalCPUCores", 0),
220
+ "totalCPUCores",
221
+ str(agent_id),
222
+ )
223
+ ram_mb = _as_int(
224
+ machine_info.get("ramMB", 0), "ramMB", str(agent_id)
225
+ )
226
+ total_ram = _as_int(
227
+ machine_info.get("totalRAMMB", 0),
228
+ "totalRAMMB",
229
+ str(agent_id),
230
+ )
231
+ disk_gb = _as_int(
232
+ machine_info.get("diskGB", 0), "diskGB", str(agent_id)
233
+ )
234
+ if min(cpu_cores, ram_mb, total_ram, disk_gb) < 0:
235
+ raise AdapterError(
236
+ f"矩池云响应格式异常: {agent_id} 资源字段为负"
237
+ )
238
+
239
+ raw_price = hardware.get("priceMillicent")
240
+ raw_discount = hardware.get("discountPriceMillicent")
241
+ price_value = (
242
+ None
243
+ if raw_price in (None, "")
244
+ else _as_float(raw_price, "priceMillicent", str(agent_id))
245
+ )
246
+ discount_value = (
247
+ None
248
+ if raw_discount in (None, "")
249
+ else _as_float(
250
+ raw_discount,
251
+ "discountPriceMillicent",
252
+ str(agent_id),
253
+ )
254
+ )
255
+ if price_value is not None and price_value < 0:
256
+ raise AdapterError(
257
+ f"矩池云响应格式异常: {agent_id}.priceMillicent 为负"
258
+ )
259
+ if discount_value is not None and discount_value < 0:
260
+ raise AdapterError(
261
+ "矩池云响应格式异常: "
262
+ f"{agent_id}.discountPriceMillicent 为负"
263
+ )
264
+ chosen = (
265
+ discount_value
266
+ if discount_value is not None and discount_value > 0
267
+ else price_value
268
+ )
269
+ price_per_hour = (
270
+ None if chosen is None else chosen / 100000
271
+ )
272
+
273
+ driver = gpu_info.get("driver")
274
+ if driver is not None and not isinstance(driver, str):
275
+ raise AdapterError(
276
+ f"矩池云响应格式异常: {agent_id}.driver 非法"
277
+ )
278
+ max_cuda = gpu_info.get("maxCUDAVer")
279
+ if max_cuda is not None and not isinstance(max_cuda, str):
280
+ raise AdapterError(
281
+ f"矩池云响应格式异常: {agent_id}.maxCUDAVer 非法"
282
+ )
283
+ tflops = gpu_info.get("tflops")
284
+ tflops_value = (
285
+ None
286
+ if tflops is None
287
+ else _as_float(tflops, "tflops", str(agent_id))
288
+ )
289
+
290
+ region = DOMAIN_NAMES.get(domain, f"domain-{domain}")
291
+ ram_per_gpu = round(ram_mb / 1024, 1)
292
+
293
+ return GpuOffer(
294
+ platform=self.platform,
295
+ service_kind="machine",
296
+ gpu_model=gpu_name,
297
+ display_name=gpu_name,
298
+ description=machine_info.get("cpuName") or "",
299
+ gpu_memory_gb=round(gpu_ram / 1024),
300
+ free=available,
301
+ total=total,
302
+ region=region,
303
+ machine_id=str(agent_id),
304
+ price_per_hour=price_per_hour,
305
+ charge_type="payg",
306
+ url=self.MARKET_URL,
307
+ checked_at=checked_at,
308
+ extra={
309
+ "domain": domain,
310
+ "region_code": domain,
311
+ "cpu_name": cpu_name,
312
+ "cpu_cores": cpu_cores,
313
+ "ram_mb": ram_mb,
314
+ "ram_per_gpu_gb": ram_per_gpu,
315
+ "total_ram_mb": total_ram,
316
+ "disk_gb": disk_gb,
317
+ "pcie_ver": machine_info.get("pcieVer"),
318
+ "motherboard": machine_info.get("motherboardName"),
319
+ "driver": driver,
320
+ "max_cuda": max_cuda,
321
+ "tflops": tflops_value,
322
+ "is_proprietary": item.get("isProprietary"),
323
+ "resource_id": item.get("resourceID"),
324
+ "items": item.get("items"),
325
+ "price_millicent": raw_price,
326
+ "discount_price_millicent": raw_discount,
327
+ "raw": dict(item),
328
+ },
329
+ )
330
+
331
+ def list_models(self) -> list:
332
+ offers = self.list_machines(min_free=0)
333
+ models = {}
334
+ for offer in offers:
335
+ entry = models.setdefault(
336
+ offer.gpu_model,
337
+ {"name": offer.gpu_model, "count": 0, "min_price": None},
338
+ )
339
+ entry["count"] += 1
340
+ if offer.price_per_hour is not None and (
341
+ entry["min_price"] is None
342
+ or offer.price_per_hour < entry["min_price"]
343
+ ):
344
+ entry["min_price"] = offer.price_per_hour
345
+ return sorted(models.values(), key=lambda item: item["name"])
346
+
347
+ def list_regions(self) -> list:
348
+ offers = self.list_machines(min_free=0)
349
+ counts = {}
350
+ for offer in offers:
351
+ name = offer.region or "未知"
352
+ counts[name] = counts.get(name, 0) + 1
353
+ return [
354
+ {"name": name, "count": count}
355
+ for name, count in sorted(counts.items())
356
+ ]
357
+
358
+
359
+ def _validate_page(response):
360
+ if not isinstance(response, dict):
361
+ raise AdapterError("矩池云响应格式异常: 顶层不是对象")
362
+ code = response.get("code")
363
+ if isinstance(code, bool) or code != 0:
364
+ raise AdapterError(
365
+ f"矩池云返回错误 code={code!r}: "
366
+ f"{response.get('msg') or ''}"
367
+ )
368
+ pagination = response.get("pagination")
369
+ if not isinstance(pagination, dict):
370
+ raise AdapterError("矩池云响应格式异常: 缺少 pagination")
371
+ total = _as_int(pagination.get("total"), "total", "pagination")
372
+ num_pages = _as_int(
373
+ pagination.get("numPages"), "numPages", "pagination"
374
+ )
375
+ if total < 0 or num_pages < 0:
376
+ raise AdapterError("矩池云响应格式异常: 分页数值为负")
377
+ machines = response.get("machines")
378
+ if not isinstance(machines, list):
379
+ raise AdapterError("矩池云响应格式异常: machines 不是数组")
380
+ return machines, total, num_pages
381
+
382
+
383
+ def _matches_filters(
384
+ offer,
385
+ *,
386
+ gpu_model,
387
+ region,
388
+ min_free,
389
+ max_price,
390
+ min_vram_gb,
391
+ min_ram_gb,
392
+ ) -> bool:
393
+ if gpu_model and gpu_model.casefold() not in offer.gpu_model.casefold():
394
+ return False
395
+ if region:
396
+ extra = offer.extra or {}
397
+ haystack = (
398
+ f"{offer.region or ''} domain-{extra.get('domain')} "
399
+ f"{extra.get('domain')}"
400
+ ).casefold()
401
+ if region.casefold() not in haystack:
402
+ return False
403
+ if offer.free < min_free:
404
+ return False
405
+ if max_price is not None:
406
+ if (
407
+ offer.price_per_hour is None
408
+ or offer.price_per_hour > max_price
409
+ ):
410
+ return False
411
+ if min_vram_gb is not None:
412
+ if (
413
+ offer.gpu_memory_gb is None
414
+ or offer.gpu_memory_gb < min_vram_gb
415
+ ):
416
+ return False
417
+ if min_ram_gb is not None:
418
+ ram = (offer.extra or {}).get("ram_per_gpu_gb")
419
+ if ram is None or ram < min_ram_gb:
420
+ return False
421
+ return True
422
+
423
+
424
+ def _as_int(value, field: str, context: str) -> int:
425
+ if isinstance(value, bool):
426
+ raise AdapterError(
427
+ f"矩池云响应格式异常: {context}.{field} 非法"
428
+ )
429
+ if isinstance(value, int):
430
+ return value
431
+ if isinstance(value, float) and value.is_integer():
432
+ return int(value)
433
+ if isinstance(value, str):
434
+ try:
435
+ number = float(value.strip())
436
+ except ValueError:
437
+ raise AdapterError(
438
+ f"矩池云响应格式异常: {context}.{field} 非法"
439
+ ) from None
440
+ if not number.is_integer():
441
+ raise AdapterError(
442
+ f"矩池云响应格式异常: {context}.{field} 非法"
443
+ )
444
+ return int(number)
445
+ raise AdapterError(
446
+ f"矩池云响应格式异常: {context}.{field} 非法"
447
+ )
448
+
449
+
450
+ def _as_float(value, field: str, context: str) -> float:
451
+ if isinstance(value, bool):
452
+ raise AdapterError(
453
+ f"矩池云响应格式异常: {context}.{field} 非法"
454
+ )
455
+ if isinstance(value, (int, float)):
456
+ number = float(value)
457
+ elif isinstance(value, str):
458
+ try:
459
+ number = float(value.strip())
460
+ except ValueError:
461
+ raise AdapterError(
462
+ f"矩池云响应格式异常: {context}.{field} 非法"
463
+ ) from None
464
+ else:
465
+ raise AdapterError(
466
+ f"矩池云响应格式异常: {context}.{field} 非法"
467
+ )
468
+ if not math.isfinite(number):
469
+ raise AdapterError(
470
+ f"矩池云响应格式异常: {context}.{field} 非法"
471
+ )
472
+ return number
473
+
474
+
475
+ def _format_time(value: datetime) -> str:
476
+ if value.tzinfo is None:
477
+ value = value.replace(tzinfo=timezone.utc)
478
+ return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
479
+
480
+
481
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
482
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
483
+ raise AdapterError(
484
+ f"矩池云返回重定向 HTTP {code},已拒绝跟随"
485
+ )
486
+
487
+
488
+ def _http_json(
489
+ method: str,
490
+ url: str,
491
+ headers: dict,
492
+ payload: Optional[dict],
493
+ timeout: float,
494
+ ) -> object:
495
+ body = None
496
+ if payload is not None:
497
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
498
+ request = urllib.request.Request(
499
+ url,
500
+ data=body,
501
+ headers=headers,
502
+ method=method,
503
+ )
504
+ opener = urllib.request.build_opener(_NoRedirect)
505
+ try:
506
+ with opener.open(request, timeout=timeout) as response:
507
+ raw = response.read()
508
+ except urllib.error.HTTPError as exc:
509
+ if exc.code == 429:
510
+ raise AdapterError("矩池云请求被限流") from None
511
+ raise AdapterError(
512
+ f"请求矩池云失败: HTTP {exc.code}"
513
+ ) from None
514
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
515
+ reason = getattr(exc, "reason", None) or type(exc).__name__
516
+ raise AdapterError(f"请求矩池云失败: {reason}") from None
517
+
518
+ try:
519
+ return json.loads(raw.decode("utf-8"))
520
+ except (UnicodeDecodeError, json.JSONDecodeError):
521
+ raise AdapterError("矩池云响应不是合法 JSON") from None
@@ -0,0 +1,155 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import urllib.error
5
+ import urllib.request
6
+ from datetime import datetime, timezone
7
+ from typing import Callable, Optional
8
+
9
+ from cloudgpu.errors import AdapterError
10
+ from cloudgpu.models import AdapterCapabilities, GpuOffer
11
+
12
+ Fetch = Callable[[str, dict, float], object]
13
+ Clock = Callable[[], datetime]
14
+
15
+ KNOWN_FIELDS = frozenset({"name", "shortName", "description", "gpuMemory", "count"})
16
+
17
+
18
+ class MornAIAdapter:
19
+ """晨涧云(mornai.cn)只读适配器。
20
+
21
+ 接口只提供全平台各型号空闲卡数,没有地区、价格、机器 ID 或总卡数。
22
+ """
23
+
24
+ platform = "mornai"
25
+ BASE_URL = "https://api.mornai.cn/app-api"
26
+ MARKET_URL = "https://www.mornai.cn/store/list"
27
+ KINDS = ("cloud", "container")
28
+ HEADERS = {
29
+ "tenant-id": "1",
30
+ "Referer": "https://www.mornai.cn/",
31
+ "Accept": "application/json",
32
+ "User-Agent": "cloudgpu/0.1",
33
+ }
34
+ capabilities = AdapterCapabilities(read_only=True)
35
+
36
+ def __init__(
37
+ self,
38
+ timeout: float = 15.0,
39
+ fetch: Optional[Fetch] = None,
40
+ clock: Optional[Clock] = None,
41
+ ) -> None:
42
+ self.timeout = timeout
43
+ self._fetch = fetch or _http_get_json
44
+ self._clock = clock or (lambda: datetime.now(timezone.utc))
45
+
46
+ def list_offers(self, *, kind: Optional[str] = None) -> list[GpuOffer]:
47
+ if kind is None:
48
+ kind = "cloud"
49
+ if kind not in self.KINDS:
50
+ raise ValueError(f"不支持的 kind: {kind}")
51
+ url = f"{self.BASE_URL}/{kind}/resource/gpu/count"
52
+ try:
53
+ payload = self._fetch(url, dict(self.HEADERS), self.timeout)
54
+ except AdapterError:
55
+ raise
56
+ except Exception as exc:
57
+ raise AdapterError(f"请求晨涧云失败: {exc}") from exc
58
+
59
+ checked_at = _format_time(self._clock())
60
+ return self._parse(payload, kind, checked_at)
61
+
62
+ def _parse(self, payload: object, kind: str, checked_at: str) -> list[GpuOffer]:
63
+ if not isinstance(payload, dict):
64
+ raise AdapterError("晨涧云响应格式异常: 顶层不是对象")
65
+
66
+ code = payload.get("code")
67
+ if code != 0:
68
+ message = payload.get("msg") or ""
69
+ raise AdapterError(f"晨涧云返回错误 code={code}: {message}")
70
+
71
+ data = payload.get("data")
72
+ if not isinstance(data, list):
73
+ raise AdapterError("晨涧云响应格式异常: data 不是列表")
74
+
75
+ offers = []
76
+ for index, item in enumerate(data):
77
+ if not isinstance(item, dict):
78
+ raise AdapterError(f"晨涧云响应格式异常: data[{index}] 不是对象")
79
+
80
+ name = item.get("name")
81
+ if not isinstance(name, str) or not name:
82
+ raise AdapterError(
83
+ f"晨涧云响应格式异常: data[{index}].name 缺失或非法"
84
+ )
85
+
86
+ count = item.get("count")
87
+ if isinstance(count, bool) or not isinstance(count, int) or count < 0:
88
+ raise AdapterError(
89
+ f"晨涧云响应格式异常: {name}.count={count!r} 非法"
90
+ )
91
+
92
+ memory = item.get("gpuMemory")
93
+ if memory is not None and (
94
+ isinstance(memory, bool) or not isinstance(memory, int)
95
+ ):
96
+ raise AdapterError(
97
+ f"晨涧云响应格式异常: {name}.gpuMemory={memory!r} 非法"
98
+ )
99
+
100
+ short_name = item.get("shortName")
101
+ if short_name is not None and not isinstance(short_name, str):
102
+ raise AdapterError(
103
+ f"晨涧云响应格式异常: {name}.shortName 不是字符串"
104
+ )
105
+
106
+ description = item.get("description")
107
+ if description is not None and not isinstance(description, str):
108
+ raise AdapterError(
109
+ f"晨涧云响应格式异常: {name}.description 不是字符串"
110
+ )
111
+
112
+ extra = {
113
+ key: value for key, value in item.items() if key not in KNOWN_FIELDS
114
+ } or None
115
+
116
+ offers.append(
117
+ GpuOffer(
118
+ platform=self.platform,
119
+ service_kind=kind,
120
+ gpu_model=name,
121
+ display_name=short_name or name,
122
+ description=description or "",
123
+ gpu_memory_gb=memory,
124
+ free=count,
125
+ total=None,
126
+ region=None,
127
+ machine_id=None,
128
+ price_per_hour=None,
129
+ charge_type=None,
130
+ url=self.MARKET_URL,
131
+ checked_at=checked_at,
132
+ extra=extra,
133
+ )
134
+ )
135
+ return offers
136
+
137
+
138
+ def _format_time(value: datetime) -> str:
139
+ if value.tzinfo is None:
140
+ value = value.replace(tzinfo=timezone.utc)
141
+ return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
142
+
143
+
144
+ def _http_get_json(url: str, headers: dict, timeout: float) -> object:
145
+ request = urllib.request.Request(url, headers=headers)
146
+ try:
147
+ with urllib.request.urlopen(request, timeout=timeout) as response:
148
+ body = response.read()
149
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
150
+ raise AdapterError(f"请求晨涧云失败: {exc}") from exc
151
+
152
+ try:
153
+ return json.loads(body.decode("utf-8"))
154
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
155
+ raise AdapterError(f"晨涧云响应不是合法 JSON: {exc}") from exc