tensorbase-sdk 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,269 @@
1
+ """Sandboxes (Firecracker microVMs for untrusted code) and desktops (computers for agents)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import time
7
+ import urllib.parse
8
+ from dataclasses import dataclass
9
+ from typing import Any, Dict, Iterable, List, Optional, Union
10
+
11
+ from ._volumes import mounts as _mounts
12
+ from ._client import Client, TensorbaseError, default_client
13
+
14
+ Egress = Union[str, Dict[str, Any], None]
15
+
16
+
17
+ def _egress(e: Egress, allow: Optional[Iterable[str]] = None) -> Optional[dict]:
18
+ if e is None and allow is None:
19
+ return None
20
+ if isinstance(e, dict):
21
+ return e
22
+ out: Dict[str, Any] = {"mode": e or ("allowlist" if allow else "open")}
23
+ if allow:
24
+ out["allow"] = list(allow)
25
+ return out
26
+
27
+
28
+ def _resources(cpu: Optional[float], memory: Optional[int], disk: Optional[int]) -> Optional[dict]:
29
+ r: Dict[str, Any] = {}
30
+ if cpu is not None:
31
+ r["cpu_millicores"] = int(cpu * 1000)
32
+ if memory is not None:
33
+ r["memory_mib"] = memory
34
+ if disk is not None:
35
+ r["disk_mib"] = disk
36
+ return r or None
37
+
38
+
39
+ def _clean(d: dict) -> dict:
40
+ return {k: v for k, v in d.items() if v is not None}
41
+
42
+
43
+ def _q(id_: str) -> str:
44
+ return urllib.parse.quote(id_, safe="")
45
+
46
+
47
+ _PENDING = ("pending", "creating", "starting", "waking", "resuming")
48
+
49
+
50
+ def _wait_running(m, wait: float):
51
+ """Polls until the machine leaves its starting states, or ``wait`` seconds pass. A failed
52
+ machine raises with the reason the API gives."""
53
+ deadline = time.monotonic() + wait
54
+ while m.status in _PENDING and time.monotonic() < deadline:
55
+ time.sleep(0.5)
56
+ m.refresh()
57
+ if m.status == "failed":
58
+ raise TensorbaseError(0, "FAILED", f"{m.id} failed: {m.data.get('status_message') or 'no reason given'}")
59
+ return m
60
+
61
+
62
+ @dataclass
63
+ class ExecResult:
64
+ exit_code: int
65
+ stdout: str
66
+ stderr: str
67
+ duration_ms: int = 0
68
+ truncated: bool = False
69
+
70
+ @classmethod
71
+ def _from(cls, d: dict) -> "ExecResult":
72
+ return cls(d.get("exit_code", 0), d.get("stdout", ""), d.get("stderr", ""), d.get("duration_ms", 0), d.get("truncated", False))
73
+
74
+
75
+ class _Files:
76
+ def __init__(self, sbx: "Sandbox"):
77
+ self._s = sbx
78
+
79
+ def read(self, path: str) -> bytes:
80
+ return self._s._client.request_raw("GET", f"/v1/sandboxes/{_q(self._s.id)}/files", query={"path": path})
81
+
82
+ def read_text(self, path: str, encoding: str = "utf-8") -> str:
83
+ return self.read(path).decode(encoding)
84
+
85
+ def write(self, path: str, data: Union[str, bytes]) -> None:
86
+ body = data.encode() if isinstance(data, str) else data
87
+ self._s._client.request_raw("PUT", f"/v1/sandboxes/{_q(self._s.id)}/files", body, {"path": path},
88
+ content_type="application/octet-stream")
89
+
90
+ def list(self, path: str = "/") -> List[dict]:
91
+ return self._s._client.request("GET", f"/v1/sandboxes/{_q(self._s.id)}/dir", query={"path": path})["items"]
92
+
93
+
94
+ class Sandbox:
95
+ """A Firecracker microVM with its own kernel, for code you do not trust.
96
+
97
+ sbx = tb.Sandbox.create(image="tensorbase/sandbox:python3.12", egress="none")
98
+ sbx.files.write("/work/main.py", code)
99
+ print(sbx.exec("python /work/main.py", timeout=30).stdout)
100
+ sbx.delete()
101
+ """
102
+
103
+ def __init__(self, data: dict, client: Optional[Client] = None):
104
+ self._client = client or default_client()
105
+ self.data = data
106
+ self.files = _Files(self)
107
+
108
+ @property
109
+ def id(self) -> str:
110
+ return self.data["id"]
111
+
112
+ @property
113
+ def status(self) -> str:
114
+ return self.data.get("status", "")
115
+
116
+ @classmethod
117
+ def create(cls, image: Optional[str] = None, *, name: Optional[str] = None, cpu: Optional[float] = None,
118
+ memory: Optional[int] = None, disk: Optional[int] = None, egress: Egress = None,
119
+ allow: Optional[Iterable[str]] = None, env: Optional[Dict[str, str]] = None,
120
+ secrets: Optional[List[str]] = None, idle_timeout: Optional[int] = None, ttl: Optional[int] = None,
121
+ from_snapshot: Optional[str] = None, labels: Optional[Dict[str, str]] = None, volumes=None, wait: int = 60,
122
+ client: Optional[Client] = None) -> "Sandbox":
123
+ """Creates a sandbox and waits up to ``wait`` seconds for it to run. ``egress`` is
124
+ "open", "allowlist" (with ``allow``) or "none". ``cpu`` is in vCPUs, ``memory`` and
125
+ ``disk`` in MiB."""
126
+ c = client or default_client()
127
+ body = _clean({"image": image, "name": name, "resources": _resources(cpu, memory, disk), "egress": _egress(egress, allow),
128
+ "env": env, "secrets": secrets, "idle_timeout_seconds": idle_timeout, "ttl_seconds": ttl,
129
+ "from_snapshot": from_snapshot, "labels": labels, "volumes": _mounts(volumes)})
130
+ data = c.request("POST", f"/v1/workspaces/{_q(c.need_workspace())}/sandboxes", body, {"wait_seconds": min(max(int(wait), 0), 60)},
131
+ timeout=min(wait, 60) + 30)
132
+ return _wait_running(cls(data, c), wait)
133
+
134
+ @classmethod
135
+ def get(cls, id: str, *, client: Optional[Client] = None) -> "Sandbox":
136
+ c = client or default_client()
137
+ return cls(c.request("GET", f"/v1/sandboxes/{_q(id)}"), c)
138
+
139
+ @classmethod
140
+ def list(cls, *, client: Optional[Client] = None) -> List["Sandbox"]:
141
+ c = client or default_client()
142
+ return [cls(d, c) for d in c.request("GET", f"/v1/workspaces/{_q(c.need_workspace())}/sandboxes")["items"]]
143
+
144
+ def refresh(self) -> "Sandbox":
145
+ self.data = self._client.request("GET", f"/v1/sandboxes/{_q(self.id)}")
146
+ return self
147
+
148
+ def exec(self, command: str, *, timeout: int = 60, cwd: Optional[str] = None, env: Optional[Dict[str, str]] = None,
149
+ stdin: Optional[str] = None) -> ExecResult:
150
+ """Runs ``command`` with /bin/sh -lc and returns its exit code and output."""
151
+ body = _clean({"command": command, "timeout_seconds": timeout, "cwd": cwd, "env": env, "stdin": stdin})
152
+ return ExecResult._from(self._client.request("POST", f"/v1/sandboxes/{_q(self.id)}:exec", body, timeout=timeout + 30))
153
+
154
+ def expose(self, port: int, *, public: bool = False) -> str:
155
+ """Serves ``port`` at an HTTPS preview URL and returns the URL."""
156
+ return self._client.request("POST", f"/v1/sandboxes/{_q(self.id)}/ports", {"port": port, "public": public})["url"]
157
+
158
+ def snapshot(self, name: Optional[str] = None) -> dict:
159
+ """Saves memory and disk; start new sandboxes from it with ``from_snapshot``."""
160
+ return self._client.request("POST", f"/v1/sandboxes/{_q(self.id)}:snapshot", _clean({"name": name}))
161
+
162
+ def pause(self) -> "Sandbox":
163
+ self.data = self._client.request("POST", f"/v1/sandboxes/{_q(self.id)}:pause", {})
164
+ return self
165
+
166
+ def resume(self) -> "Sandbox":
167
+ self.data = self._client.request("POST", f"/v1/sandboxes/{_q(self.id)}:resume", {})
168
+ return self
169
+
170
+ def delete(self) -> None:
171
+ self._client.request("DELETE", f"/v1/sandboxes/{_q(self.id)}")
172
+
173
+ def __enter__(self) -> "Sandbox":
174
+ return self
175
+
176
+ def __exit__(self, *exc) -> None:
177
+ self.delete()
178
+
179
+ def __repr__(self) -> str:
180
+ return f"Sandbox({self.id!r}, status={self.status!r})"
181
+
182
+
183
+ class Desktop:
184
+ """A Linux desktop with Chrome and a terminal that an agent drives with the computer-use API.
185
+
186
+ desk = tb.Desktop.create(name="research", look={"display_name": "Research agent"})
187
+ desk.act([{"type": "browser_open", "url": "https://example.com"}])
188
+ png = desk.screenshot()
189
+ """
190
+
191
+ def __init__(self, data: dict, client: Optional[Client] = None):
192
+ self._client = client or default_client()
193
+ self.data = data
194
+
195
+ @property
196
+ def id(self) -> str:
197
+ return self.data["id"]
198
+
199
+ @property
200
+ def status(self) -> str:
201
+ return self.data.get("status", "")
202
+
203
+ @classmethod
204
+ def create(cls, name: Optional[str] = None, *, look: Optional[dict] = None, cpu: Optional[float] = None,
205
+ memory: Optional[int] = None, disk: Optional[int] = None, width: Optional[int] = None,
206
+ height: Optional[int] = None, egress: Egress = None, allow: Optional[Iterable[str]] = None,
207
+ env: Optional[Dict[str, str]] = None, secrets: Optional[List[str]] = None,
208
+ idle_timeout: Optional[int] = None, labels: Optional[Dict[str, str]] = None, volumes=None, wait: int = 120,
209
+ client: Optional[Client] = None) -> "Desktop":
210
+ c = client or default_client()
211
+ screen = _clean({"width": width, "height": height}) or None
212
+ body = _clean({"name": name, "look": look, "resources": _resources(cpu, memory, disk), "screen": screen,
213
+ "egress": _egress(egress, allow), "env": env, "secrets": secrets,
214
+ "idle_timeout_seconds": idle_timeout, "labels": labels, "volumes": _mounts(volumes)})
215
+ data = c.request("POST", f"/v1/workspaces/{_q(c.need_workspace())}/desktops", body, {"wait_seconds": min(max(int(wait), 0), 60)},
216
+ timeout=min(wait, 60) + 30)
217
+ return _wait_running(cls(data, c), wait)
218
+
219
+ @classmethod
220
+ def get(cls, id: str, *, client: Optional[Client] = None) -> "Desktop":
221
+ c = client or default_client()
222
+ return cls(c.request("GET", f"/v1/desktops/{_q(id)}"), c)
223
+
224
+ @classmethod
225
+ def list(cls, *, client: Optional[Client] = None) -> List["Desktop"]:
226
+ c = client or default_client()
227
+ return [cls(d, c) for d in c.request("GET", f"/v1/workspaces/{_q(c.need_workspace())}/desktops")["items"]]
228
+
229
+ def refresh(self) -> "Desktop":
230
+ self.data = self._client.request("GET", f"/v1/desktops/{_q(self.id)}")
231
+ return self
232
+
233
+ def act(self, actions: List[dict], *, screenshot: bool = False) -> dict:
234
+ """Runs computer-use actions in order (click, type, key, scroll, browser_open, …). With
235
+ ``screenshot=True`` the result's ``screenshot`` holds PNG bytes taken after the last one."""
236
+ res = self._client.request("POST", f"/v1/desktops/{_q(self.id)}:act", {"actions": actions, "screenshot": screenshot})
237
+ png = res.get("screenshot_png_base64")
238
+ res["screenshot"] = base64.b64decode(png) if png else None
239
+ return res
240
+
241
+ def screenshot(self, width: Optional[int] = None) -> bytes:
242
+ """The screen as PNG bytes (``width`` scales it down)."""
243
+ return self._client.request_raw("GET", f"/v1/desktops/{_q(self.id)}/screenshot", query={"width": width})
244
+
245
+ def exec(self, command: str, *, timeout: int = 60, cwd: Optional[str] = None, env: Optional[Dict[str, str]] = None) -> ExecResult:
246
+ body = _clean({"command": command, "timeout_seconds": timeout, "cwd": cwd, "env": env})
247
+ return ExecResult._from(self._client.request("POST", f"/v1/desktops/{_q(self.id)}:exec", body, timeout=timeout + 30))
248
+
249
+ def live_url(self, *, control: bool = False) -> str:
250
+ """A one-time, 60-second WebSocket URL for a noVNC viewer."""
251
+ return self._client.request("POST", f"/v1/desktops/{_q(self.id)}/tickets", {"kind": "vnc", "control": control})["url"]
252
+
253
+ def cdp_url(self) -> str:
254
+ """A one-time Chrome DevTools Protocol URL (Puppeteer ``connect``, Playwright ``connect_over_cdp``)."""
255
+ return self._client.request("POST", f"/v1/desktops/{_q(self.id)}/tickets", {"kind": "cdp"})["url"]
256
+
257
+ def sleep(self) -> "Desktop":
258
+ self.data = self._client.request("POST", f"/v1/desktops/{_q(self.id)}:sleep", {})
259
+ return self
260
+
261
+ def wake(self) -> "Desktop":
262
+ self.data = self._client.request("POST", f"/v1/desktops/{_q(self.id)}:wake", {})
263
+ return self
264
+
265
+ def delete(self) -> None:
266
+ self._client.request("DELETE", f"/v1/desktops/{_q(self.id)}")
267
+
268
+ def __repr__(self) -> str:
269
+ return f"Desktop({self.id!r}, status={self.status!r})"
tensorbase/_runner.py ADDED
@@ -0,0 +1,402 @@
1
+ """Tensorbase container runtime.
2
+
3
+ Runs inside every Python function, endpoint, ASGI app, task queue and schedule container. It
4
+ imports the user's handler and serves it over HTTP/1.1 on TB_LISTEN (``tcp:0.0.0.0:8000`` or
5
+ ``unix:/tb/run/http.sock``). The worker agent connects to it; the container itself never connects
6
+ to the platform.
7
+
8
+ Routes:
9
+ GET /__tb/health 200 once the handler module is imported
10
+ POST /__tb/invoke {"args": [...], "kwargs": {...}} -> {"result": ...} | {"error": {...}}
11
+ * anything else kind=endpoint: the function is called with the JSON body (or query) as kwargs
12
+ kind=asgi: the ASGI application
13
+
14
+ Only the standard library is used, so any Python 3.9+ image works.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import importlib
21
+ import inspect
22
+ import json
23
+ import os
24
+ import sys
25
+ import time
26
+ import traceback
27
+ import urllib.parse
28
+ from concurrent.futures import ThreadPoolExecutor
29
+
30
+ KIND = os.environ.get("TB_KIND", "function")
31
+ HANDLER = os.environ.get("TB_HANDLER", "")
32
+ LISTEN = os.environ.get("TB_LISTEN", "tcp:0.0.0.0:8000")
33
+ CONCURRENCY = max(1, int(os.environ.get("TB_CONCURRENCY", "1") or 1))
34
+ CODE_DIR = os.environ.get("TB_CODE_DIR", "/code")
35
+ MAX_BODY = 64 << 20
36
+
37
+ _pool = ThreadPoolExecutor(max_workers=max(CONCURRENCY, 1), thread_name_prefix="tb-call")
38
+ _target = None # the user's callable or ASGI app
39
+ _ready = False
40
+ _load_error = None
41
+
42
+ STATUS_TEXT = {200: "OK", 201: "Created", 204: "No Content", 400: "Bad Request", 404: "Not Found",
43
+ 405: "Method Not Allowed", 413: "Payload Too Large", 500: "Internal Server Error",
44
+ 503: "Service Unavailable"}
45
+
46
+
47
+ def _log(msg: str) -> None:
48
+ print(f"[tensorbase] {msg}", file=sys.stderr, flush=True)
49
+
50
+
51
+ def _load():
52
+ global _target, _ready, _load_error
53
+ if CODE_DIR and CODE_DIR not in sys.path:
54
+ sys.path.insert(0, CODE_DIR)
55
+ if CODE_DIR and os.path.isdir(CODE_DIR):
56
+ os.chdir(CODE_DIR)
57
+ mod_name, _, attr = HANDLER.partition(":")
58
+ if not mod_name or not attr:
59
+ raise RuntimeError(f"TB_HANDLER must be module:function, got {HANDLER!r}")
60
+ if mod_name.endswith(".py"):
61
+ mod_name = mod_name[:-3].replace("/", ".")
62
+ module = importlib.import_module(mod_name)
63
+ obj = module
64
+ for part in attr.split("."):
65
+ obj = getattr(obj, part)
66
+ func = getattr(obj, "__tb_func__", obj)
67
+ if KIND == "asgi":
68
+ # @asgi decorates a factory that returns the app; a bare ASGI app is accepted too.
69
+ if getattr(obj, "__tb_kind__", "") == "asgi" or _is_factory(func):
70
+ func = func()
71
+ _target = func
72
+ _ready = True
73
+
74
+
75
+ def _is_factory(f) -> bool:
76
+ try:
77
+ params = [p for p in inspect.signature(f).parameters.values()
78
+ if p.default is p.empty and p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
79
+ except (TypeError, ValueError):
80
+ return False
81
+ return len(params) == 0
82
+
83
+
84
+ def _jsonable(v):
85
+ try:
86
+ json.dumps(v)
87
+ return v
88
+ except TypeError:
89
+ if hasattr(v, "model_dump"):
90
+ return v.model_dump()
91
+ if hasattr(v, "__dict__"):
92
+ return {k: x for k, x in vars(v).items() if not k.startswith("_")}
93
+ return repr(v)
94
+
95
+
96
+ def _error(e: BaseException) -> dict:
97
+ return {"type": type(e).__name__, "message": str(e),
98
+ "traceback": "".join(traceback.format_exception(type(e), e, e.__traceback__))}
99
+
100
+
101
+ async def _call(args, kwargs):
102
+ fn = _target
103
+ if inspect.iscoroutinefunction(fn):
104
+ return await fn(*args, **kwargs)
105
+ loop = asyncio.get_running_loop()
106
+ res = await loop.run_in_executor(_pool, lambda: fn(*args, **kwargs))
107
+ if inspect.isawaitable(res):
108
+ res = await res
109
+ return res
110
+
111
+
112
+ # ---------------------------------------------------------------- HTTP/1.1
113
+
114
+ class Request:
115
+ def __init__(self, method, target, version, headers, body):
116
+ self.method = method
117
+ self.target = target
118
+ self.version = version
119
+ self.headers = headers # list of (lower-name, value)
120
+ self.body = body
121
+ path, _, query = target.partition("?")
122
+ self.path = urllib.parse.unquote(path)
123
+ self.raw_path = path
124
+ self.query = query
125
+
126
+ def header(self, name, default=""):
127
+ name = name.lower()
128
+ for k, v in self.headers:
129
+ if k == name:
130
+ return v
131
+ return default
132
+
133
+
134
+ async def _read_request(reader: asyncio.StreamReader):
135
+ line = await reader.readline()
136
+ if not line:
137
+ return None
138
+ try:
139
+ method, target, version = line.decode("latin-1").rstrip("\r\n").split(" ", 2)
140
+ except ValueError:
141
+ raise ValueError("bad request line")
142
+ headers = []
143
+ while True:
144
+ h = await reader.readline()
145
+ if h in (b"\r\n", b"\n", b""):
146
+ break
147
+ k, _, v = h.decode("latin-1").partition(":")
148
+ headers.append((k.strip().lower(), v.strip()))
149
+ req = Request(method, target, version, headers, b"")
150
+ te = req.header("transfer-encoding").lower()
151
+ if "chunked" in te:
152
+ chunks = []
153
+ size_total = 0
154
+ while True:
155
+ size_line = await reader.readline()
156
+ size = int(size_line.split(b";")[0].strip() or b"0", 16)
157
+ if size == 0:
158
+ while (await reader.readline()) not in (b"\r\n", b"\n", b""):
159
+ pass
160
+ break
161
+ size_total += size
162
+ if size_total > MAX_BODY:
163
+ raise OverflowError
164
+ chunks.append(await reader.readexactly(size))
165
+ await reader.readline()
166
+ req.body = b"".join(chunks)
167
+ else:
168
+ n = int(req.header("content-length", "0") or 0)
169
+ if n > MAX_BODY:
170
+ raise OverflowError
171
+ if n:
172
+ req.body = await reader.readexactly(n)
173
+ return req
174
+
175
+
176
+ def _head(status, headers, keep_alive):
177
+ lines = [f"HTTP/1.1 {status} {STATUS_TEXT.get(status, 'Status')}"]
178
+ names = set()
179
+ for k, v in headers:
180
+ lines.append(f"{k}: {v}")
181
+ names.add(k.lower())
182
+ if "connection" not in names:
183
+ lines.append("Connection: " + ("keep-alive" if keep_alive else "close"))
184
+ return ("\r\n".join(lines) + "\r\n\r\n").encode("latin-1")
185
+
186
+
187
+ async def _respond(writer, status, body: bytes, content_type="application/json", keep_alive=True, extra=()):
188
+ headers = [("Content-Type", content_type), ("Content-Length", str(len(body)))] + list(extra)
189
+ writer.write(_head(status, headers, keep_alive) + body)
190
+ await writer.drain()
191
+
192
+
193
+ def _json(v) -> bytes:
194
+ return json.dumps(v, default=repr).encode()
195
+
196
+
197
+ async def _handle_invoke(req, writer, keep_alive):
198
+ try:
199
+ payload = json.loads(req.body or b"{}")
200
+ except ValueError as e:
201
+ return await _respond(writer, 400, _json({"error": {"type": "BadRequest", "message": str(e)}}), keep_alive=keep_alive)
202
+ args = payload.get("args") or []
203
+ kwargs = payload.get("kwargs") or {}
204
+ start = time.monotonic()
205
+ try:
206
+ result = await _call(args, kwargs)
207
+ body = {"result": _jsonable(result)}
208
+ except BaseException as e: # noqa: BLE001 - user code may raise anything
209
+ if isinstance(e, (KeyboardInterrupt, SystemExit)):
210
+ raise
211
+ traceback.print_exc()
212
+ body = {"error": _error(e)}
213
+ body["duration_ms"] = int((time.monotonic() - start) * 1000)
214
+ await _respond(writer, 200, _json(body), keep_alive=keep_alive)
215
+
216
+
217
+ async def _handle_endpoint(req, writer, keep_alive):
218
+ kwargs = {}
219
+ if req.body:
220
+ try:
221
+ parsed = json.loads(req.body)
222
+ except ValueError:
223
+ return await _respond(writer, 400, _json({"error": "the request body must be JSON"}), keep_alive=keep_alive)
224
+ if isinstance(parsed, dict):
225
+ kwargs = parsed
226
+ else:
227
+ kwargs = {"body": parsed}
228
+ elif req.query:
229
+ kwargs = {k: v[0] if len(v) == 1 else v for k, v in urllib.parse.parse_qs(req.query).items()}
230
+ try:
231
+ result = await _call([], kwargs)
232
+ except TypeError as e:
233
+ traceback.print_exc()
234
+ return await _respond(writer, 400, _json({"error": str(e)}), keep_alive=keep_alive)
235
+ except Exception as e: # noqa: BLE001
236
+ traceback.print_exc()
237
+ return await _respond(writer, 500, _json({"error": _error(e)["message"]}), keep_alive=keep_alive)
238
+ if isinstance(result, bytes):
239
+ return await _respond(writer, 200, result, "application/octet-stream", keep_alive)
240
+ if isinstance(result, str):
241
+ return await _respond(writer, 200, result.encode(), "text/plain; charset=utf-8", keep_alive)
242
+ await _respond(writer, 200, _json(_jsonable(result)), keep_alive=keep_alive)
243
+
244
+
245
+ async def _handle_asgi(req, writer, keep_alive, client, server):
246
+ scope = {
247
+ "type": "http", "asgi": {"version": "3.0", "spec_version": "2.3"},
248
+ "http_version": req.version.split("/")[-1] if "/" in req.version else "1.1",
249
+ "method": req.method, "scheme": req.header("x-forwarded-proto", "http"),
250
+ "path": req.path, "raw_path": req.raw_path.encode(), "query_string": req.query.encode(),
251
+ "root_path": "", "headers": [(k.encode("latin-1"), v.encode("latin-1")) for k, v in req.headers],
252
+ "client": client, "server": server,
253
+ }
254
+ body_sent = False
255
+ state = {"started": False, "chunked": False, "done": False}
256
+
257
+ async def receive():
258
+ nonlocal body_sent
259
+ if not body_sent:
260
+ body_sent = True
261
+ return {"type": "http.request", "body": req.body, "more_body": False}
262
+ await asyncio.sleep(3600)
263
+ return {"type": "http.disconnect"}
264
+
265
+ async def send(message):
266
+ t = message["type"]
267
+ if t == "http.response.start":
268
+ headers = [(k.decode("latin-1"), v.decode("latin-1")) for k, v in message.get("headers", [])]
269
+ names = {k.lower() for k, _ in headers}
270
+ if "content-length" not in names:
271
+ headers.append(("Transfer-Encoding", "chunked"))
272
+ state["chunked"] = True
273
+ writer.write(_head(message["status"], headers, keep_alive))
274
+ state["started"] = True
275
+ elif t == "http.response.body":
276
+ body = message.get("body", b"")
277
+ more = message.get("more_body", False)
278
+ if state["chunked"]:
279
+ if body:
280
+ writer.write(b"%x\r\n%s\r\n" % (len(body), body))
281
+ if not more:
282
+ writer.write(b"0\r\n\r\n")
283
+ else:
284
+ writer.write(body)
285
+ if not more:
286
+ state["done"] = True
287
+ await writer.drain()
288
+
289
+ try:
290
+ await _target(scope, receive, send)
291
+ except Exception as e: # noqa: BLE001
292
+ traceback.print_exc()
293
+ if not state["started"]:
294
+ return await _respond(writer, 500, b"Internal Server Error", "text/plain", keep_alive)
295
+ raise
296
+ if not state["started"]:
297
+ await _respond(writer, 500, b"ASGI app sent no response", "text/plain", keep_alive)
298
+ elif not state["done"]:
299
+ if state["chunked"]:
300
+ writer.write(b"0\r\n\r\n")
301
+ await writer.drain()
302
+
303
+
304
+ async def _serve_conn(reader, writer):
305
+ peer = writer.get_extra_info("peername")
306
+ client = list(peer[:2]) if isinstance(peer, tuple) else ["127.0.0.1", 0]
307
+ server = ["tensorbase", 80]
308
+ try:
309
+ while True:
310
+ try:
311
+ req = await _read_request(reader)
312
+ except OverflowError:
313
+ await _respond(writer, 413, _json({"error": "request body too large"}), keep_alive=False)
314
+ break
315
+ except (ValueError, asyncio.IncompleteReadError):
316
+ break
317
+ if req is None:
318
+ break
319
+ keep_alive = req.header("connection").lower() != "close"
320
+ if req.path == "/__tb/health":
321
+ status = 200 if _ready else 503
322
+ await _respond(writer, status, _json({"ready": _ready, "error": _load_error}), keep_alive=keep_alive)
323
+ elif not _ready:
324
+ await _respond(writer, 503, _json({"error": _load_error or "starting"}), keep_alive=keep_alive)
325
+ elif req.path == "/__tb/invoke" and req.method == "POST":
326
+ await _handle_invoke(req, writer, keep_alive)
327
+ elif KIND == "asgi":
328
+ await _handle_asgi(req, writer, keep_alive, client, server)
329
+ elif KIND == "endpoint":
330
+ await _handle_endpoint(req, writer, keep_alive)
331
+ else:
332
+ await _respond(writer, 404, _json({"error": "not found"}), keep_alive=keep_alive)
333
+ if not keep_alive:
334
+ break
335
+ except (ConnectionError, asyncio.CancelledError):
336
+ pass
337
+ finally:
338
+ try:
339
+ writer.close()
340
+ except Exception: # noqa: BLE001
341
+ pass
342
+
343
+
344
+ async def _lifespan():
345
+ if KIND != "asgi":
346
+ return
347
+ queue: asyncio.Queue = asyncio.Queue()
348
+ await queue.put({"type": "lifespan.startup"})
349
+ done = asyncio.get_running_loop().create_future()
350
+
351
+ async def receive():
352
+ return await queue.get()
353
+
354
+ async def send(message):
355
+ if message["type"].startswith("lifespan.startup") and not done.done():
356
+ done.set_result(message["type"])
357
+
358
+ async def run():
359
+ try:
360
+ await _target({"type": "lifespan", "asgi": {"version": "3.0"}}, receive, send)
361
+ except Exception: # noqa: BLE001 - apps without lifespan support raise here
362
+ pass
363
+ if not done.done():
364
+ done.set_result("unsupported")
365
+
366
+ asyncio.get_running_loop().create_task(run())
367
+ try:
368
+ await asyncio.wait_for(done, timeout=60)
369
+ except asyncio.TimeoutError:
370
+ _log("ASGI lifespan startup timed out")
371
+
372
+
373
+ async def main():
374
+ global _load_error
375
+ scheme, _, addr = LISTEN.partition(":")
376
+ if scheme == "unix":
377
+ try:
378
+ os.unlink(addr)
379
+ except FileNotFoundError:
380
+ pass
381
+ server = await asyncio.start_unix_server(_serve_conn, path=addr, limit=1 << 20)
382
+ else:
383
+ host, _, port = addr.rpartition(":")
384
+ server = await asyncio.start_server(_serve_conn, host=host or "0.0.0.0", port=int(port), limit=1 << 20)
385
+ _log(f"loading {HANDLER} ({KIND}, concurrency {CONCURRENCY})")
386
+ try:
387
+ _load()
388
+ await _lifespan()
389
+ _log("ready")
390
+ except BaseException as e: # noqa: BLE001
391
+ _load_error = f"{type(e).__name__}: {e}"
392
+ traceback.print_exc()
393
+ _log("handler failed to load")
394
+ sys.stdout.flush()
395
+ sys.stderr.flush()
396
+ os._exit(3)
397
+ async with server:
398
+ await server.serve_forever()
399
+
400
+
401
+ if __name__ == "__main__":
402
+ asyncio.run(main())