Metadata-Version: 2.4
Name: impulse-compute
Version: 0.1.1
Summary: The ImpulseCompute SDK: sandboxes, commands, files and previews over the Compute API.
Project-URL: Homepage, https://github.com/ImpulseHosting/impulse-compute-cli/tree/main/sdk/python
Project-URL: Repository, https://github.com/ImpulseHosting/impulse-compute-cli
License-Expression: MIT
License-File: LICENSE
Keywords: code-execution,compute,impulse,microvm,sandbox
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.27
Requires-Dist: typing-extensions>=4.7
Provides-Extra: dev
Requires-Dist: mypy<2,>=1.10; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# impulse-compute

The Python SDK for ImpulseCompute: sandboxes (each a microVM of its own), the commands they run, their files and the
ports they expose. Python 3.9 and later, sync (`Compute`) and async (`AsyncCompute`).

```sh
pip install impulse-compute
```

## Quickstart

```python
from impulse_compute import Compute

compute = Compute()  # the key from COMPUTE_API_KEY

sbx = compute.sandboxes.create(template="node", ttl="30m")
try:
    r = sbx.commands.run("node -e 'console.log(6 * 7)'")
    print(r.stdout)  # 42

    # A path is absolute, or relative to the user's home (where commands run by default).
    sbx.files.write("hello.txt", "hi\n")
    print(sbx.files.read_text("hello.txt"))  # hi
finally:
    sbx.destroy()
```

The async client is the same, awaited:

```python
from impulse_compute import AsyncCompute

async with AsyncCompute() as compute:
    sbx = await compute.sandboxes.create(template="base")
    r = await sbx.commands.run("uname -a")
    await sbx.destroy()
```

A sandbox made without a firewall policy reaches no network at all: make it with one that allows what it needs
(`firewall_policy`).

## The client

`Compute(...)` takes:

- `api_key`: the API key, else `COMPUTE_API_KEY`;
- `base_url`: the API's address, else `COMPUTE_API_URL`, else `https://api.impulse.host/compute/v1` (Impulse Hosting's,
  which opens with its beta; a hosting provider running ImpulseCompute has an address of its own);
- `timeout`: how long a call waits for its answer, in seconds (60 by default);
- `max_retries`: how many times a call that failed for a passing reason is tried again (2 by default);
- `http_client`, `headers`: an httpx client of your own, and headers for every call.

Close it with `compute.close()`, or use it as a context manager.

Calls are retried when no answer came (a connection refused or reset, a timeout), on `429`, `502`, `503` and `504`
unless the API marks the error not retryable (a quota reached is not), and on any error it marks retryable. A retry
waits 0.5 s doubling (with jitter, up to 8 s), or as long as `Retry-After` says when that is a minute or less; a longer
wait is left to you, the error's `retry_after` saying how long. Every call that changes something carries an `Idempotency-Key`, the same on each of its retries,
so a retry never applies a change twice; pass `idempotency_key` where a helper takes one to make a change once across
your own retries too.

## Sandboxes

```python
sbx = compute.sandboxes.create(
    template="base",  # or node, deno, or a template of yours
    name="build-42",
    ttl="1h",  # or seconds, or a timedelta
    idle_suspend="10m",  # False never suspends it
    vcpu=2,
    memory_mb=2048,
    env={"APP_ENV": "production"},
    secrets=["DATABASE_URL"],
    firewall_policy="open",
    labels={"team": "data"},
)

again = compute.sandboxes.get("build-42")
for s in compute.sandboxes.list(label="team=data"):
    print(s.id, s.state, s.expires_at)

sbx.suspend()  # memory and disk saved, memory released
sbx.resume()
sbx.extend("2h")
sbx.destroy()
```

## Commands

```python
# One call that waits: a string runs under /bin/sh -c, a list as it is.
r = sbx.commands.run(["python3", "-c", "print('hi')"], cwd="/srv", timeout=60)
r.exit_code, r.stdout, r.stderr, r.truncated

# Output as it arrives, and input.
sbx.commands.run("pytest", on_stdout=print, on_stderr=print)
sbx.commands.run("wc -c", stdin="hello")

# A non-zero exit is the result's to say; check makes it a CommandExitError.
sbx.commands.run("make", check=True)

# Started, then written to and read as it runs.
sh = sbx.commands.start("bash", stdin=True, tty={"rows": 40, "cols": 120})
sh.send_stdin("ls\nexit\n")
for ev in sh:
    if ev.type == "stdout":
        print(ev.data.decode(), end="")
result = sh.wait()

# One that runs on until it is signalled.
server = sbx.commands.start("python3 -m http.server 8080", on_stdout=print)
server.kill("INT")
server.wait()
```

A command's output is read once. A stream cut short (a connection lost, the sandbox suspended) is resumed after the
last record read; output missed meanwhile makes the result `truncated`. A result keeps up to 1 MiB of each stream;
the callbacks and the events see all of it. Reading a command's output resumes its sandbox if it was suspended, as any
call that reaches the sandbox does; `disconnect()` stops reading (the command runs on), and a later read resumes.

## Files

```python
sbx.files.write("/srv/data.json", json.dumps(data))  # text, bytes, a binary file or an iterator of bytes
data = sbx.files.read("/srv/out.bin")
text = sbx.files.read_text("/srv/out.txt")
for chunk in sbx.files.read_stream("/var/log/app.log"):
    ...

listing = sbx.files.list("/srv")  # entries, sorted by name
info = sbx.files.stat("/srv/data.json")
sbx.files.exists("/srv/missing")  # False
sbx.files.mkdir("/srv/a/b")  # its missing parents too
sbx.files.rename("/srv/a", "/srv/c")
sbx.files.remove("/srv/c", recursive=True)
```

A file is written whole: a reader never sees half of it. Text and bytes carry their SHA-256, so the sandbox refuses a
body changed on the way. A refusal by the sandbox (a path not found, permission denied) is a `ComputeError` whose
`path_reason()` says why.

## Ports

```python
import httpx

app = sbx.commands.start("python3 -m http.server 8080")
preview = sbx.ports.expose(8080)  # token-gated
# The app may take a moment to listen: until it does, the preview answers an error.
httpx.get(preview.url, headers=preview.headers())  # Impulse-Preview-Token
public = sbx.ports.expose(3000, public=True)  # anyone with the URL: for a browser or an iframe
rotated = sbx.ports.rotate_token(8080, token_ttl="1h")
sbx.ports.unexpose(8080)
```

A private port's access token is in the answer that minted it only. When that answer is lost and a retry is told the
token was already issued, the SDK rotates the token and returns the new one.

## Templates and operations

```python
tpl = compute.templates.build("py-data", image="python:3.12-slim")
sbx = compute.sandboxes.create(template="py-data")

# A call that starts work returns an Operation; wait for it.
op = compute.api.restart_service("api")
compute.operations.wait(op)  # OperationFailedError, OperationTimeoutError
```

## Cloaked secrets

A secret set with a `cloak` reaches your sandboxes and services as a placeholder. The egress proxy outside the VM
puts the value in the named request headers (`Authorization` unless you say otherwise) of HTTPS requests to the hosts
you named, and nowhere else.

```python
compute.api.set_env_var("OPENAI_API_KEY", {"value": "sk-...", "secret": True, "cloak": {"hosts": ["api.openai.com"]}})
sbx = compute.sandboxes.create(template="node", secrets=["OPENAI_API_KEY"], firewall_policy="open")
# In the sandbox, OPENAI_API_KEY is impulse_cloaked_...; a request to api.openai.com carries the key.
```

The workload trusts the proxy through a certificate authority given to it at its start (`SSL_CERT_FILE`,
`REQUESTS_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS` and the like are set for you). A value a host echoes in a response (as it
was sent, as JSON writes it, or percent-encoded) is turned back into the placeholder; one echoed in another form
(base64, a part of it) would still show the workload the value: name only the hosts the secret is for, and cloak a
random key.

## Scoped sandboxes

A sandbox can be granted a prefix of one of your per-workload storage bindings, read-only unless you ask for
`read_write` (the API key needs `compute:manage` as well as `compute:sandbox`), and can act as one of your Impulse
Auth users with the access token your Auth service issued that user. It holds no standing key: the AWS SDKs inside it
fetch short-lived keys from the machine that runs it, and it reads the token at `IMPULSE_ACT_AS_TOKEN_URI`.

```python
sbx = compute.sandboxes.create(
    template="node",
    ttl="1h",  # at least as long as the token lasts
    grant={"binding": "agent-data", "prefix": "runs/42/"},
    act_as={"auth_binding": "users", "user_access_token": user_access_token},
)
sbx.grant  # {"binding", "prefix", "access", "generation"}
sbx.act_as  # {"auth_binding", "user_id", "expires_at"}, never the token
sbx.replace_act_as(fresh_token)  # the same user, before the token ends
sbx.drop_act_as()
```

The token is the user's whole credential while it lasts: anything in the sandbox can read it. Require
reauthentication for password changes in every project whose tokens you hand to a sandbox.

## Everything else

`compute.api` has one method per operation of the API, with its types, for what the helpers do not cover: services,
deployments, environment variables, firewall policies and logs.

## Errors

- `ComputeError`: the API answered with an error. It has the `status`, the `code` (`resource_not_found`,
  `quota_exceeded`, …), the `detail`, the `request_id` to quote to support, and the rest of the problem.
- `ComputeConnectionError`: no answer, after the call's retries.
- `OperationFailedError`, `OperationTimeoutError`, `CommandExitError` and `DisconnectedError`.

All of them are `ImpulseComputeError`s.

## Licence

MIT.
