dmlops 0.2.10__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.
dmlops/_transport.py ADDED
@@ -0,0 +1,133 @@
1
+ """HTTP transport: thin urllib wrapper speaking the platform ApiResponse envelope."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import json
7
+ import urllib.error
8
+ import urllib.request
9
+ from typing import Any, BinaryIO
10
+
11
+ from .exceptions import MlopsAuthError, MlopsConflict, MlopsError
12
+
13
+ SDK_VERSION = "0.2.10"
14
+ SDK_MAJOR = 0
15
+
16
+ DEFAULT_TIMEOUT = 30.0
17
+
18
+
19
+ class Transport:
20
+ """Base-URL + PAT holder; every request carries the SDK version header."""
21
+
22
+ def __init__(self, server: str, token: str | None = None) -> None:
23
+ self.server = server.rstrip("/")
24
+ self.token = token
25
+
26
+ def request(
27
+ self,
28
+ method: str,
29
+ path: str,
30
+ body: dict[str, Any] | None = None,
31
+ *,
32
+ timeout: float = DEFAULT_TIMEOUT,
33
+ headers: dict[str, str] | None = None,
34
+ ) -> Any:
35
+ """Call `<server><path>` and unwrap the ApiResponse envelope.
36
+
37
+ Returns the `data` payload.
38
+ """
39
+ url = path if path.startswith("http") else f"{self.server}{path}"
40
+ data = None
41
+ req_headers: dict[str, str] = {
42
+ "X-Mlops-Sdk-Version": SDK_VERSION,
43
+ "Accept": "application/json",
44
+ }
45
+ if self.token:
46
+ req_headers["Authorization"] = f"ApiKey {self.token}"
47
+ if headers:
48
+ req_headers.update(headers)
49
+ if body is not None:
50
+ data = json.dumps(body).encode("utf-8")
51
+ req_headers["Content-Type"] = "application/json"
52
+ req = urllib.request.Request(url, data=data, method=method, headers=req_headers)
53
+ try:
54
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
55
+ payload = resp.read()
56
+ warn = resp.headers.get("X-Mlops-Sdk-Warn")
57
+ if warn:
58
+ import sys
59
+
60
+ print(f"[mlops] server warning: {warn}", file=sys.stderr)
61
+ except urllib.error.HTTPError as e:
62
+ detail = ""
63
+ try:
64
+ env = json.loads(e.read().decode("utf-8", "replace"))
65
+ err = env.get("error") or {}
66
+ detail = err.get("message") or ""
67
+ code = err.get("code") or ""
68
+ except Exception:
69
+ code = ""
70
+ if e.code == 401:
71
+ raise MlopsAuthError(detail or "authentication failed (401)")
72
+ if e.code == 409:
73
+ exc = MlopsConflict(detail or "conflict (409)")
74
+ exc.code = code or "CONFLICT"
75
+ raise exc
76
+ exc = MlopsError(f"HTTP {e.code}: {detail or e.reason}")
77
+ exc.status = e.code
78
+ raise exc
79
+ except urllib.error.URLError as e:
80
+ raise MlopsError(f"cannot reach server: {e.reason}")
81
+ except http.client.HTTPException as e:
82
+ # IncompleteRead / BadStatusLine / RemoteDisconnected raised
83
+ # while reading the response — not URLError subclasses.
84
+ raise MlopsError(f"bad response from server: {e}")
85
+ except OSError as e:
86
+ # Connect/read timeouts and TLS errors (URLError is an OSError
87
+ # subclass and is handled above).
88
+ raise MlopsError(f"cannot reach server: {e}")
89
+ if not payload:
90
+ return None
91
+ try:
92
+ env = json.loads(payload.decode("utf-8"))
93
+ except ValueError as e:
94
+ raise MlopsError(f"invalid JSON response: {e}")
95
+ if not env.get("success", False):
96
+ err = env.get("error") or {}
97
+ code = err.get("code") or ""
98
+ message = err.get("message") or "request failed"
99
+ if code == "CANCELLED":
100
+ exc = MlopsConflict(message)
101
+ exc.code = "CANCELLED"
102
+ raise exc
103
+ raise MlopsError(f"{code}: {message}")
104
+ return env.get("data")
105
+
106
+ def put_data(
107
+ self,
108
+ url: str,
109
+ data: "bytes | BinaryIO",
110
+ headers: dict[str, str],
111
+ length: int,
112
+ ) -> None:
113
+ """Plain PUT to a presigned MinIO URL (not the platform envelope).
114
+
115
+ ``data`` may be bytes or a binary file object; http.client reads
116
+ file objects in blocks, so large artifacts stream without loading
117
+ into memory. ``length`` is the exact byte count sent (the presigned
118
+ URL signs the content length).
119
+ """
120
+ req = urllib.request.Request(
121
+ url, data=data, method="PUT", headers={"Content-Length": str(length), **headers}
122
+ )
123
+ try:
124
+ with urllib.request.urlopen(req, timeout=max(DEFAULT_TIMEOUT, 300.0)):
125
+ return
126
+ except urllib.error.HTTPError as e:
127
+ raise MlopsError(f"artifact upload failed: HTTP {e.code}: {e.reason}")
128
+ except urllib.error.URLError as e:
129
+ raise MlopsError(f"artifact upload failed: {e.reason}")
130
+ except http.client.HTTPException as e:
131
+ raise MlopsError(f"artifact upload failed: bad response: {e}")
132
+ except OSError as e:
133
+ raise MlopsError(f"artifact upload failed: {e}")