cere 0.1.11__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.
cere/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ """cere: the Python SDK of Cere sandboxes.
2
+
3
+ gVisor sandboxes on the cluster's nodes, in the shape of Modal's API, and agents that run in them::
4
+
5
+ import cere
6
+
7
+ sb = cere.Sandbox.create(image="python:3.12-slim", timeout=600)
8
+ p = sb.exec("python", "-c", "print('hello from a sandbox')")
9
+ print(p.stdout.read(), end="")
10
+ sb.terminate()
11
+
12
+ Sign in once with the CLI (``cere login``, which opens the developer console in your browser),
13
+ or set ``CERE_TOKEN`` (an access token from Developer Console -> Access tokens, for CI).
14
+ Standard library only.
15
+ """
16
+
17
+ from ._version import __version__
18
+ from ._http import CereError, Client, default_client, set_default_client
19
+ from ._s3 import NotConfigured, S3Error
20
+ from .agent import Agent, AgentResult, MissingSecretsError, RunOutcome, run_outcome
21
+ from .egress import Allow, egress_log
22
+ from .process import Process
23
+ from .sandbox import Sandbox
24
+ from .secret import Secret, placeholder
25
+ from .usage import BILLING_STATES, Resources, Usage, billing_state, usage_by_label, usage_records
26
+
27
+ __all__ = [
28
+ "__version__",
29
+ "Agent",
30
+ "AgentResult",
31
+ "Allow",
32
+ "BILLING_STATES",
33
+ "CereError",
34
+ "MissingSecretsError",
35
+ "Client",
36
+ "NotConfigured",
37
+ "Process",
38
+ "Resources",
39
+ "RunOutcome",
40
+ "S3Error",
41
+ "Sandbox",
42
+ "Secret",
43
+ "Usage",
44
+ "billing_state",
45
+ "default_client",
46
+ "egress_log",
47
+ "placeholder",
48
+ "run_outcome",
49
+ "set_default_client",
50
+ "usage_by_label",
51
+ "usage_records",
52
+ ]
cere/_cli.py ADDED
@@ -0,0 +1,60 @@
1
+ """The ``cere`` command of the pure-Python wheel.
2
+
3
+ The cere CLI is a Go binary. The ``cere`` project on PyPI ships it inside per-platform wheels for
4
+ macOS (arm64, x86_64) and Linux (x86_64, aarch64), where pip installs the binary as the ``cere``
5
+ command and this module is never run. Anywhere else pip installs the pure-Python wheel: the SDK
6
+ works, and this command either hands over to a ``cere`` found further along ``PATH`` (one built from
7
+ source, say) or says how to get one.
8
+ """
9
+
10
+ import os
11
+ import platform
12
+ import subprocess
13
+ import sys
14
+
15
+ # Set while handing over, so two fallback commands on one PATH never call each other in a loop.
16
+ _HANDED_OVER = "CERE_FALLBACK_HANDED_OVER"
17
+
18
+ MESSAGE = """\
19
+ cere: pip installed the Python SDK (import cere) but not the cere command-line tool, which is a
20
+ native binary: PyPI has it for macOS (arm64, x86_64) and Linux (x86_64, aarch64), and this is
21
+ {system} {machine} with Python {python}.
22
+
23
+ - On one of those platforms, your pip is probably too old to pick the binary wheel:
24
+ python -m pip install -U pip && python -m pip install --force-reinstall cere
25
+ - Elsewhere, build the CLI from source (Go; `make cli` in a ddc-node checkout) and put it on PATH;
26
+ this command runs it from there. On Windows, install cere inside WSL.
27
+ - The SDK works without the CLI: set CERE_TOKEN to an access token from
28
+ Developer Console -> Access tokens (and CERE_API_URL for another network).
29
+ """
30
+
31
+
32
+ def _other_cere():
33
+ """Another ``cere`` executable on PATH, outside this script's own directory, or None."""
34
+ here = os.path.dirname(os.path.realpath(sys.argv[0])) if sys.argv and sys.argv[0] else ""
35
+ names = ("cere.exe", "cere") if os.name == "nt" else ("cere",)
36
+ for d in os.environ.get("PATH", "").split(os.pathsep):
37
+ if not d or (here and os.path.realpath(d) == here):
38
+ continue
39
+ for name in names:
40
+ p = os.path.join(d, name)
41
+ if os.path.isfile(p) and os.access(p, os.X_OK):
42
+ return p
43
+ return None
44
+
45
+
46
+ def main():
47
+ other = None if os.environ.get(_HANDED_OVER) else _other_cere()
48
+ if other:
49
+ env = dict(os.environ, **{_HANDED_OVER: "1"})
50
+ args = [other] + sys.argv[1:]
51
+ if os.name == "nt":
52
+ return subprocess.call(args, env=env)
53
+ os.execve(other, args, env)
54
+ sys.stderr.write(MESSAGE.format(system=platform.system(), machine=platform.machine(),
55
+ python=platform.python_version()))
56
+ return 1
57
+
58
+
59
+ if __name__ == "__main__":
60
+ sys.exit(main())
cere/_http.py ADDED
@@ -0,0 +1,150 @@
1
+ """The HTTP client of the public sandbox API (docs/compute/sandboxes/API.md)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from typing import Any, Iterator, Optional, Tuple
10
+
11
+ from . import config
12
+ from ._version import __version__
13
+ from ._sse import events
14
+
15
+ DEFAULT_TIMEOUT = 60.0
16
+
17
+
18
+ class CereError(Exception):
19
+ """A non-2xx answer: ``status``, ``message`` and the stable ``code``
20
+ (``no_capacity``, ``not_running``, ``file_gone``, ...)."""
21
+
22
+ def __init__(self, status: int, message: str, code: Optional[str] = None):
23
+ super().__init__(f"{status} {code}: {message}" if code else f"{status}: {message}")
24
+ self.status = status
25
+ self.message = message
26
+ self.code = code
27
+
28
+
29
+ def _error(status: int, body: bytes) -> CereError:
30
+ text = body.decode("utf-8", errors="replace")
31
+ try:
32
+ doc = json.loads(text)
33
+ except ValueError:
34
+ doc = None
35
+ if isinstance(doc, dict) and doc.get("error") is not None:
36
+ err = doc["error"]
37
+ if isinstance(err, dict):
38
+ err = err.get("message", "")
39
+ return CereError(status, str(err), doc.get("code"))
40
+ text = text.strip()[:300]
41
+ return CereError(status, text or "HTTP %d" % status)
42
+
43
+
44
+ class Client:
45
+ """Calls the cluster's API with a DDC access token.
46
+
47
+ By default it reads what ``cere login`` saved (or ``CERE_TOKEN`` / ``CERE_API_URL``)."""
48
+
49
+ def __init__(self, api_url: Optional[str] = None, token: Optional[str] = None, timeout: float = DEFAULT_TIMEOUT):
50
+ cfg = config.load()
51
+ self.api_url = (api_url or cfg.api_url).rstrip("/")
52
+ self.token = token if token is not None else cfg.token
53
+ self.timeout = timeout
54
+ self.s3 = cfg.s3
55
+ if not self.token:
56
+ raise CereError(401, "not logged in: run `cere login`, or set CERE_TOKEN to an access token from "
57
+ "Developer Console -> Access tokens", "unauthenticated")
58
+
59
+ def __repr__(self) -> str:
60
+ return f"Client({self.api_url!r})"
61
+
62
+ def _request(self, method: str, path: str, *, query: Optional[dict] = None, body: Any = None,
63
+ data: Optional[bytes] = None, accept: str = "application/json",
64
+ timeout: Optional[float] = None):
65
+ url = self.api_url + path
66
+ if query:
67
+ url += "?" + urllib.parse.urlencode(
68
+ [(k, v) for k, vals in query.items() for v in (vals if isinstance(vals, list) else [vals]) if v is not None])
69
+ headers = {"Authorization": "Bearer " + self.token, "Accept": accept,
70
+ "User-Agent": "cere-sdk-python/" + __version__}
71
+ if body is not None:
72
+ data = json.dumps(body).encode()
73
+ headers["Content-Type"] = "application/json"
74
+ elif data is not None:
75
+ headers["Content-Type"] = "application/octet-stream"
76
+ req = urllib.request.Request(url, data=data, method=method, headers=headers)
77
+ try:
78
+ return urllib.request.urlopen(req, timeout=timeout or self.timeout)
79
+ except urllib.error.HTTPError as e:
80
+ raise _error(e.code, e.read()) from None
81
+
82
+ def call(self, method: str, path: str, *, query: Optional[dict] = None, body: Any = None,
83
+ timeout: Optional[float] = None) -> Any:
84
+ """A JSON request; returns the decoded answer (None for 204)."""
85
+ with self._request(method, path, query=query, body=body, timeout=timeout) as resp:
86
+ raw = resp.read()
87
+ return json.loads(raw) if raw else None
88
+
89
+ def get_bytes(self, path: str, *, query: Optional[dict] = None, timeout: Optional[float] = None) -> bytes:
90
+ with self._request("GET", path, query=query, accept="*/*", timeout=timeout) as resp:
91
+ return resp.read()
92
+
93
+ def put_bytes(self, path: str, data: bytes, *, query: Optional[dict] = None, timeout: Optional[float] = None) -> None:
94
+ with self._request("PUT", path, query=query, data=data, timeout=timeout) as resp:
95
+ resp.read()
96
+
97
+ def stream(self, method: str, path: str, *, query: Optional[dict] = None, body: Any = None,
98
+ timeout: Optional[float] = None) -> Iterator[Tuple[str, Any]]:
99
+ """Send a request whose answer is an event stream; yield its events.
100
+
101
+ ``timeout`` is the longest silence allowed (the gateway pings every 15 s). An
102
+ ``error`` event raises CereError."""
103
+ resp = self._request(method, path, query=query, body=body, accept="text/event-stream",
104
+ timeout=timeout or self.timeout)
105
+ ctype = resp.headers.get_content_type()
106
+ if ctype != "text/event-stream":
107
+ resp.close()
108
+ raise CereError(502, f"expected text/event-stream from {path}, got {ctype}")
109
+
110
+ def gen() -> Iterator[Tuple[str, Any]]:
111
+ with resp:
112
+ for name, data in events(resp):
113
+ if name == "error":
114
+ if isinstance(data, dict):
115
+ raise CereError(502, str(data.get("error", data)), data.get("code"))
116
+ raise CereError(502, str(data))
117
+ yield name, data
118
+
119
+ return gen()
120
+
121
+ def pages(self, path: str, query: Optional[dict] = None, limit: Optional[int] = None) -> list:
122
+ """Every item of a paged listing (following ``next_cursor``), up to ``limit``."""
123
+ query = dict(query or {})
124
+ out: list = []
125
+ while True:
126
+ want = 500 if limit is None else min(500, limit - len(out))
127
+ query["limit"] = want
128
+ page = self.call("GET", path, query=query)
129
+ items = page.get("items") or []
130
+ out.extend(items)
131
+ cursor = page.get("next_cursor")
132
+ if not cursor or not items or (limit is not None and len(out) >= limit):
133
+ return out
134
+ query["cursor"] = cursor
135
+
136
+
137
+ _default: Optional[Client] = None
138
+
139
+
140
+ def default_client() -> Client:
141
+ global _default
142
+ if _default is None:
143
+ _default = Client()
144
+ return _default
145
+
146
+
147
+ def set_default_client(client: Optional[Client]) -> None:
148
+ """Use ``client`` for calls that are not given one (None: read the config again)."""
149
+ global _default
150
+ _default = client
cere/_s3.py ADDED
@@ -0,0 +1,148 @@
1
+ """A small S3 client (AWS Signature Version 4, standard library only) for the DDC S3 gateway:
2
+ the agent layer keeps definitions at ``cere/agents/<name>.json`` and run outputs under
3
+ ``cere/runs/<sandbox-id>/`` in the customer's bucket. Path-style URLs, unsigned-checksum-free
4
+ requests: what the DDC gateway implements."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import datetime as dt
9
+ import hashlib
10
+ import hmac
11
+ import json
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+ import xml.etree.ElementTree as ET
16
+ from typing import Dict, List, Optional
17
+
18
+ from .config import S3Config
19
+
20
+ AGENTS_PREFIX = "cere/agents/"
21
+ RUNS_PREFIX = "cere/runs/"
22
+ TIMEOUT = 60.0
23
+
24
+
25
+ class S3Error(Exception):
26
+ """An error answer from the bucket's S3 endpoint (agent definitions and run outputs):
27
+ ``status``, the S3 ``code`` (``NoSuchKey``, ``AccessDenied``, ...) and ``message``."""
28
+
29
+ def __init__(self, status: int, code: str, message: str):
30
+ super().__init__(f"S3 {status} {code}: {message}")
31
+ self.status, self.code, self.message = status, code, message
32
+
33
+
34
+ class NotConfigured(Exception):
35
+ """No S3 credential for the bucket: definitions in the bucket need one (``cere login
36
+ --s3-access-key-id ... --s3-bucket ... --s3-secret-stdin``)."""
37
+
38
+
39
+ def _quote(s: str, safe: str = "-_.~") -> str:
40
+ return urllib.parse.quote(s, safe=safe)
41
+
42
+
43
+ def sign(method: str, url: str, headers: Dict[str, str], payload_hash: str, access_key_id: str,
44
+ secret_access_key: str, region: str, now: dt.datetime, service: str = "s3") -> Dict[str, str]:
45
+ """Return ``headers`` plus ``x-amz-date``, ``x-amz-content-sha256`` and ``Authorization``
46
+ for a SigV4-signed request."""
47
+ u = urllib.parse.urlsplit(url)
48
+ amz_date = now.strftime("%Y%m%dT%H%M%SZ")
49
+ day = now.strftime("%Y%m%d")
50
+ out = dict(headers)
51
+ out["x-amz-date"] = amz_date
52
+ out["x-amz-content-sha256"] = payload_hash
53
+ host = u.netloc
54
+ canon_headers = {k.lower().strip(): " ".join(str(v).split()) for k, v in out.items()}
55
+ canon_headers["host"] = host
56
+ signed = ";".join(sorted(canon_headers))
57
+ query = urllib.parse.parse_qsl(u.query, keep_blank_values=True)
58
+ canon_query = "&".join(f"{_quote(k)}={_quote(v)}" for k, v in sorted(query))
59
+ canon_path = _quote(urllib.parse.unquote(u.path or "/"), safe="/-_.~")
60
+ canonical = "\n".join([
61
+ method, canon_path, canon_query,
62
+ "".join(f"{k}:{canon_headers[k]}\n" for k in sorted(canon_headers)),
63
+ signed, payload_hash,
64
+ ])
65
+ scope = f"{day}/{region}/{service}/aws4_request"
66
+ to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, hashlib.sha256(canonical.encode()).hexdigest()])
67
+ key = ("AWS4" + secret_access_key).encode()
68
+ for part in (day, region, service, "aws4_request"):
69
+ key = hmac.new(key, part.encode(), hashlib.sha256).digest()
70
+ signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest()
71
+ out["Authorization"] = (f"AWS4-HMAC-SHA256 Credential={access_key_id}/{scope}, "
72
+ f"SignedHeaders={signed}, Signature={signature}")
73
+ return out
74
+
75
+
76
+ def gateway_region(endpoint: str) -> str:
77
+ """The region the DDC S3 gateway signs for (``GET /auth/info``)."""
78
+ with urllib.request.urlopen(endpoint.rstrip("/") + "/auth/info", timeout=TIMEOUT) as r:
79
+ region = json.load(r).get("region")
80
+ if not region:
81
+ raise S3Error(502, "NoRegion", f"{endpoint}/auth/info named no region")
82
+ return region
83
+
84
+
85
+ class Bucket:
86
+ """The agent layer's keys in one bucket."""
87
+
88
+ def __init__(self, cfg: S3Config):
89
+ if not cfg.complete():
90
+ raise NotConfigured(
91
+ "no S3 credential for the bucket: create one in Developer Console -> Access tokens, then "
92
+ "`cere login --s3-access-key-id <id> --s3-bucket <name> --s3-secret-stdin` (or set CERE_S3_*)")
93
+ self.cfg = cfg
94
+ self.region = cfg.region or gateway_region(cfg.endpoint)
95
+
96
+ @property
97
+ def name(self) -> str:
98
+ return self.cfg.bucket
99
+
100
+ def _call(self, method: str, key: str = "", query: Optional[Dict[str, str]] = None, data: bytes = b"",
101
+ content_type: Optional[str] = None) -> bytes:
102
+ url = f"{self.cfg.endpoint.rstrip('/')}/{_quote(self.cfg.bucket)}"
103
+ if key:
104
+ url += "/" + _quote(key, safe="/-_.~")
105
+ if query:
106
+ url += "?" + "&".join(f"{_quote(k)}={_quote(v)}" for k, v in sorted(query.items()))
107
+ headers: Dict[str, str] = {}
108
+ if content_type:
109
+ headers["Content-Type"] = content_type
110
+ headers = sign(method, url, headers, hashlib.sha256(data).hexdigest(), self.cfg.access_key_id,
111
+ self.cfg.secret_access_key, self.region, dt.datetime.now(dt.timezone.utc))
112
+ req = urllib.request.Request(url, data=data if method == "PUT" else None, method=method, headers=headers)
113
+ try:
114
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
115
+ return r.read()
116
+ except urllib.error.HTTPError as e:
117
+ body = e.read()
118
+ code, msg = "Error", body.decode("utf-8", "replace")[:200]
119
+ try:
120
+ root = ET.fromstring(body)
121
+ code = root.findtext("Code") or code
122
+ msg = root.findtext("Message") or msg
123
+ except ET.ParseError:
124
+ pass
125
+ raise S3Error(e.code, code, msg) from None
126
+
127
+ def list(self, prefix: str) -> List[str]:
128
+ keys: List[str] = []
129
+ token = None
130
+ while True:
131
+ q = {"list-type": "2", "prefix": prefix}
132
+ if token:
133
+ q["continuation-token"] = token
134
+ root = ET.fromstring(self._call("GET", query=q))
135
+ ns = root.tag[: root.tag.index("}") + 1] if root.tag.startswith("{") else ""
136
+ keys += [c.findtext(f"{ns}Key") or "" for c in root.findall(f"{ns}Contents")]
137
+ token = root.findtext(f"{ns}NextContinuationToken")
138
+ if root.findtext(f"{ns}IsTruncated") != "true" or not token:
139
+ return keys
140
+
141
+ def get(self, key: str) -> bytes:
142
+ return self._call("GET", key)
143
+
144
+ def put(self, key: str, data: bytes, content_type: str) -> None:
145
+ self._call("PUT", key, data=data, content_type=content_type)
146
+
147
+ def delete(self, key: str) -> None:
148
+ self._call("DELETE", key)
cere/_sse.py ADDED
@@ -0,0 +1,46 @@
1
+ """A text/event-stream reader. The gateway sends JSON on every ``data:`` line and a
2
+ ``: ping`` comment every 15 seconds; comments, ``id:`` and ``retry:`` are skipped."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from typing import IO, Any, Iterator, Tuple
8
+
9
+
10
+ class StreamCut(Exception):
11
+ """The stream ended in the middle of an event."""
12
+
13
+
14
+ def events(stream: IO[bytes]) -> Iterator[Tuple[str, Any]]:
15
+ """Yield ``(event name, decoded data)`` until the stream ends."""
16
+ name, data, started = "", [], False
17
+ while True:
18
+ raw = stream.readline()
19
+ if not raw:
20
+ if started:
21
+ raise StreamCut("the event stream ended in the middle of an event")
22
+ return
23
+ terminated = raw.endswith(b"\n")
24
+ line = raw.decode("utf-8", errors="replace").rstrip("\r\n")
25
+ if line == "":
26
+ if started:
27
+ text = "\n".join(data)
28
+ try:
29
+ value: Any = json.loads(text)
30
+ except ValueError:
31
+ value = text
32
+ yield name or "message", value
33
+ name, data, started = "", [], False
34
+ continue
35
+ if not terminated:
36
+ raise StreamCut("the event stream ended in the middle of an event")
37
+ if line.startswith(":"):
38
+ continue
39
+ fld, _, value = line.partition(":")
40
+ if value.startswith(" "):
41
+ value = value[1:]
42
+ if fld == "event":
43
+ name, started = value, True
44
+ elif fld == "data":
45
+ data.append(value)
46
+ started = True
cere/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.11"