epochal-api 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.
- epochal/api/__init__.py +41 -0
- epochal/api/_async_client.py +456 -0
- epochal/api/_base.py +200 -0
- epochal/api/_client.py +449 -0
- epochal/api/_errors.py +120 -0
- epochal/api/_types.py +469 -0
- epochal/api/_wire.py +96 -0
- epochal/api/entities.py +1231 -0
- epochal/api/py.typed +0 -0
- epochal/api/time_portal.py +68 -0
- epochal_api-0.1.0.dist-info/METADATA +112 -0
- epochal_api-0.1.0.dist-info/RECORD +14 -0
- epochal_api-0.1.0.dist-info/WHEEL +4 -0
- epochal_api-0.1.0.dist-info/licenses/LICENSE +201 -0
epochal/api/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Client for the Epochal API. Its one module today is the time portal: web search, web fetch and
|
|
2
|
+
sandboxes held to a past instant, so nothing published or crawled after it is used. Each method is
|
|
3
|
+
one API call, retried when that is safe and the failure may pass on its own.
|
|
4
|
+
|
|
5
|
+
from epochal.api import Client
|
|
6
|
+
|
|
7
|
+
with Client() as client:
|
|
8
|
+
found = client.time_portal("2025-03-12").search("fed rate decision")
|
|
9
|
+
for hit in found.results:
|
|
10
|
+
print(hit.title, hit.url)
|
|
11
|
+
|
|
12
|
+
:class:`AsyncClient` does the same with coroutines. The API key comes from ``api_key=`` or
|
|
13
|
+
``EPOCHAL_API_KEY``.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from epochal.api._async_client import AsyncClient
|
|
17
|
+
from epochal.api._base import MAX_WAIT
|
|
18
|
+
from epochal.api._client import Client
|
|
19
|
+
from epochal.api._errors import (
|
|
20
|
+
APIError,
|
|
21
|
+
DecodeError,
|
|
22
|
+
EpochalError,
|
|
23
|
+
InvalidArgumentError,
|
|
24
|
+
MissingApiKeyError,
|
|
25
|
+
TransportError,
|
|
26
|
+
)
|
|
27
|
+
from epochal.api._wire import Duration, Instant
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"MAX_WAIT",
|
|
31
|
+
"APIError",
|
|
32
|
+
"AsyncClient",
|
|
33
|
+
"Client",
|
|
34
|
+
"DecodeError",
|
|
35
|
+
"Duration",
|
|
36
|
+
"EpochalError",
|
|
37
|
+
"Instant",
|
|
38
|
+
"InvalidArgumentError",
|
|
39
|
+
"MissingApiKeyError",
|
|
40
|
+
"TransportError",
|
|
41
|
+
]
|
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
# Generated from _client.py by scripts/unasync.py; edit that file, then run the script.
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import base64
|
|
6
|
+
import dataclasses
|
|
7
|
+
import datetime as dt
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
from types import TracebackType
|
|
10
|
+
from typing import Any, TypeVar
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
from epochal.api import _base as b
|
|
14
|
+
from epochal.api import _wire
|
|
15
|
+
from epochal.api._base import DEFAULT_TIMEOUT, Call, Config
|
|
16
|
+
from epochal.api._errors import EpochalError, InvalidArgumentError
|
|
17
|
+
from epochal.api._types import (
|
|
18
|
+
Category,
|
|
19
|
+
Document,
|
|
20
|
+
ExecOutput,
|
|
21
|
+
FetchResponse,
|
|
22
|
+
FileList,
|
|
23
|
+
FileRange,
|
|
24
|
+
FileStat,
|
|
25
|
+
Network,
|
|
26
|
+
SandboxInfo,
|
|
27
|
+
SandboxList,
|
|
28
|
+
SandboxState,
|
|
29
|
+
SearchResponse,
|
|
30
|
+
)
|
|
31
|
+
from epochal.api._wire import Duration, Instant
|
|
32
|
+
|
|
33
|
+
T = TypeVar("T")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class AsyncClient:
|
|
37
|
+
"""An asyncio Epochal API client: reuses connections. Each API
|
|
38
|
+
module is a handle from it, such as :meth:`time_portal`.
|
|
39
|
+
|
|
40
|
+
Use it as an async context manager, or await :meth:`close`, to release its connections.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
api_key: Defaults to ``EPOCHAL_API_KEY``.
|
|
44
|
+
base_url: Defaults to ``EPOCHAL_BASE_URL``, then ``https://api.epochal.com``.
|
|
45
|
+
max_retries: How many times a call is retried after a dropped connection, a timeout, or
|
|
46
|
+
a 408, 429, 500, 502, 503, 504 or 520-524, with jittered exponential backoff that
|
|
47
|
+
honors ``Retry-After``, sleeping at most 60 s in all. Search, fetch and page are
|
|
48
|
+
billed, so they are retried only on 408, 429 and 503. ``0`` disables retries.
|
|
49
|
+
timeout: For the client this makes; by default 10 s to connect and 85 s to read.
|
|
50
|
+
http_client: An ``httpx.AsyncClient`` to send with, for proxies or custom transports. It is
|
|
51
|
+
not closed by :meth:`close`; redirects are never followed through it.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
*,
|
|
57
|
+
api_key: str | None = None,
|
|
58
|
+
base_url: str | None = None,
|
|
59
|
+
max_retries: int = b.DEFAULT_MAX_RETRIES,
|
|
60
|
+
timeout: httpx.Timeout | float | None = None,
|
|
61
|
+
http_client: httpx.AsyncClient | None = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
self._config = Config(api_key, base_url, max_retries)
|
|
64
|
+
self._owned = http_client is None
|
|
65
|
+
self._http = http_client or httpx.AsyncClient(
|
|
66
|
+
timeout=DEFAULT_TIMEOUT if timeout is None else timeout
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def base_url(self) -> str:
|
|
71
|
+
"""Where requests go."""
|
|
72
|
+
return self._config.base_url
|
|
73
|
+
|
|
74
|
+
def __repr__(self) -> str:
|
|
75
|
+
return f"AsyncClient(base_url={self.base_url!r})"
|
|
76
|
+
|
|
77
|
+
def time_portal(self, as_of: Instant) -> AsyncTimePortal:
|
|
78
|
+
"""The time portal held to ``as_of``: web search, web fetch and sandboxes as they stood
|
|
79
|
+
then. A bare day means its last second, 23:59:59 UTC."""
|
|
80
|
+
return AsyncTimePortal(self, as_of)
|
|
81
|
+
|
|
82
|
+
async def close(self) -> None:
|
|
83
|
+
"""Releases the connections of the client this made; one passed in is left open."""
|
|
84
|
+
if self._owned:
|
|
85
|
+
await self._http.aclose()
|
|
86
|
+
|
|
87
|
+
async def __aenter__(self) -> AsyncClient:
|
|
88
|
+
return self
|
|
89
|
+
|
|
90
|
+
async def __aexit__(
|
|
91
|
+
self, t: type[BaseException] | None, e: BaseException | None, tb: TracebackType | None
|
|
92
|
+
) -> None:
|
|
93
|
+
await self.close()
|
|
94
|
+
|
|
95
|
+
async def _send(self, call: Call[T]) -> T:
|
|
96
|
+
slept, attempt = 0.0, 0
|
|
97
|
+
while True:
|
|
98
|
+
attempt += 1
|
|
99
|
+
try:
|
|
100
|
+
return await self._attempt(call, retried=attempt > 1)
|
|
101
|
+
except EpochalError as e:
|
|
102
|
+
wait = self._config.backoff(call, e, attempt, slept)
|
|
103
|
+
if wait is None:
|
|
104
|
+
raise
|
|
105
|
+
await asyncio.sleep(wait)
|
|
106
|
+
slept += wait
|
|
107
|
+
|
|
108
|
+
async def _attempt(self, call: Call[T], *, retried: bool) -> T:
|
|
109
|
+
try:
|
|
110
|
+
request = self._config.request(self._http, call)
|
|
111
|
+
response = await self._http.send(request, follow_redirects=False)
|
|
112
|
+
except httpx.HTTPError as e:
|
|
113
|
+
raise b.transport_error(e) from e
|
|
114
|
+
return b.result(call, response, retried=retried)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class AsyncTimePortal:
|
|
118
|
+
"""The time portal held to one instant, from :meth:`AsyncClient.time_portal`: search, fetch and
|
|
119
|
+
new boxes are held to :attr:`as_of`. Calls on an existing box take its id, and the box keeps
|
|
120
|
+
the instant it was made with. Each call is sent through the client, with its connections and
|
|
121
|
+
retries."""
|
|
122
|
+
|
|
123
|
+
__slots__ = ("_as_of", "_client")
|
|
124
|
+
|
|
125
|
+
def __init__(self, client: AsyncClient, as_of: Instant) -> None:
|
|
126
|
+
self._client = client
|
|
127
|
+
self._as_of = _wire.instant(as_of, day_end=True)
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def as_of(self) -> dt.datetime:
|
|
131
|
+
"""The instant search, fetch and new boxes are held to, UTC."""
|
|
132
|
+
return self._as_of
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def _headers(self) -> dict[str, str]:
|
|
136
|
+
return b.as_of(self._as_of)
|
|
137
|
+
|
|
138
|
+
def __repr__(self) -> str:
|
|
139
|
+
return f"AsyncTimePortal({self._client!r}, as_of={self.as_of.isoformat()!r})"
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def client(self) -> AsyncClient:
|
|
143
|
+
"""The client its calls go through."""
|
|
144
|
+
return self._client
|
|
145
|
+
|
|
146
|
+
async def _send(self, call: Call[T]) -> T:
|
|
147
|
+
return await self._client._send(
|
|
148
|
+
dataclasses.replace(call, path=f"{b.TIME_PORTAL}{call.path}")
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
async def search(
|
|
152
|
+
self,
|
|
153
|
+
query: str,
|
|
154
|
+
*,
|
|
155
|
+
num_results: int | None = None,
|
|
156
|
+
domains: Sequence[str] = (),
|
|
157
|
+
exclude_domains: Sequence[str] = (),
|
|
158
|
+
languages: Sequence[str] = (),
|
|
159
|
+
published_after: Instant | None = None,
|
|
160
|
+
categories: Sequence[Category | str] = (),
|
|
161
|
+
include_text: bool = False,
|
|
162
|
+
extra_body: Mapping[str, Any] | None = None,
|
|
163
|
+
) -> SearchResponse:
|
|
164
|
+
"""Web search as it would have answered at :attr:`as_of`.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
num_results: 1 to 10; the server defaults to 10.
|
|
168
|
+
domains: Only pages from these sites, subdomains included.
|
|
169
|
+
exclude_domains: Never pages from these sites, subdomains included.
|
|
170
|
+
languages: Preferred result languages as BCP 47 tags, most preferred first.
|
|
171
|
+
published_after: Only pages published at or after this instant.
|
|
172
|
+
categories: Only pages in these categories; empty searches everything. A name
|
|
173
|
+
this version doesn't list is sent as given.
|
|
174
|
+
include_text: Also return each page's full text.
|
|
175
|
+
extra_body: Fields this version doesn't model, sent in the body as given.
|
|
176
|
+
"""
|
|
177
|
+
body = b.compact(
|
|
178
|
+
query=query,
|
|
179
|
+
num_results=num_results,
|
|
180
|
+
domains=list(domains),
|
|
181
|
+
exclude_domains=list(exclude_domains),
|
|
182
|
+
languages=list(languages),
|
|
183
|
+
published_after=None
|
|
184
|
+
if published_after is None
|
|
185
|
+
else _wire.instant_param(published_after),
|
|
186
|
+
categories=[str(c) for c in categories],
|
|
187
|
+
include_text=include_text or None,
|
|
188
|
+
) | dict(extra_body or {})
|
|
189
|
+
parse = b.json(SearchResponse.from_json)
|
|
190
|
+
return await self._send(
|
|
191
|
+
Call("POST", "/search", parse, headers=self._headers, json=body, billed=True)
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
async def fetch(
|
|
195
|
+
self,
|
|
196
|
+
url: str,
|
|
197
|
+
*,
|
|
198
|
+
max_characters: int | None = None,
|
|
199
|
+
extra_body: Mapping[str, Any] | None = None,
|
|
200
|
+
) -> FetchResponse:
|
|
201
|
+
"""One page as it read at :attr:`as_of`, as markdown with its metadata. A page that could
|
|
202
|
+
not be read is returned, with ``status`` :attr:`PageStatus.ERROR`, not raised.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
max_characters: Cut ``content`` to this many characters; the server defaults to
|
|
206
|
+
100,000.
|
|
207
|
+
extra_body: Fields this version doesn't model, sent in the body as given.
|
|
208
|
+
"""
|
|
209
|
+
body = b.compact(url=url, max_characters=max_characters) | dict(extra_body or {})
|
|
210
|
+
parse = b.json(FetchResponse.from_json)
|
|
211
|
+
return await self._send(
|
|
212
|
+
Call("POST", "/fetch", parse, headers=self._headers, json=body, billed=True)
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
async def page(self, url: str) -> Document:
|
|
216
|
+
"""The archived page itself (HTML, PDF, ...) as it stood at :attr:`as_of`, with its type.
|
|
217
|
+
A page that could not be read is returned, with ``status`` :attr:`PageStatus.ERROR`, not
|
|
218
|
+
raised."""
|
|
219
|
+
|
|
220
|
+
def parse(r: httpx.Response) -> Document:
|
|
221
|
+
return Document.from_response(r.content, r.headers)
|
|
222
|
+
|
|
223
|
+
body = {"url": url, "format": "page"}
|
|
224
|
+
return await self._send(
|
|
225
|
+
Call("POST", "/fetch", parse, headers=self._headers, json=body, billed=True)
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
async def create_sandbox(
|
|
229
|
+
self,
|
|
230
|
+
*,
|
|
231
|
+
network: Network | str | None = None,
|
|
232
|
+
vcpus: int | None = None,
|
|
233
|
+
memory_gib: int | None = None,
|
|
234
|
+
timeout: Duration | None = None,
|
|
235
|
+
idle_timeout: Duration | None = None,
|
|
236
|
+
env: Mapping[str, str] | None = None,
|
|
237
|
+
metadata: Mapping[str, str] | None = None,
|
|
238
|
+
apps: Sequence[str] = (),
|
|
239
|
+
idempotency_key: str | None = None,
|
|
240
|
+
) -> SandboxInfo:
|
|
241
|
+
"""Creates a box held to :attr:`as_of`; it is usually still ``CREATING``. Anything not set
|
|
242
|
+
takes the API's default: no network, 1 vCPU, 2 GiB, a 1 h lifetime and a 10 min idle
|
|
243
|
+
timeout. The box boots the newest Ubuntu build dated on or before :attr:`as_of`.
|
|
244
|
+
|
|
245
|
+
Args:
|
|
246
|
+
timeout: The box ends this long after it boots.
|
|
247
|
+
idle_timeout: The box ends after this long with no command running.
|
|
248
|
+
env: In the environment of every command in the box. Values are not logged.
|
|
249
|
+
metadata: Labels kept with the box and returned with it.
|
|
250
|
+
apps: Apps mounted read-only at ``/opt/epochal/bin``, by name. An app is a current
|
|
251
|
+
build, not one as of ``as_of``, so a box that uses one is not strictly held to
|
|
252
|
+
``as_of``.
|
|
253
|
+
idempotency_key: A create repeated with the same key makes one box. Defaults to a
|
|
254
|
+
fresh key, which covers this call's own retries.
|
|
255
|
+
"""
|
|
256
|
+
body = b.compact(
|
|
257
|
+
network=None if network is None else b.known(Network(network), network),
|
|
258
|
+
vcpus=vcpus,
|
|
259
|
+
memory_gib=memory_gib,
|
|
260
|
+
timeout=None if timeout is None else _wire.duration(timeout),
|
|
261
|
+
idle_timeout=None if idle_timeout is None else _wire.duration(idle_timeout),
|
|
262
|
+
env=dict(env or {}),
|
|
263
|
+
metadata=dict(metadata or {}),
|
|
264
|
+
apps=list(apps),
|
|
265
|
+
)
|
|
266
|
+
headers = {**self._headers, **b.idempotent(idempotency_key)}
|
|
267
|
+
parse = b.json(SandboxInfo.from_json)
|
|
268
|
+
return await self._send(Call("POST", b.SANDBOX, parse, headers=headers, json=body))
|
|
269
|
+
|
|
270
|
+
async def get_sandbox(self, sandbox_id: str, *, wait: Duration | None = None) -> SandboxInfo:
|
|
271
|
+
"""A box as it is now, or, with ``wait``, once it leaves ``CREATING`` or ``wait`` passes,
|
|
272
|
+
whichever is first; the API holds a wait for at most :data:`MAX_WAIT`."""
|
|
273
|
+
params = [] if wait is None else [("wait", _wire.duration(wait))]
|
|
274
|
+
parse = b.json(SandboxInfo.from_json)
|
|
275
|
+
return await self._send(
|
|
276
|
+
Call("GET", b.box(sandbox_id), parse, params=params, hold=wait is not None)
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
async def list_sandboxes(
|
|
280
|
+
self,
|
|
281
|
+
*,
|
|
282
|
+
state: SandboxState | str | None = None,
|
|
283
|
+
cursor: str | None = None,
|
|
284
|
+
limit: int | None = None,
|
|
285
|
+
) -> SandboxList:
|
|
286
|
+
"""One page of the account's boxes; ``limit`` is 1 to 100."""
|
|
287
|
+
params = b.params(
|
|
288
|
+
state=None if state is None else b.known(SandboxState(state), state),
|
|
289
|
+
cursor=cursor,
|
|
290
|
+
limit=limit,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
def parse(r: httpx.Response) -> SandboxList:
|
|
294
|
+
j = r.json()
|
|
295
|
+
return SandboxList(
|
|
296
|
+
[SandboxInfo.from_json(s) for s in j["sandboxes"]], j.get("next_cursor")
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
return await self._send(Call("GET", b.SANDBOX, parse, params=params))
|
|
300
|
+
|
|
301
|
+
async def terminate_sandbox(self, sandbox_id: str) -> None:
|
|
302
|
+
"""Ends a box now. Terminating an ended box succeeds."""
|
|
303
|
+
await self._send(Call("DELETE", b.box(sandbox_id), b.none))
|
|
304
|
+
|
|
305
|
+
async def start_exec(
|
|
306
|
+
self,
|
|
307
|
+
sandbox_id: str,
|
|
308
|
+
argv: Sequence[str],
|
|
309
|
+
*,
|
|
310
|
+
env: Mapping[str, str] | None = None,
|
|
311
|
+
cwd: str | None = None,
|
|
312
|
+
timeout: Duration | None = None,
|
|
313
|
+
stdin: bytes = b"",
|
|
314
|
+
stdin_open: bool = False,
|
|
315
|
+
idempotency_key: str | None = None,
|
|
316
|
+
) -> str:
|
|
317
|
+
"""Starts ``argv``, run without a shell, and returns the command's id.
|
|
318
|
+
|
|
319
|
+
Args:
|
|
320
|
+
cwd: The working directory; the image's ``HOME`` by default.
|
|
321
|
+
timeout: Kills the command after this long; 1 h by default.
|
|
322
|
+
stdin: Bytes written to stdin at start, at most 1 MiB.
|
|
323
|
+
stdin_open: Keeps stdin open for :meth:`send_exec_input`; otherwise it is closed
|
|
324
|
+
after ``stdin``.
|
|
325
|
+
idempotency_key: A start repeated with the same key runs the command once.
|
|
326
|
+
"""
|
|
327
|
+
body = b.compact(
|
|
328
|
+
argv=b.check_argv(argv),
|
|
329
|
+
env=dict(env or {}),
|
|
330
|
+
cwd=cwd,
|
|
331
|
+
timeout=None if timeout is None else _wire.duration(timeout),
|
|
332
|
+
stdin_b64=base64.b64encode(stdin).decode() if stdin else None,
|
|
333
|
+
stdin_open=stdin_open or None,
|
|
334
|
+
)
|
|
335
|
+
path, headers = b.box(sandbox_id, "/execs"), b.idempotent(idempotency_key)
|
|
336
|
+
return await self._send(
|
|
337
|
+
Call("POST", path, lambda r: str(r.json()["id"]), headers=headers, json=body)
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
async def read_exec_output(
|
|
341
|
+
self,
|
|
342
|
+
sandbox_id: str,
|
|
343
|
+
exec_id: str,
|
|
344
|
+
*,
|
|
345
|
+
stdout_offset: int = 0,
|
|
346
|
+
stderr_offset: int = 0,
|
|
347
|
+
wait: Duration | None = None,
|
|
348
|
+
max_bytes: int | None = None,
|
|
349
|
+
) -> ExecOutput:
|
|
350
|
+
"""A command's output after the offsets; with ``wait``, held until there is new output,
|
|
351
|
+
the command ends, or ``wait`` passes (at most :data:`MAX_WAIT`)."""
|
|
352
|
+
params = b.params(
|
|
353
|
+
stdout_offset=stdout_offset,
|
|
354
|
+
stderr_offset=stderr_offset,
|
|
355
|
+
wait=None if wait is None else _wire.duration(wait),
|
|
356
|
+
max_bytes=max_bytes,
|
|
357
|
+
)
|
|
358
|
+
path, parse = b.execution(sandbox_id, exec_id, "/output"), b.json(ExecOutput.from_json)
|
|
359
|
+
return await self._send(Call("GET", path, parse, params=params, hold=wait is not None))
|
|
360
|
+
|
|
361
|
+
async def send_exec_input(
|
|
362
|
+
self,
|
|
363
|
+
sandbox_id: str,
|
|
364
|
+
exec_id: str,
|
|
365
|
+
seq: int,
|
|
366
|
+
*,
|
|
367
|
+
data: bytes | None = None,
|
|
368
|
+
eof: bool = False,
|
|
369
|
+
signal: int | None = None,
|
|
370
|
+
) -> int:
|
|
371
|
+
"""Applies one of ``data`` (at most 1 MiB), ``eof`` or ``signal`` as input number ``seq``
|
|
372
|
+
(from 0) and returns the next ``seq``. An input already applied is not applied again; one
|
|
373
|
+
out of order raises :class:`APIError` with the ``next_seq`` the command expects."""
|
|
374
|
+
if (data is not None) + eof + (signal is not None) != 1:
|
|
375
|
+
raise InvalidArgumentError("send exactly one of data, eof or signal")
|
|
376
|
+
body = b.compact(
|
|
377
|
+
seq=seq,
|
|
378
|
+
data_b64=None if data is None else base64.b64encode(data).decode(),
|
|
379
|
+
eof=eof or None,
|
|
380
|
+
signal=signal,
|
|
381
|
+
)
|
|
382
|
+
path = b.execution(sandbox_id, exec_id, "/input")
|
|
383
|
+
return await self._send(Call("POST", path, lambda r: int(r.json()["next_seq"]), json=body))
|
|
384
|
+
|
|
385
|
+
async def stat_file(self, sandbox_id: str, path: str) -> FileStat:
|
|
386
|
+
"""Metadata of ``path``, without following a final symlink."""
|
|
387
|
+
parse = b.json(FileStat.from_json)
|
|
388
|
+
return await self._send(
|
|
389
|
+
Call("GET", b.box(sandbox_id, "/files/stat"), parse, params=[("path", path)])
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
async def list_files(
|
|
393
|
+
self,
|
|
394
|
+
sandbox_id: str,
|
|
395
|
+
path: str,
|
|
396
|
+
*,
|
|
397
|
+
recursive: bool = False,
|
|
398
|
+
cursor: str | None = None,
|
|
399
|
+
limit: int | None = None,
|
|
400
|
+
) -> FileList:
|
|
401
|
+
"""One page of the entries under ``path``; ``limit`` is 1 to 100."""
|
|
402
|
+
params = b.params(
|
|
403
|
+
path=path, recursive="true" if recursive else None, cursor=cursor, limit=limit
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
def parse(r: httpx.Response) -> FileList:
|
|
407
|
+
j = r.json()
|
|
408
|
+
return FileList([FileStat.from_json(e) for e in j["entries"]], j.get("next_cursor"))
|
|
409
|
+
|
|
410
|
+
return await self._send(Call("GET", b.box(sandbox_id, "/files/list"), parse, params=params))
|
|
411
|
+
|
|
412
|
+
async def read_file(
|
|
413
|
+
self, sandbox_id: str, path: str, *, offset: int = 0, length: int | None = None
|
|
414
|
+
) -> FileRange:
|
|
415
|
+
"""Bytes of ``path`` from ``offset``: ``length`` of them, or as many as the box sends in
|
|
416
|
+
one call (16 MiB). A read at or past the end returns no bytes rather than raising."""
|
|
417
|
+
if offset < 0 or (length is not None and length <= 0):
|
|
418
|
+
raise InvalidArgumentError(
|
|
419
|
+
"a read starts at offset >= 0 and asks for at least one byte"
|
|
420
|
+
)
|
|
421
|
+
last = "" if length is None else str(offset + length - 1)
|
|
422
|
+
|
|
423
|
+
def parse(r: httpx.Response) -> FileRange:
|
|
424
|
+
first, total = b.content_range(r.headers.get("content-range"))
|
|
425
|
+
if r.status_code == httpx.codes.REQUESTED_RANGE_NOT_SATISFIABLE:
|
|
426
|
+
return FileRange(offset, b"", total)
|
|
427
|
+
if r.status_code == httpx.codes.PARTIAL_CONTENT:
|
|
428
|
+
return FileRange(offset if first is None else first, r.content, total)
|
|
429
|
+
if r.status_code == httpx.codes.OK:
|
|
430
|
+
return FileRange(0, r.content, len(r.content))
|
|
431
|
+
raise ValueError(f"{path}: a range read answered HTTP {r.status_code}")
|
|
432
|
+
|
|
433
|
+
def accept(r: httpx.Response) -> bool:
|
|
434
|
+
return r.is_success or r.status_code == httpx.codes.REQUESTED_RANGE_NOT_SATISFIABLE
|
|
435
|
+
|
|
436
|
+
headers = {"range": f"bytes={offset}-{last}"}
|
|
437
|
+
url = b.box(sandbox_id, "/files")
|
|
438
|
+
return await self._send(Call("GET", url, parse, [("path", path)], headers, accept=accept))
|
|
439
|
+
|
|
440
|
+
async def write_file(
|
|
441
|
+
self, sandbox_id: str, path: str, data: bytes, *, offset: int = 0
|
|
442
|
+
) -> FileStat:
|
|
443
|
+
"""Writes ``data`` (at most 8 MiB) into ``path`` at ``offset`` and returns the file after.
|
|
444
|
+
Offset 0 replaces the file; a later offset writes into it, zero-filling any gap."""
|
|
445
|
+
params = [("path", path), ("offset", str(offset))]
|
|
446
|
+
headers = {"content-type": "application/octet-stream"}
|
|
447
|
+
parse = b.json(FileStat.from_json)
|
|
448
|
+
url = b.box(sandbox_id, "/files")
|
|
449
|
+
return await self._send(
|
|
450
|
+
Call("PUT", url, parse, params, headers, content=bytes(data), hold=True)
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
async def remove_file(self, sandbox_id: str, path: str, *, recursive: bool = False) -> None:
|
|
454
|
+
"""Removes ``path``; a directory only with ``recursive``."""
|
|
455
|
+
params = b.params(path=path, recursive="true" if recursive else None)
|
|
456
|
+
await self._send(Call("DELETE", b.box(sandbox_id, "/files"), b.none, params=params))
|