Metadata-Version: 2.4
Name: ebtp
Version: 0.4.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Typing :: Typed
License-File: LICENSE-MIT
License-File: LICENSE-APACHE
Summary: Python client for ebtp: content-defined chunking, chunk-level dedup and byte-range reads over HTTP(S)
Keywords: dedup,chunking,storage,client,http
Home-Page: https://ebtp.dev
Author: 4thel00z
License-Expression: MIT OR Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://ebtp.dev
Project-URL: Repository, https://github.com/4thel00z/ebtp

# ebtp for Python

Python client for [ebtp](https://ebtp.dev): uploads files with content-defined chunking and
chunk-level dedup, and reads them back whole or by byte range over HTTP or HTTPS. The package
wraps the Rust client `ebtp-client`, so Python runs the same pipeline: file ids are the ids the
Rust client computes for the same bytes, and every downloaded chunk is checked against its hash.

## Install

```sh
pip install ebtp
```

Wheels are abi3 and work on CPython 3.10 and newer (Linux x86_64 and aarch64, macOS arm64).
Other platforms build from the source distribution, which needs a Rust toolchain.

## Blocking client

```python
import ebtp

client = ebtp.Client("http://127.0.0.1:8080")

id = client.put("model.safetensors")
ids = client.put_all(["a.bin", "b.bin"])
other = client.put_bytes(b"bytes already in memory")

size = client.len(id)
data = client.get(id)
client.get_into(id, "copy.safetensors")
files = client.get_all(ids)
```

Calls release the interpreter while they read, hash, compress and transfer, so threads can run
uploads and downloads side by side.

Ctrl-C, or any signal handler that raises, stops a call on the main thread within about 0.1 s:
no new requests start, and once the exception is raised the call writes nothing more to its
target. Requests already sent, at most the pipeline's `concurrency` of them, finish in the
background. A write to the target that is running when the signal arrives is finished first, so
a target on a stalled file system or a FIFO nobody reads holds up the stop.

## asyncio client

```python
import asyncio
import ebtp


async def main() -> None:
    client = ebtp.AsyncClient("http://127.0.0.1:8080")
    id = await client.put("model.safetensors")
    head = await client.get(id, 0, 1 << 20)
    ids = await asyncio.gather(*(client.put(p) for p in ["a.bin", "b.bin"]))


asyncio.run(main())
```

Both clients take the same arguments and have the same methods; `AsyncClient` returns asyncio
futures that a Tokio runtime inside the extension drives. Cancelling one, for example through
`asyncio.wait_for`, starts no new requests, and the call writes nothing more to its target after
the awaiting task sees the cancellation; as with Ctrl-C, a write that is running is finished
first, on the event loop's thread. `get_into` calls the `write` method of a file object on the
event loop, so objects bound to the loop can be targets. If the loop stops running before such a
call is done, the call fails with `FileError` and writes nothing more.

Downloads waiting on the network hold no threads, so many of them can run at once from asyncio
tasks or from threads.

## Processes

A client works in a process forked after it was used, such as a `multiprocessing` or PyTorch
`DataLoader` worker: the child opens its own connections and runs its own Tokio runtime. The
child cannot free the parent's runtime and connections, so each forked child keeps a fixed
amount of the parent's memory and file descriptors, and the parent's connections stay open
until its children exit. Forking while a call runs on another thread is not supported; CPython
warns about forking a process with threads for the same reason.

## Pipeline

The second argument is the pipeline spec, `"v1"` by default. Uploads with different pipelines
give different file ids for the same bytes; any pipeline reads any file.

```python
client = ebtp.Client("http://127.0.0.1:8080", "v1,small_put=4M")
```

## Credentials

A static bearer token, for example one from an OIDC provider:

```python
client = ebtp.Client(url, credentials=ebtp.Token("eyJ..."))
```

An API key, traded at the server for tokens of one namespace and scope (`"read"` or `"write"`).
Tokens are replaced shortly before they expire, and a token the server refuses is replaced once:

```python
client = ebtp.Client(url, credentials=ebtp.ApiKey(key, "team-a", "write"))
```

## HTTPS with a custom root

HTTPS verifies servers against the Mozilla root store bundled with the client (webpki-roots),
not the operating system's store. To also trust a private CA, pass its PEM certificate:

```python
from pathlib import Path

client = ebtp.Client(
    "https://ebtp.internal:8443",
    root_certificate=Path("ca.pem").read_text(),
)
```

## Timeout

`timeout` (seconds) bounds connecting and each read of a response; a transfer that keeps making
progress is not cut off.

```python
client = ebtp.Client(url, timeout=30)
```

## Range reads

`get(id, start, end)` returns bytes `[start, end)`; `end` defaults to the file length.
`get_into(id, target, start, end)` writes them to a path or to a writable binary file object
and returns the byte count. A path is created or truncated only once the server has confirmed
the range; a read that fails after that, for example on a hash mismatch or a dropped
connection, leaves the file truncated or partly written. `ebtp.Target`, `ebtp.StrPath` and
`ebtp.BinaryWriter` name the accepted types.

```python
import io

size = client.len(id)
tail = client.get(id, max(size - 4096, 0))
buffer = io.BytesIO()
client.get_into(id, buffer, 0, 1 << 20)
```

## Errors

Every error is an `ebtp.EbtpError`. Branch on its subclasses:

| Class | When |
| --- | --- |
| `NotFound` | no file has this id |
| `Unauthorized` | credentials missing, refused, or not allowed to do this |
| `InvalidRange` | the range ends past the end of the file, starts after its end or is negative |
| `IntegrityError` | a downloaded chunk does not match its hash or does not decode |
| `TransportError` | the server could not be reached, or a request or transfer failed or timed out |
| `ServerError` | the server answered with an unexpected status or body |
| `ConfigError` | invalid URL, pipeline, certificate, credentials or timeout |
| `FileError` | a local file could not be read or written, or changed during upload |

An exception raised by a file object passed to `get_into` propagates unchanged. A buffer the
interpreter cannot allocate raises `MemoryError`.

`InvalidRange` carries `start`, `end` and `len` (the file length) when the server reported them,
and None otherwise:

```python
try:
    data = client.get(id, 0, 1 << 30)
except ebtp.InvalidRange as error:
    data = client.get(id, 0, error.len)
```

## License

MIT OR Apache-2.0, at your option.

