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.
- tensorbase/__init__.py +28 -0
- tensorbase/_app.py +364 -0
- tensorbase/_client.py +96 -0
- tensorbase/_inspect.py +51 -0
- tensorbase/_machines.py +269 -0
- tensorbase/_runner.py +402 -0
- tensorbase/_volumes.py +204 -0
- tensorbase/webhooks.py +79 -0
- tensorbase_sdk-0.1.0.dist-info/METADATA +122 -0
- tensorbase_sdk-0.1.0.dist-info/RECORD +13 -0
- tensorbase_sdk-0.1.0.dist-info/WHEEL +5 -0
- tensorbase_sdk-0.1.0.dist-info/licenses/LICENSE +201 -0
- tensorbase_sdk-0.1.0.dist-info/top_level.txt +1 -0
tensorbase/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Tensorbase Python SDK.
|
|
2
|
+
|
|
3
|
+
import tensorbase as tb
|
|
4
|
+
|
|
5
|
+
app = tb.App("demo")
|
|
6
|
+
|
|
7
|
+
@app.function(cpu=1, memory=512)
|
|
8
|
+
def square(x):
|
|
9
|
+
return x * x
|
|
10
|
+
|
|
11
|
+
# tb deploy app.py
|
|
12
|
+
square.remote(4) # 16
|
|
13
|
+
square.map([1, 2, 3]) # [1, 4, 9]
|
|
14
|
+
|
|
15
|
+
Inside a Tensorbase container the decorators only register functions; nothing calls the API.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from ._app import (App, Function, Image, RemoteError, Secret, Task, Volume, asgi, endpoint, function,
|
|
19
|
+
functions_in, schedule, task_queue)
|
|
20
|
+
from ._client import Client, TensorbaseError
|
|
21
|
+
from ._machines import Desktop, ExecResult, Sandbox
|
|
22
|
+
from . import webhooks
|
|
23
|
+
|
|
24
|
+
__version__ = "0.1.0"
|
|
25
|
+
|
|
26
|
+
__all__ = ["App", "Client", "Desktop", "ExecResult", "Function", "Image", "RemoteError", "Sandbox", "Secret", "Task",
|
|
27
|
+
"TensorbaseError", "Volume",
|
|
28
|
+
"asgi", "endpoint", "function", "functions_in", "schedule", "task_queue", "webhooks"]
|
tensorbase/_app.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""Apps, decorators and handles for deployed functions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import concurrent.futures
|
|
6
|
+
import functools
|
|
7
|
+
import inspect
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Union
|
|
13
|
+
|
|
14
|
+
from ._client import Client, TensorbaseError, default_client
|
|
15
|
+
from ._volumes import Volume, mounts as _mounts
|
|
16
|
+
|
|
17
|
+
IN_CONTAINER = os.environ.get("TB_CONTAINER") == "1"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Image:
|
|
22
|
+
"""A container image built once per spec (hash) by the platform.
|
|
23
|
+
|
|
24
|
+
``Image(python_packages=["numpy"])`` extends ``python:3.12-slim``; ``Image(dockerfile=...)``
|
|
25
|
+
builds a Dockerfile instead.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
base: str = "python:3.12-slim"
|
|
29
|
+
python_packages: List[str] = field(default_factory=list)
|
|
30
|
+
apt_packages: List[str] = field(default_factory=list)
|
|
31
|
+
commands: List[str] = field(default_factory=list)
|
|
32
|
+
env: Dict[str, str] = field(default_factory=dict)
|
|
33
|
+
dockerfile: Optional[str] = None
|
|
34
|
+
|
|
35
|
+
def add_python_packages(self, *pkgs: str) -> "Image":
|
|
36
|
+
return Image(self.base, self.python_packages + list(pkgs), self.apt_packages, self.commands, self.env, self.dockerfile)
|
|
37
|
+
|
|
38
|
+
def add_apt_packages(self, *pkgs: str) -> "Image":
|
|
39
|
+
return Image(self.base, self.python_packages, self.apt_packages + list(pkgs), self.commands, self.env, self.dockerfile)
|
|
40
|
+
|
|
41
|
+
def add_commands(self, *cmds: str) -> "Image":
|
|
42
|
+
return Image(self.base, self.python_packages, self.apt_packages, self.commands + list(cmds), self.env, self.dockerfile)
|
|
43
|
+
|
|
44
|
+
def with_env(self, **env: str) -> "Image":
|
|
45
|
+
return Image(self.base, self.python_packages, self.apt_packages, self.commands, {**self.env, **env}, self.dockerfile)
|
|
46
|
+
|
|
47
|
+
def spec(self) -> dict:
|
|
48
|
+
return {"base": self.base, "python_packages": self.python_packages, "apt_packages": self.apt_packages,
|
|
49
|
+
"commands": self.commands, "env": self.env, "dockerfile": self.dockerfile}
|
|
50
|
+
|
|
51
|
+
def is_plain(self) -> bool:
|
|
52
|
+
"""A stock python image with nothing added: no build needed."""
|
|
53
|
+
return (self.dockerfile is None and not self.python_packages and not self.apt_packages and not self.commands
|
|
54
|
+
and not self.env and self.base.startswith("python:3.") and self.base.endswith("-slim"))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class Secret:
|
|
59
|
+
"""A workspace secret exposed to the function as an environment variable of the same name."""
|
|
60
|
+
|
|
61
|
+
name: str
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _runtime_of(image: Optional[Image]) -> str:
|
|
65
|
+
if image and image.base.startswith("python:3.") and image.base.endswith("-slim"):
|
|
66
|
+
return "python" + image.base[len("python:"):-len("-slim")]
|
|
67
|
+
return "python{}.{}".format(*sys.version_info[:2]) if sys.version_info[:2] in ((3, 10), (3, 11), (3, 12), (3, 13)) else "python3.12"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Task:
|
|
71
|
+
"""A queued call. ``result()`` waits for it."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, data: dict, client: Client):
|
|
74
|
+
self._data = data
|
|
75
|
+
self._client = client
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def id(self) -> str:
|
|
79
|
+
return self._data["id"]
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def status(self) -> str:
|
|
83
|
+
return self._data["status"]
|
|
84
|
+
|
|
85
|
+
def refresh(self, wait: int = 0) -> "Task":
|
|
86
|
+
self._data = self._client.request("GET", f"/v1/tasks/{self.id}", query={"wait_seconds": wait or None}, timeout=wait + 30)
|
|
87
|
+
return self
|
|
88
|
+
|
|
89
|
+
def result(self, timeout: Optional[float] = None) -> Any:
|
|
90
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
91
|
+
while self.status not in ("succeeded", "failed", "cancelled", "timed_out"):
|
|
92
|
+
left = 60 if deadline is None else max(0, min(60, deadline - time.monotonic()))
|
|
93
|
+
if deadline is not None and left == 0:
|
|
94
|
+
raise TimeoutError(f"task {self.id} is still {self.status}")
|
|
95
|
+
self.refresh(int(left) or 1)
|
|
96
|
+
if self.status != "succeeded":
|
|
97
|
+
err = self._data.get("error") or {}
|
|
98
|
+
raise RemoteError(err.get("type", self.status), err.get("message", self.status), err.get("traceback", ""))
|
|
99
|
+
return self._data.get("result")
|
|
100
|
+
|
|
101
|
+
def cancel(self) -> "Task":
|
|
102
|
+
self._data = self._client.request("POST", f"/v1/tasks/{self.id}:cancel")
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
def __repr__(self) -> str:
|
|
106
|
+
return f"<Task {self.id} {self.status}>"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class RemoteError(Exception):
|
|
110
|
+
"""The remote function raised. ``traceback`` is the remote traceback."""
|
|
111
|
+
|
|
112
|
+
def __init__(self, type_: str, message: str, traceback: str = ""):
|
|
113
|
+
super().__init__(f"{type_}: {message}")
|
|
114
|
+
self.type = type_
|
|
115
|
+
self.traceback = traceback
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _mib(v) -> int:
|
|
119
|
+
"""Memory in MiB: a number of MiB, or a string such as "512Mi", "4Gi", "2G" or "1024"."""
|
|
120
|
+
if isinstance(v, (int, float)):
|
|
121
|
+
return int(v)
|
|
122
|
+
t = str(v).strip()
|
|
123
|
+
units = {"ki": 1 / 1024, "mi": 1, "gi": 1024, "ti": 1024 * 1024, "k": 1000 / 1024 / 1024, "m": 1000 * 1000 / 1024 / 1024,
|
|
124
|
+
"g": 1000 ** 3 / 1024 / 1024, "": 1}
|
|
125
|
+
num = t.rstrip("KkMmGgTtIi")
|
|
126
|
+
unit = t[len(num):].lower()
|
|
127
|
+
if unit not in units or not num:
|
|
128
|
+
raise ValueError(f"memory {v!r}: use MiB (512) or a size like '512Mi' or '4Gi'")
|
|
129
|
+
return int(float(num) * units[unit])
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class Function:
|
|
133
|
+
"""A decorated function. Call it to run locally; ``.remote()`` runs the deployed version."""
|
|
134
|
+
|
|
135
|
+
def __init__(self, func: Callable, kind: str, app: "App", options: dict):
|
|
136
|
+
functools.update_wrapper(self, func)
|
|
137
|
+
self.__tb_func__ = func
|
|
138
|
+
self.__tb_kind__ = kind
|
|
139
|
+
self.func = func
|
|
140
|
+
self.kind = kind
|
|
141
|
+
self.app = app
|
|
142
|
+
self.options = options
|
|
143
|
+
self.name = options.get("name") or func.__name__.replace("_", "-").lower()
|
|
144
|
+
self._deployment_id: Optional[str] = None
|
|
145
|
+
|
|
146
|
+
@classmethod
|
|
147
|
+
def lookup(cls, app: str, name: str, *, client: Optional[Client] = None) -> "Function":
|
|
148
|
+
"""A handle to a deployed function without importing its code:
|
|
149
|
+
``tb.Function.lookup("hello", "square").remote(7)``."""
|
|
150
|
+
def not_local(*_a, **_k):
|
|
151
|
+
raise TypeError(f"{app}/{name} was looked up; call .remote(), .map() or .spawn()")
|
|
152
|
+
not_local.__name__ = not_local.__qualname__ = name
|
|
153
|
+
fn = cls(not_local, "function", App(app, client=client), {"name": name})
|
|
154
|
+
dep = fn._client().request("GET", f"/v1/deployments/{fn.deployment_id()}")
|
|
155
|
+
fn.kind = fn.__tb_kind__ = dep.get("kind", "function")
|
|
156
|
+
return fn
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def app_name(self) -> str:
|
|
160
|
+
if not self.app.implicit:
|
|
161
|
+
return self.app.name
|
|
162
|
+
mod = self.func.__module__
|
|
163
|
+
if mod == "__main__":
|
|
164
|
+
mod = os.path.splitext(os.path.basename(getattr(sys.modules["__main__"], "__file__", "app") or "app"))[0]
|
|
165
|
+
return mod.split(".")[-1].replace("_", "-").lower()
|
|
166
|
+
|
|
167
|
+
def __call__(self, *args, **kwargs):
|
|
168
|
+
return self.func(*args, **kwargs)
|
|
169
|
+
|
|
170
|
+
def local(self, *args, **kwargs):
|
|
171
|
+
return self.func(*args, **kwargs)
|
|
172
|
+
|
|
173
|
+
# ---- deployment manifest (read by `tb deploy`) ----
|
|
174
|
+
|
|
175
|
+
def manifest(self, module: str) -> dict:
|
|
176
|
+
o = self.options
|
|
177
|
+
image: Optional[Image] = o.get("image")
|
|
178
|
+
resources = {"cpu_millicores": int(float(o.get("cpu", 1)) * 1000), "memory_mib": _mib(o.get("memory", 1024))}
|
|
179
|
+
if o.get("gpu"):
|
|
180
|
+
resources["gpu"] = o["gpu"]
|
|
181
|
+
resources["gpu_count"] = int(o.get("gpu_count", 1))
|
|
182
|
+
m = {
|
|
183
|
+
"app": self.app_name, "name": self.name, "kind": self.kind, "handler": f"{module}:{self.func.__name__}",
|
|
184
|
+
"runtime": _runtime_of(image), "resources": resources,
|
|
185
|
+
"autoscaling": {k: o[k] for k in ("min_containers", "max_containers", "concurrency", "keep_warm_seconds") if o.get(k) is not None},
|
|
186
|
+
"timeout_seconds": int(o.get("timeout", 300)), "retries": int(o.get("retries", 0)),
|
|
187
|
+
"env": dict(o.get("env") or {}),
|
|
188
|
+
"secrets": [s.name if isinstance(s, Secret) else str(s) for s in (o.get("secrets") or [])],
|
|
189
|
+
"volumes": _mounts(o.get("volumes")) or [],
|
|
190
|
+
"auth": "public" if o.get("public") else "api_key",
|
|
191
|
+
"routes": list(o.get("routes") or []),
|
|
192
|
+
}
|
|
193
|
+
if self.kind == "schedule":
|
|
194
|
+
m["schedule"] = o["cron"]
|
|
195
|
+
if o.get("callback_url"):
|
|
196
|
+
m["callback_url"] = str(o["callback_url"])
|
|
197
|
+
if image is not None and not image.is_plain():
|
|
198
|
+
m["image"] = image.spec()
|
|
199
|
+
return m
|
|
200
|
+
|
|
201
|
+
# ---- remote calls ----
|
|
202
|
+
|
|
203
|
+
def _client(self) -> Client:
|
|
204
|
+
return self.app.client or default_client()
|
|
205
|
+
|
|
206
|
+
def deployment_id(self) -> str:
|
|
207
|
+
if self._deployment_id:
|
|
208
|
+
return self._deployment_id
|
|
209
|
+
c = self._client()
|
|
210
|
+
ws = c.need_workspace()
|
|
211
|
+
apps = c.request("GET", f"/v1/workspaces/{ws}/apps", query={"limit": 200})["items"]
|
|
212
|
+
app = next((a for a in apps if a["name"] == self.app_name), None)
|
|
213
|
+
if app is None:
|
|
214
|
+
raise TensorbaseError(404, "NOT_FOUND", f"app {self.app_name!r} is not deployed (tb deploy)")
|
|
215
|
+
deps = c.request("GET", f"/v1/apps/{app['id']}/deployments", query={"limit": 200})["items"]
|
|
216
|
+
dep = next((d for d in deps if d["name"] == self.name), None)
|
|
217
|
+
if dep is None:
|
|
218
|
+
raise TensorbaseError(404, "NOT_FOUND", f"{self.name!r} is not deployed in app {self.app_name!r} (tb deploy)")
|
|
219
|
+
self._deployment_id = dep["id"]
|
|
220
|
+
return dep["id"]
|
|
221
|
+
|
|
222
|
+
def remote(self, *args, **kwargs) -> Any:
|
|
223
|
+
"""Run the deployed function and return its result (raises RemoteError on failure)."""
|
|
224
|
+
if self.kind not in ("function", "task_queue", "schedule"):
|
|
225
|
+
raise TypeError(f"{self.kind} deployments are called at their URL")
|
|
226
|
+
inv = self._client().request("POST", f"/v1/deployments/{self.deployment_id()}:invoke", {"args": list(args), "kwargs": kwargs},
|
|
227
|
+
timeout=int(self.options.get("timeout", 300)) + 60)
|
|
228
|
+
if inv["status"] != "succeeded":
|
|
229
|
+
err = inv.get("error") or {}
|
|
230
|
+
raise RemoteError(err.get("type", inv["status"]), err.get("message", ""), err.get("traceback", ""))
|
|
231
|
+
return inv.get("result")
|
|
232
|
+
|
|
233
|
+
def map(self, inputs: Iterable[Any], *, max_workers: int = 32, return_exceptions: bool = False) -> List[Any]:
|
|
234
|
+
"""Call the function once per input, in parallel, and return results in order. Tuples are
|
|
235
|
+
spread as positional arguments, dicts as keyword arguments."""
|
|
236
|
+
items = list(inputs)
|
|
237
|
+
|
|
238
|
+
def one(x):
|
|
239
|
+
try:
|
|
240
|
+
if isinstance(x, tuple):
|
|
241
|
+
return self.remote(*x)
|
|
242
|
+
if isinstance(x, dict):
|
|
243
|
+
return self.remote(**x)
|
|
244
|
+
return self.remote(x)
|
|
245
|
+
except Exception as e: # noqa: BLE001
|
|
246
|
+
if return_exceptions:
|
|
247
|
+
return e
|
|
248
|
+
raise
|
|
249
|
+
|
|
250
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, min(max_workers, len(items) or 1))) as pool:
|
|
251
|
+
return list(pool.map(one, items))
|
|
252
|
+
|
|
253
|
+
def spawn(self, *args, **kwargs) -> Task:
|
|
254
|
+
"""Queue a call and return a Task (task queues, or any function asynchronously).
|
|
255
|
+
|
|
256
|
+
To get a signed POST when the task finishes, deploy with ``callback_url=...`` or use
|
|
257
|
+
:meth:`spawn_with_callback`; verify it with :func:`tensorbase.webhooks.verify`.
|
|
258
|
+
"""
|
|
259
|
+
return self._spawn(None, args, kwargs)
|
|
260
|
+
|
|
261
|
+
def spawn_with_callback(self, callback_url: str, *args, **kwargs) -> Task:
|
|
262
|
+
"""Like :meth:`spawn`, but POST the finished task to ``callback_url`` (instead of the
|
|
263
|
+
deployment's ``callback_url``)."""
|
|
264
|
+
return self._spawn(callback_url, args, kwargs)
|
|
265
|
+
|
|
266
|
+
def _spawn(self, callback_url: Optional[str], args, kwargs) -> Task:
|
|
267
|
+
body = {"args": list(args), "kwargs": kwargs}
|
|
268
|
+
if callback_url:
|
|
269
|
+
body["callback_url"] = callback_url
|
|
270
|
+
t = self._client().request("POST", f"/v1/deployments/{self.deployment_id()}/tasks", body)
|
|
271
|
+
return Task(t, self._client())
|
|
272
|
+
|
|
273
|
+
put = spawn
|
|
274
|
+
|
|
275
|
+
@property
|
|
276
|
+
def url(self) -> Optional[str]:
|
|
277
|
+
return self._client().request("GET", f"/v1/deployments/{self.deployment_id()}").get("url")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class App:
|
|
281
|
+
"""Groups functions that deploy together. ``App("name")``; decorators register functions."""
|
|
282
|
+
|
|
283
|
+
def __init__(self, name: Optional[str] = None, *, image: Optional[Image] = None, secrets: Optional[list] = None,
|
|
284
|
+
client: Optional[Client] = None):
|
|
285
|
+
# Without a name, the app is named after the file that defines its functions.
|
|
286
|
+
self.implicit = name is None and not os.environ.get("TB_APP")
|
|
287
|
+
name = name or os.environ.get("TB_APP") or "app"
|
|
288
|
+
self.name = name.replace("_", "-").lower()
|
|
289
|
+
self.image = image
|
|
290
|
+
self.secrets = secrets or []
|
|
291
|
+
self.client = client
|
|
292
|
+
self.functions: Dict[str, Function] = {}
|
|
293
|
+
|
|
294
|
+
def _decorator(self, kind: str, func: Optional[Callable], options: dict):
|
|
295
|
+
def wrap(f: Callable) -> Function:
|
|
296
|
+
opts = dict(options)
|
|
297
|
+
if opts.get("image") is None and self.image is not None:
|
|
298
|
+
opts["image"] = self.image
|
|
299
|
+
if self.secrets:
|
|
300
|
+
opts["secrets"] = list(self.secrets) + list(opts.get("secrets") or [])
|
|
301
|
+
fn = Function(f, kind, self, opts)
|
|
302
|
+
self.functions[fn.name] = fn
|
|
303
|
+
return fn
|
|
304
|
+
return wrap(func) if func is not None else wrap
|
|
305
|
+
|
|
306
|
+
def function(self, func=None, **options):
|
|
307
|
+
"""A function called with ``.remote()`` / ``.map()`` (Lambda-style)."""
|
|
308
|
+
return self._decorator("function", func, options)
|
|
309
|
+
|
|
310
|
+
def endpoint(self, func=None, **options):
|
|
311
|
+
"""An HTTP endpoint: the JSON body (or query) is passed as keyword arguments."""
|
|
312
|
+
return self._decorator("endpoint", func, options)
|
|
313
|
+
|
|
314
|
+
def asgi(self, func=None, **options):
|
|
315
|
+
"""An ASGI app (FastAPI, Starlette…): decorate a function that returns the app."""
|
|
316
|
+
return self._decorator("asgi", func, options)
|
|
317
|
+
|
|
318
|
+
def task_queue(self, func=None, **options):
|
|
319
|
+
"""A task queue: ``.put()`` / ``.spawn()`` enqueue; containers scale with queue depth."""
|
|
320
|
+
return self._decorator("task_queue", func, options)
|
|
321
|
+
|
|
322
|
+
def schedule(self, cron: str, **options):
|
|
323
|
+
"""Run on a cron expression (UTC), e.g. ``@app.schedule("*/5 * * * *")``."""
|
|
324
|
+
return self._decorator("schedule", None, {**options, "cron": cron})
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
_default_app: Optional[App] = None
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _app() -> App:
|
|
331
|
+
global _default_app
|
|
332
|
+
if _default_app is None:
|
|
333
|
+
_default_app = App()
|
|
334
|
+
return _default_app
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def function(func=None, **options):
|
|
338
|
+
return _app().function(func, **options)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def endpoint(func=None, **options):
|
|
342
|
+
return _app().endpoint(func, **options)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def asgi(func=None, **options):
|
|
346
|
+
return _app().asgi(func, **options)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def task_queue(func=None, **options):
|
|
350
|
+
return _app().task_queue(func, **options)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def schedule(cron: str, **options):
|
|
354
|
+
return _app().schedule(cron, **options)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def functions_in(module) -> List[Function]:
|
|
358
|
+
"""Every decorated function defined at the top level of a module."""
|
|
359
|
+
seen, out = set(), []
|
|
360
|
+
for _, v in inspect.getmembers(module):
|
|
361
|
+
if isinstance(v, Function) and id(v) not in seen:
|
|
362
|
+
seen.add(id(v))
|
|
363
|
+
out.append(v)
|
|
364
|
+
return out
|
tensorbase/_client.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Minimal HTTP client for the Tensorbase API (standard library only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import Any, Optional
|
|
11
|
+
|
|
12
|
+
CONFIG_PATH = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "tensorbase", "config.json")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TensorbaseError(Exception):
|
|
16
|
+
"""An API error: ``code`` is the canonical code (NOT_FOUND, …), ``status`` the HTTP status."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, status: int, code: str, message: str):
|
|
19
|
+
super().__init__(f"{code} ({status}): {message}")
|
|
20
|
+
self.status = status
|
|
21
|
+
self.code = code
|
|
22
|
+
self.message = message
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _file_config() -> dict:
|
|
26
|
+
try:
|
|
27
|
+
with open(CONFIG_PATH) as f:
|
|
28
|
+
return json.load(f)
|
|
29
|
+
except (OSError, ValueError):
|
|
30
|
+
return {}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Client:
|
|
34
|
+
"""Talks to the gateway. Settings come from arguments, then TB_API_URL / TB_TOKEN /
|
|
35
|
+
TB_WORKSPACE, then ~/.config/tensorbase/config.json (written by ``tb login``)."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, api_url: Optional[str] = None, token: Optional[str] = None, workspace: Optional[str] = None,
|
|
38
|
+
timeout: float = 330):
|
|
39
|
+
cfg = _file_config()
|
|
40
|
+
self.api_url = (api_url or os.environ.get("TB_API_URL") or cfg.get("api_url") or "https://gateway.tensorbase.ai").rstrip("/")
|
|
41
|
+
self.token = token or os.environ.get("TB_TOKEN") or os.environ.get("TB_API_KEY") or cfg.get("token") or ""
|
|
42
|
+
self.workspace = workspace or os.environ.get("TB_WORKSPACE") or cfg.get("workspace") or ""
|
|
43
|
+
self.timeout = timeout
|
|
44
|
+
|
|
45
|
+
def request(self, method: str, path: str, body: Any = None, query: Optional[dict] = None, timeout: Optional[float] = None) -> Any:
|
|
46
|
+
data = None if body is None else json.dumps(body).encode()
|
|
47
|
+
raw = self.request_raw(method, path, data, query, timeout, "application/json" if body is not None else None)
|
|
48
|
+
return json.loads(raw) if raw else None
|
|
49
|
+
|
|
50
|
+
def request_raw(self, method: str, path: str, data: Optional[bytes] = None, query: Optional[dict] = None,
|
|
51
|
+
timeout: Optional[float] = None, content_type: Optional[str] = None) -> bytes:
|
|
52
|
+
"""Sends ``data`` as is and returns the response body as bytes (files, screenshots)."""
|
|
53
|
+
with self.open(method, path, data, query, timeout, content_type) as res:
|
|
54
|
+
return res.read()
|
|
55
|
+
|
|
56
|
+
def open(self, method: str, path: str, data: Any = None, query: Optional[dict] = None,
|
|
57
|
+
timeout: Optional[float] = None, content_type: Optional[str] = None, length: Optional[int] = None):
|
|
58
|
+
"""Like request_raw, but returns the open response to stream from. ``data`` may be a file
|
|
59
|
+
object (pass ``length``)."""
|
|
60
|
+
url = self.api_url + path
|
|
61
|
+
if query:
|
|
62
|
+
url += "?" + urllib.parse.urlencode({k: v for k, v in query.items() if v is not None})
|
|
63
|
+
headers = {"Accept": "application/json, */*", "User-Agent": "tensorbase-python"}
|
|
64
|
+
if self.token:
|
|
65
|
+
headers["Authorization"] = "Bearer " + self.token
|
|
66
|
+
if content_type:
|
|
67
|
+
headers["Content-Type"] = content_type
|
|
68
|
+
if length is not None:
|
|
69
|
+
headers["Content-Length"] = str(length)
|
|
70
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
71
|
+
try:
|
|
72
|
+
return urllib.request.urlopen(req, timeout=timeout or self.timeout)
|
|
73
|
+
except urllib.error.HTTPError as e:
|
|
74
|
+
raw = e.read()
|
|
75
|
+
try:
|
|
76
|
+
err = json.loads(raw)["error"]
|
|
77
|
+
raise TensorbaseError(err.get("status", e.code), err.get("code", "UNKNOWN"), err.get("message", "")) from None
|
|
78
|
+
except (ValueError, KeyError, TypeError):
|
|
79
|
+
raise TensorbaseError(e.code, "HTTP_ERROR", raw.decode(errors="replace")[:500]) from None
|
|
80
|
+
except urllib.error.URLError as e:
|
|
81
|
+
raise TensorbaseError(0, "UNAVAILABLE", f"cannot reach {self.api_url}: {e.reason}") from None
|
|
82
|
+
|
|
83
|
+
def need_workspace(self) -> str:
|
|
84
|
+
if not self.workspace:
|
|
85
|
+
raise TensorbaseError(0, "FAILED_PRECONDITION", "no workspace: set TB_WORKSPACE or run `tb login`")
|
|
86
|
+
return self.workspace
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
_default: Optional[Client] = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def default_client() -> Client:
|
|
93
|
+
global _default
|
|
94
|
+
if _default is None:
|
|
95
|
+
_default = Client()
|
|
96
|
+
return _default
|
tensorbase/_inspect.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Prints the deployment manifest of a Python file for `tb deploy` / `tb serve`.
|
|
2
|
+
|
|
3
|
+
python3 -m tensorbase._inspect app.py[:function]
|
|
4
|
+
|
|
5
|
+
Output: {"functions": [manifest, …]} as JSON on stdout. The file is imported with the project
|
|
6
|
+
directory (the current directory) on sys.path, as it will be inside the container.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import importlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def module_name(path: str) -> str:
|
|
18
|
+
rel = os.path.relpath(os.path.abspath(path), os.getcwd())
|
|
19
|
+
if rel.startswith(".."):
|
|
20
|
+
raise SystemExit(f"{path} must be inside the current directory (the project that gets uploaded)")
|
|
21
|
+
if rel.endswith(".py"):
|
|
22
|
+
rel = rel[:-3]
|
|
23
|
+
return rel.replace(os.sep, ".")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def main(argv: list) -> int:
|
|
27
|
+
if len(argv) != 1:
|
|
28
|
+
print("usage: python3 -m tensorbase._inspect app.py[:function]", file=sys.stderr)
|
|
29
|
+
return 2
|
|
30
|
+
target, _, fn_name = argv[0].partition(":")
|
|
31
|
+
mod = module_name(target)
|
|
32
|
+
sys.path.insert(0, os.getcwd())
|
|
33
|
+
os.environ.setdefault("TB_INSPECT", "1")
|
|
34
|
+
module = importlib.import_module(mod)
|
|
35
|
+
from tensorbase import functions_in
|
|
36
|
+
|
|
37
|
+
fns = functions_in(module)
|
|
38
|
+
if fn_name:
|
|
39
|
+
fns = [f for f in fns if f.func.__name__ == fn_name or f.name == fn_name]
|
|
40
|
+
if not fns:
|
|
41
|
+
print(f"{argv[0]}: no Tensorbase function named {fn_name!r}", file=sys.stderr)
|
|
42
|
+
return 1
|
|
43
|
+
if not fns:
|
|
44
|
+
print(f"{target}: no @function, @endpoint, @asgi, @task_queue or @schedule found", file=sys.stderr)
|
|
45
|
+
return 1
|
|
46
|
+
json.dump({"functions": [f.manifest(mod) for f in fns]}, sys.stdout)
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == "__main__":
|
|
51
|
+
sys.exit(main(sys.argv[1:]))
|