> ## Documentation Index
> Fetch the complete documentation index at: https://docs.snackbase.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Functions

> Deploy sandboxed Python handlers with pinned dependencies on your SnackBase instance

**Functions** let tenants deploy real Python business logic on the SnackBase instance—HTTP-invocable, secret-aware, and dependency-capable—without a separate backend.

## Positioning

| Product | Role |
| - | - |
| Custom Endpoints | No-code HTTP action pipelines |
| Hooks / Workflows | Event/schedule/graph automation |
| Platform `@app.hook.*` | Trusted code shipped with the server |
| **Functions** | Tenant-deployed sandboxed Python FaaS |

## Invoke URL

```
POST /api/v1/f/{account_slug}/{function_slug}
```

Optional path suffix is supported: `/api/v1/f/{account_slug}/{slug}/sub/path`.

`auth_required` defaults to **true** (JWT / API key for the same account). Public webhooks set `auth_required=false`.

## Handler contract

```python theme={null}
from snackbase_fn import Request, Response

def handler(req: Request) -> Response:
    return Response.json({"ok": True, "user": req.auth.user_id})
```

Async handlers are supported. Baseline packages in every env: `snackbase_fn` and `httpx`.

## Dependencies

Declare exact pins on deploy (`openai==1.66.0`). Unpinned names, ranges, and git/URL installs are rejected. The server runs **uv** at deploy time; invoke is offline (no PyPI on the hot path).

Installing a package can execute code on the host, so deploys are fail-closed by default:

* `SNACKBASE_FUNCTION_DEPENDENCY_MODE` defaults to `allowlist`. Only packages named in `SNACKBASE_FUNCTION_DEPENDENCY_ALLOWLIST` install; anything else is rejected with HTTP 400. Set the mode to `open_pinned` to accept any pinned PyPI package — that lets any account admin install arbitrary packages on the instance.
* Pins install from wheels only (`--only-binary`), so a source distribution's build backend never runs. A package with no wheel for the runtime platform fails to deploy.
* The install subprocess runs with a scrubbed environment: it inherits proxy, CA and cache settings but never the server's `SNACKBASE_*` secrets.

## Invoke sandbox

Each invocation runs in a subprocess the kernel confines:

* **Filesystem** — [Landlock](https://docs.kernel.org/userspace-api/landlock.html) restricts the child to the interpreter, its own function env (read-only) and its per-invoke work directory (read-write). Other tenants' envs, `sb_data/` and the database file are unreachable. Landlock needs no extra container capabilities and no seccomp exemption, but it does need **Linux 5.13+**.
* **Resources** — `setrlimit` bounds address space (`SNACKBASE_FUNCTION_MEMORY_LIMIT_MB`, default 512), CPU time and open file descriptors, on top of the existing wall-clock timeout.
* **Egress** — the SSRF policy is applied at `socket.connect`, so it covers raw sockets and not just `httpx`/`urllib`.

`SNACKBASE_FUNCTION_SANDBOX_MODE` controls this:

| Value | Behaviour |
| - | - |
| `auto` (default) | Confine where the kernel supports it. In production this is treated as `required`. |
| `required` | Refuse to invoke when confinement cannot be established. |
| `disabled` | Run handlers unconfined. Only appropriate for single-tenant deployments where the tenant is already trusted with the host. |

On a kernel without Landlock — including macOS development machines — `auto` runs handlers unconfined and logs a warning at startup. A production deployment on such a kernel refuses invokes rather than degrading silently.

## Dual client

| Helper | Scope |
| - | - |
| `get_client()` | Caller-scoped token (respects collection rules) |
| `get_admin_client()` | Service token gated by function **grants** (deny-by-default) |

Encrypted collection fields stay redacted unless the function has both:

* grant `records.secrets.read:<collection>`
* API-key scope `records:secrets:read`

## Secrets

Function secrets are Fernet-encrypted, write-only on list, and injected as env vars into the child process. Names cannot start with `SNACKBASE_`.

## Isolation & limits

* Per-version venv + `python -I` subprocess
* Timeout kill (default 30s) → HTTP 504 / status `timeout`
* Per-account and global concurrency caps → 429
* SSRF egress policy: deny loopback, RFC1918, link-local, metadata, ports 25/587
* Nested invoke budget via `X-Function-Depth`

## Management API

| Method | Path | Description |
| - | - | - |
| POST | `/api/v1/functions` | Create |
| GET | `/api/v1/functions` | List |
| GET | `/api/v1/functions/{slug}` | Get |
| PATCH | `/api/v1/functions/{slug}` | Update / lifecycle |
| DELETE | `/api/v1/functions/{slug}` | Soft-delete |
| POST | `/api/v1/functions/{slug}/deploy` | Deploy files + pins |
| GET | `/api/v1/functions/{slug}/executions` | Execution log |
| GET | `/api/v1/functions/{slug}/versions` | Version history |
| POST | `/api/v1/functions/{slug}/versions/{id}/activate` | Rollback |
| PATCH | `/api/v1/functions/{slug}/grants` | Admin-client grants |
| GET | `/api/v1/functions/{slug}/stats` | Invoke stats |
| POST | `/api/v1/functions/{slug}/test` | Management test invoke |
| \* | `/api/v1/function-secrets` | Secrets CRUD (values write-only) |

Manage mutations require account admin (or `functions:write` / `secrets:write` scopes).

## Automation

Hooks, Workflows, and Custom Endpoints support action type `invoke_function`:

```json theme={null}
{ "type": "invoke_function", "slug": "hello", "payload": { "x": 1 } }
```

## SDK & CLI

```ts theme={null}
const { data } = await client.functions.invoke('hello', { body: { name: 'Ada' } });
```

```bash theme={null}
snackbase functions list
snackbase functions deploy hello --dir ./snackbase/functions/hello
snackbase functions logs hello
snackbase functions serve hello
```

## Admin UI

Instance Admin → **Functions** (instance Admin only; not hosted in Cloud Console):

* **Code tab** — CodeMirror multi-file Python editor with line numbers, syntax highlighting, search, and folding. Switching files keeps each file’s content, cursor, selection, scroll position, and undo history.
* **File rules** — Relative POSIX paths only (for example `utils.py`, `lib/formatters.py`). Absolute paths, `..` segments, backslashes, empty names, and names longer than 255 characters are rejected in the UI and again on deploy.
* **Entrypoint** — Marked with ★. Use **Set as entrypoint** before removing the current entrypoint file. At least one source file is required.
* **Dependencies panel** — Exact pins (`package==version`) are the source of truth. The editor always generates a read-only `requirements.txt` from that list (including an empty file when there are no pins). Do not edit `requirements.txt` in the Code tab.
* **Deploy is save** — Source is persisted only when you deploy. A successful deploy creates an immutable Function version and clears the unsaved-changes indicator. Leaving or reloading with local edits prompts for confirmation; un-deployed edits exist only in the browser session and can be lost if you confirm leave.
* **Syntax preflight** — Deploy parses every `.py` / `.pyi` file before installing dependencies. Syntax errors return HTTP 400 with file, line, and column. Invalid imports still pass preflight; handler-contract checks remain on test/invoke.
* Also: test sheet, executions, versions/rollback, grants, and secrets.

There is no Python language-server / IntelliSense and no SQL query editor in this surface. The shared editor shell is language-adaptable for a future SQL Editor (dialect + collection schema completion) without replacing Function deploy or dirty-state behavior.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.