vlambda 0.3.0__tar.gz → 1.0.0__tar.gz

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.
Files changed (55) hide show
  1. vlambda-1.0.0/PKG-INFO +738 -0
  2. vlambda-1.0.0/README.md +726 -0
  3. {vlambda-0.3.0 → vlambda-1.0.0}/pyproject.toml +13 -1
  4. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/__init__.py +6 -0
  5. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/__main__.py +334 -36
  6. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/assets.py +10 -2
  7. vlambda-1.0.0/python/vlambda/async_support.py +46 -0
  8. vlambda-1.0.0/python/vlambda/auth.py +300 -0
  9. vlambda-1.0.0/python/vlambda/backup.py +469 -0
  10. vlambda-1.0.0/python/vlambda/broker.py +467 -0
  11. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/cache.py +42 -18
  12. vlambda-1.0.0/python/vlambda/capabilities.py +204 -0
  13. vlambda-1.0.0/python/vlambda/cli.py +386 -0
  14. vlambda-1.0.0/python/vlambda/cron.py +144 -0
  15. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/dbpool.py +5 -1
  16. vlambda-1.0.0/python/vlambda/egress_store.py +114 -0
  17. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/env.py +79 -12
  18. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/forkd.py +16 -11
  19. vlambda-1.0.0/python/vlambda/kv_store.py +313 -0
  20. vlambda-1.0.0/python/vlambda/lifecycle.py +70 -0
  21. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/metrics.py +49 -21
  22. vlambda-1.0.0/python/vlambda/openapi.py +226 -0
  23. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/packages.py +51 -5
  24. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/pool.py +77 -25
  25. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/project.py +142 -28
  26. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/request.py +8 -2
  27. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/reset.py +84 -3
  28. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/response.py +12 -1
  29. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/runner.py +49 -8
  30. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/sandbox.py +3 -2
  31. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/sandbox_os.py +146 -33
  32. vlambda-1.0.0/python/vlambda/schedules.py +588 -0
  33. vlambda-1.0.0/python/vlambda/schema.py +56 -0
  34. vlambda-1.0.0/python/vlambda/selfcheck.py +48 -0
  35. vlambda-1.0.0/python/vlambda/sqlite_compat.py +38 -0
  36. vlambda-1.0.0/python/vlambda/tasks.py +435 -0
  37. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/transfer.py +3 -0
  38. vlambda-1.0.0/python/vlambda/version.py +3 -0
  39. {vlambda-0.3.0 → vlambda-1.0.0}/src/vlambda_native.v +1353 -1223
  40. vlambda-1.0.0/tests/test_unit.py +1774 -0
  41. vlambda-1.0.0/tests/test_vlambda.py +2108 -0
  42. {vlambda-0.3.0 → vlambda-1.0.0}/vcraft.toml +1 -1
  43. vlambda-0.3.0/PKG-INFO +0 -392
  44. vlambda-0.3.0/README.md +0 -380
  45. vlambda-0.3.0/python/vlambda/auth.py +0 -91
  46. vlambda-0.3.0/python/vlambda/cli.py +0 -181
  47. vlambda-0.3.0/python/vlambda/tasks.py +0 -206
  48. vlambda-0.3.0/tests/test_unit.py +0 -642
  49. vlambda-0.3.0/tests/test_vlambda.py +0 -1119
  50. {vlambda-0.3.0 → vlambda-1.0.0}/LICENSE +0 -0
  51. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/py.typed +0 -0
  52. {vlambda-0.3.0 → vlambda-1.0.0}/python/vlambda/shared_cache.py +0 -0
  53. {vlambda-0.3.0 → vlambda-1.0.0}/tests/conftest.py +0 -0
  54. {vlambda-0.3.0 → vlambda-1.0.0}/v.mod +0 -0
  55. {vlambda-0.3.0 → vlambda-1.0.0}/vcraft_build.py +0 -0
vlambda-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,738 @@
1
+ Metadata-Version: 2.1
2
+ Name: vlambda
3
+ Version: 1.0.0
4
+ Summary: An ASGI-like server for Python lambdas, written in V.
5
+ License: MIT
6
+ Requires-Python: >=3.14
7
+ Classifier: Programming Language :: Other
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: Implementation :: CPython
10
+ Description-Content-Type: text/markdown
11
+
12
+ # vlambda
13
+
14
+ An ASGI-like server for Python lambdas, written in V. Uses [vcraft](https://github.com/rroblf01/vcraft) for the V↔Python bridge.
15
+
16
+ **Live at:** https://vlambda.ricardorobles.es
17
+
18
+ ## What is vlambda?
19
+
20
+ vlambda lets you write Python functions ("lambdas") and serve them as HTTP endpoints. It's like AWS Lambda, but self-hosted, with no cold start in persistent mode and a fresh sandbox per invocation in Docker (~10-20 ms p50).
21
+
22
+ ```python
23
+ def handler(request):
24
+ return {"msg": "hello", "path": request.path}
25
+ ```
26
+
27
+ POST that code to `/vlambda` and it becomes `GET /f/<slug>` instantly.
28
+
29
+ ## Features
30
+
31
+ - **No cold starts in persistent mode** — Docker uses a fresh Landlock process per invocation, which adds a small startup cost
32
+ - **Fast** — ~3,000 req/s in-process; the Docker fork sandbox adds a few milliseconds per invocation
33
+ - **Auth** — JWT-based authentication with per-user ownership
34
+ - **Web UI** — Dashboard for managing lambdas, code editor, metrics
35
+ - **Async invocation** — Fire-and-forget with task tracking
36
+ - **KV store** — per-lambda typed key/value state with TTL and atomic increments
37
+ - **Controlled egress** — allow-listed HTTPS calls from the sandbox via `request.fetch`
38
+ - **Schedules** — persistent five-field cron jobs with timezones, run history and a single leader
39
+ - **OpenAPI** — owner-scoped spec, metadata editor and CLI export
40
+ - **Sandbox** — Landlock + seccomp in Docker, plus restricted Python builtins and blocked modules
41
+ - **Metrics** — Prometheus-compatible + Chart.js dashboard
42
+ - **Per-lambda method** — GET, POST, PUT, PATCH, DELETE
43
+ - **Naming** — Human-readable names for lambdas
44
+ - **Multi-file projects** — ZIP uploads, file editor, `requirements.txt`/`pyproject.toml`
45
+ - **Versions and aliases** — rollback and `prod`/`staging` aliases
46
+ - **PyPI packages** — install per lambda/project from the UI
47
+ - **Persistent metrics and logs** — survive restarts, queryable by slug/name
48
+ - **CORS** — opt-in per-origin CORS for `/f/` responses, with `OPTIONS` preflight
49
+ - **Static files** — projects serve `index.html`, CSS, JS and assets at `/f/<slug>/<path>`
50
+ - **API tokens** — long-lived tokens with scopes and revocation
51
+ - **Export / import / duplicate** — move lambdas and projects as JSON
52
+ - **POC templates** — HTML + `fetch`, webhook, JSON API, static site
53
+ - **Free-threaded builds** — `cp314t`/`cp315t` wheels
54
+
55
+ ## Roadmap
56
+
57
+ 1.0 is the current release line: single-host deployments on Linux, data
58
+ lifecycle (backup/restore and schema versions), security hardening,
59
+ operational tooling and complete documentation. Multi-host active/active is out
60
+ of scope, and Firecracker/microVM-per-invocation isolation is not part of 1.0.
61
+ See [docs/ROADMAP-1.0.0.md](docs/ROADMAP-1.0.0.md); the 0.4.0 design notes
62
+ remain in [docs/ROADMAP-0.4.0.md](docs/ROADMAP-0.4.0.md).
63
+
64
+ ## Installation
65
+
66
+ ```bash
67
+ uv pip install vlambda
68
+ ```
69
+
70
+ Or with pip:
71
+ ```bash
72
+ pip install vlambda
73
+ ```
74
+
75
+ The production container image is published as
76
+ `ghcr.io/rroblf01/vlambda:<version>` for `linux/amd64` and `linux/arm64`.
77
+
78
+ ## Usage
79
+
80
+ ```bash
81
+ export VLAMBDA_SECRET="$(openssl rand -hex 32)"
82
+ python -m vlambda --port 8080 --sqlite_path ./vlambda.db --num_coroutines 10
83
+ ```
84
+
85
+ Or with environment variables:
86
+ ```bash
87
+ VLAMBDA_SECRET="$(openssl rand -hex 32)" \
88
+ VLAMBDA_PORT=8080 VLAMBDA_DB=./vlambda.db VLAMBDA_COROUTINES=10 python -m vlambda
89
+ ```
90
+
91
+ For a local development instance without TLS or real users you can set
92
+ `VLAMBDA_DEV=1` instead; the server warns and uses an insecure JWT secret.
93
+
94
+ Then open http://localhost:8080/ in your browser. `python -m vlambda --version`
95
+ prints the running package version; `/health` and `/ready` return it in JSON.
96
+
97
+ ## Documentation
98
+
99
+ - [API reference](docs/API.md)
100
+ - [CLI reference](docs/CLI.md)
101
+ - [Compatibility and versioning](docs/COMPATIBILITY.md)
102
+ - [Upgrading](docs/UPGRADING.md)
103
+ - [Operations](docs/OPERATIONS.md)
104
+ - [Security policy](SECURITY.md)
105
+ - [Contributing](CONTRIBUTING.md)
106
+
107
+ ## Build a POC in five minutes
108
+
109
+ 1. Open the UI and log in.
110
+ 2. Pick a template in **New lambda** (`JSON API`, `Webhook receiver`,
111
+ `Form receiver`, `HTML page`…) and create it.
112
+ 3. Open the invoke URL `https://your-host/f/<slug>`.
113
+ 4. Need files? Upload a ZIP in **Upload project**; anything in the project is
114
+ served at `/f/<slug>/<path>` and any unknown path runs `handler(request)`.
115
+
116
+ More complete examples live in [`examples/`](examples/): a static site, an
117
+ HTML + `fetch` POC, a webhook receiver and a JSON API.
118
+
119
+ ## API tokens
120
+
121
+ Create a token in **System → API tokens**, or with the API:
122
+
123
+ ```bash
124
+ curl -X POST "$VLAMBDA_URL/tokens" \
125
+ -H "Authorization: Bearer $JWT" \
126
+ -H "Content-Type: application/json" \
127
+ -d '{"name":"ci","scopes":["read","write"]}'
128
+ ```
129
+
130
+ The response contains the token (`vl_…`) once. Use it as
131
+ `Authorization: Bearer vl_…`. Scopes are `read`, `write` and `admin`; revoke a
132
+ token with `DELETE /tokens/<id>`. Tokens do not expire.
133
+
134
+ ## Docker + Dokploy
135
+
136
+ The repository includes a production image (`Dockerfile`, installs from PyPI) and
137
+ a development image (`Dockerfile.dev`, builds the local wheel). Both use a
138
+ free-threaded Python 3.15 venv, a pre-warmed fork supervisor and a fresh
139
+ Landlock + seccomp child per invocation, and expose plain HTTP on port `8080`;
140
+ Dokploy (or another proxy) handles TLS and the public domain.
141
+
142
+ The sandbox needs no extra Docker flags, capabilities or host sysctl changes.
143
+ It requires a Linux kernel with Landlock (5.13+; Ubuntu 22.04+, Debian 12+).
144
+
145
+ ```bash
146
+ export VLAMBDA_SECRET="$(openssl rand -hex 32)"
147
+ export VLAMBDA_ADMIN_TOKEN="$(openssl rand -hex 32)"
148
+ docker compose -f docker/compose.yml up -d --build
149
+ ```
150
+
151
+ With Dokploy, create an application from the image, map the domain to container
152
+ port `8080`, and set `VLAMBDA_SECRET` and `VLAMBDA_ADMIN_TOKEN`. Dokploy terminates
153
+ TLS, so the container does not manage certificates.
154
+
155
+ See `docker/README.md` for details, limits and the reset command.
156
+
157
+ ## CLI Options
158
+
159
+ | Flag | Env Var | Default | Description |
160
+ |------|---------|---------|-------------|
161
+ | `--port` | `VLAMBDA_PORT` | 8080 | Listen port |
162
+ | `--sqlite_path` | `VLAMBDA_DB` | ./vlambda.db | SQLite database path |
163
+ | `--num_coroutines` | `VLAMBDA_COROUTINES` | 10 | Worker pool size |
164
+ | `--max_body_size` | `VLAMBDA_MAX_BODY` | 1048576 | Max request body (bytes) |
165
+ | | `VLAMBDA_MAX_RESPONSE` | 10485760 | Max lambda response body (bytes) |
166
+ | | `VLAMBDA_MAX_TASKS` | 10000 | Queued async tasks before new tasks are rejected |
167
+ | | `VLAMBDA_MAX_TASKS_PER_OWNER` | 100 | Queued async tasks per user before new tasks are rejected |
168
+ | | `VLAMBDA_TRUST_PROXY` | 0 | Trust `X-Forwarded-For` for the client IP (enable only behind a proxy that overwrites it) |
169
+ | `--rate_limit` | `VLAMBDA_RATE_LIMIT` | 100 | Requests/sec per IP |
170
+ | `--invoke_timeout` | `VLAMBDA_TIMEOUT` | 30 | Lambda invocation timeout (s) |
171
+ | `--max_memory_mb` | `VLAMBDA_MAX_MEMORY_MB` | 0 | RAM limit (0=unlimited) |
172
+ | `--cors_origin` | `VLAMBDA_CORS` | *(none)* | CORS allowed origin; set `*` or an explicit origin to enable CORS |
173
+ | `--cert` | `VLAMBDA_CERT` | | TLS certificate path |
174
+ | `--key` | `VLAMBDA_KEY` | | TLS key path |
175
+ | | `VLAMBDA_REGISTRATION` | 1 | Allow public registration (`0` disables it; the production image sets `0`) |
176
+ | | `VLAMBDA_LOGIN_MAX_FAILURES` | 5 | Failed logins before a temporary block |
177
+ | | `VLAMBDA_LOGIN_WINDOW` | 300 | Failure window in seconds |
178
+ | | `VLAMBDA_LOGIN_BLOCK` | 300 | Block duration in seconds |
179
+ | | `VLAMBDA_REGISTER_MAX` | 5 | Registrations allowed per IP in the window |
180
+ | | `VLAMBDA_REGISTER_WINDOW` | 600 | Registration window in seconds |
181
+ | | `VLAMBDA_PASSWORD_MIN_LENGTH` | 12 | Minimum password length |
182
+ | | `VLAMBDA_USER_RATE_LIMIT` | rate limit | Requests/s per authenticated user (`0` follows the global limit) |
183
+ | | `VLAMBDA_AUDIT_RETENTION_DAYS` | 90 | Days of administrative audit entries to keep (`0` keeps all) |
184
+ | | `VLAMBDA_BACKUP_KEY` | encryption key | Key for `vlambda backup --encrypt`; keep it out of the backup |
185
+ | | `VLAMBDA_SANDBOX` | auto | `auto`, `fork`, `landlock`, `nsjail` or `process` (`auto` selects fork when Landlock + seccomp are available) |
186
+ | | `VLAMBDA_SECCOMP_MODE` | allowlist | `allowlist` (default) or `denylist` fallback for unusual runtimes |
187
+ | | `VLAMBDA_CORS` | *(none)* | Allowed CORS origin for `/f/`; set `*` or an explicit origin to enable |
188
+ | | `VLAMBDA_PIP_INDEX_URL` | PyPI | Index used when installing lambda packages |
189
+ | | `VLAMBDA_PIP_EXTRA_INDEX_URL` | | Additional allowed package index |
190
+ | | `VLAMBDA_PIP_REQUIRE_HASHES` | 0 | Require hashes in `requirements.txt` (`--require-hashes`) |
191
+ | | `VLAMBDA_METRICS_STATS_TTL` | 15 | Cache for percentile stats in seconds (`0` disables it) |
192
+ | | `VLAMBDA_DEV` | 0 | Allow local development without `VLAMBDA_SECRET` |
193
+ | | `VLAMBDA_SQLITE_JOURNAL` | auto | `wal` or `delete`; auto falls back to `delete` when CPython and system SQLite versions differ |
194
+ | | `VLAMBDA_RESP_CACHE_TTL` | 0 | GET response cache TTL in seconds (0 disables it) |
195
+ | | `VLAMBDA_CACHE_BACKEND` | memory | `memory`, `file` or `redis` for the optional response cache |
196
+
197
+ vlambda normally uses SQLite WAL. When CPython bundles a SQLite version
198
+ different from the system `libsqlite3` used by the V extension (for example on
199
+ Python 3.15), it automatically falls back to the rollback journal to avoid
200
+ cross-library WAL corruption. Set `VLAMBDA_SQLITE_JOURNAL=wal` or `delete` to
201
+ override it.
202
+
203
+ The GET response cache is disabled by default because a handler can depend on
204
+ headers, cookies, `request.env`, time or other request state. Enable it only for
205
+ stateless, idempotent GET lambdas; handlers that read request context, log,
206
+ `random` or `time.time` are skipped automatically.
207
+
208
+ ## API
209
+
210
+ ### Authentication
211
+ - `GET /config` — Public runtime flags (whether registration is open)
212
+ - `POST /register` — Register user (body: `username:password`); returns `403` when registration is disabled
213
+ - `POST /login` — Login (body: `username:password`) → JWT token
214
+ - `POST /password` — Change your password (body: `old:new`, or JSON `{"old":"...","new":"..."}` when the old password contains a colon); revokes existing sessions
215
+ - `POST /admin/users` — Create a user with `X-Admin-Token` and body `username:password` (for closed registration)
216
+
217
+ ### Admin token
218
+
219
+ vlambda does **not** have an admin user account or an `is_admin` column. The
220
+ admin is a deployment secret, `VLAMBDA_ADMIN_TOKEN`, sent as
221
+ `X-Admin-Token`. With registration closed (the production default), use it to
222
+ create the first users:
223
+
224
+ ```bash
225
+ curl -X POST https://your-host/admin/users \
226
+ -H "X-Admin-Token: $VLAMBDA_ADMIN_TOKEN" \
227
+ -d "alice:change-me-please-123"
228
+ ```
229
+
230
+ The token also protects `/admin/password` (reset a password),
231
+ `/admin/reset` (wipe all data) and `/admin/audit` (read administrative audit
232
+ entries), plus `/shutdown`:
233
+
234
+ ```bash
235
+ curl -X POST https://your-host/admin/password \
236
+ -H "X-Admin-Token: $VLAMBDA_ADMIN_TOKEN" \
237
+ -d "alice:new-password-123"
238
+
239
+ curl https://your-host/admin/audit?limit=50 \
240
+ -H "X-Admin-Token: $VLAMBDA_ADMIN_TOKEN"
241
+ ```
242
+
243
+ The token is not stored in SQLite, cannot log in, and does not own lambdas.
244
+ It remains valid across a data reset; users do not. To see every user's
245
+ tasks, metrics, logs or OpenAPI document, send the admin token alongside a
246
+ valid Bearer token. A reset does not change `VLAMBDA_ADMIN_TOKEN` or
247
+ `VLAMBDA_SECRET`.
248
+
249
+ ### Lambdas (requires auth)
250
+ - `POST /vlambda?method=GET&name=my-lambda` — Create lambda (body: Python code)
251
+ - `GET /vlambda` — List lambdas (pipe-delimited)
252
+ - `GET /vlambda?format=json` — List lambdas as JSON
253
+ - `GET /vlambda/<slug>` — Get lambda code
254
+ - `PUT /vlambda/<slug>?method=POST&name=new-name` — Update lambda
255
+ - `DELETE /vlambda/<slug>` — Delete lambda
256
+ - `GET /vlambda/<slug>/env` — List environment variables (secrets masked)
257
+ - `PUT /vlambda/<slug>/env` — Replace vars/secrets: `{"vars": {...}, "secrets": {...}}`
258
+
259
+ ### API tokens (requires auth)
260
+ - `POST /tokens` — Create a token: `{"name":"ci","scopes":["read","write"]}`; `admin` implies read/write and allows token management
261
+ - `GET /tokens` — List tokens (never returns the secret)
262
+ - `DELETE /tokens/<id>` — Revoke a token
263
+
264
+ Tokens are accepted anywhere a JWT is accepted. `read` allows listing and
265
+ reading, `write` allows mutating lambdas/projects, and `admin` allows token
266
+ management. The `/admin/*` endpoints always require the deployment admin token
267
+ (`X-Admin-Token`), not an API token scope.
268
+
269
+ ### Export / import
270
+ - `GET /vlambda/<slug>/export` — Export code or project files as JSON
271
+ - `POST /vlambda/import` — Create from an exported JSON body
272
+ - `POST /vlambda/<slug>/duplicate` — Copy a lambda or project
273
+
274
+ Project exports include text files. Binary files are listed in
275
+ `skipped_files` and are not copied.
276
+
277
+ ### Invocation
278
+ - `GET/POST/PUT/PATCH/DELETE /f/<slug>` — Invoke lambda (method must match)
279
+ - `OPTIONS /f/<slug>` — CORS preflight (returns `204`)
280
+ - `GET /f/<slug>/<path>` — Serve a project file, or invoke the handler if the
281
+ file does not exist
282
+ - `POST /async/<slug>` — Async invoke (returns task_id)
283
+ - `GET /task/<id>` — Get async task result
284
+
285
+ ### Projects
286
+ - `POST /vlambda?project=1&entry=main.py` — Upload a ZIP project (base64 body)
287
+ - `GET /project/<slug>` — Read project files
288
+ - `PUT /project/<slug>` — Save project files
289
+ - `GET /f/<slug>/` — Serve `index.html`
290
+ - `GET /f/<slug>/<path>` — Serve a static file (`vendor/`, `.git/` and `..` blocked)
291
+
292
+ ### Versions and aliases
293
+ - `GET /vlambda/<slug>/versions` — List versions
294
+ - `GET /vlambda/<slug>/version/<n>` — Read a version
295
+ - `POST /vlambda/<slug>/rollback?version=<n>` — Roll back
296
+ - `GET /vlambda/<slug>/aliases` — List aliases
297
+ - `POST /vlambda/<slug>/alias?name=prod&version=<n>` — Create alias
298
+ - `GET /f/<slug>?alias=prod` — Invoke an alias
299
+
300
+ ### Packages
301
+ - `GET /vlambda/<slug>/packages` — List requirements
302
+ - `POST /vlambda/<slug>/packages` — Install PyPI packages into the vendor dir
303
+
304
+ For production, pin versions in `requirements.txt` and point
305
+ `VLAMBDA_PIP_INDEX_URL` at a controlled mirror (or use
306
+ `VLAMBDA_PIP_REQUIRE_HASHES=1` with hashes). Without that, package
307
+ installation trusts whatever PyPI serves at upload time.
308
+
309
+ ### KV, egress and schedules
310
+ - `GET/PUT/DELETE /vlambda/<slug>/kv[/<key>]` — Read, write or delete KV entries
311
+ - `GET/PUT /vlambda/<slug>/egress` — Read or replace the egress allow-list
312
+ - `GET/POST /vlambda/<slug>/schedules` — List or create schedules
313
+ - `PUT/DELETE /vlambda/<slug>/schedules/<id>` — Update or delete a schedule
314
+ - `POST /vlambda/<slug>/schedules/<id>/run` — Run a schedule now
315
+ - `GET /vlambda/<slug>/schedules/<id>/runs` — Run history
316
+
317
+ ### Metadata and OpenAPI
318
+ - `GET/PUT /vlambda/<slug>/meta` — Summary, tags and description
319
+ - `GET /openapi.json` — Owner-scoped OpenAPI 3.1 document
320
+
321
+ ### Monitoring (requires auth)
322
+ - `GET /health` — Health check with the running version
323
+ - `GET /ready` — Readiness with the running version
324
+ - `GET /metrics` — Prometheus metrics
325
+ - `GET /metrics/json` — Live JSON metrics
326
+ - `GET /metrics/history?days=N&slug=` — Raw persisted metrics
327
+ - `GET /metrics/stats?days=N&slug=` — p50/p95/p99
328
+ - `GET /metrics/aggregate?days=N&slug=` — Per-lambda aggregates
329
+ - `GET /metrics/summary?days=N&slug=` — Daily rollups
330
+ - `GET /metrics/export?days=N&slug=` — CSV export
331
+ - `DELETE /metrics/history?days=N&slug=` — Delete metrics older than N days (`days=0` deletes all)
332
+ - `GET /logs/history?days=N&slug=` — Persisted lambda logs
333
+ - `DELETE /logs/history?days=N&slug=` — Delete logs older than N days (`days=0` deletes all)
334
+ - `GET /pool/stats`, `GET /dlq`
335
+ - `POST /shutdown` — Graceful shutdown (requires `X-Admin-Token`)
336
+
337
+ ## Logging
338
+
339
+ Lambdas can persist structured logs with `request.log()`:
340
+
341
+ ```python
342
+ def handler(request):
343
+ request.log("processing " + request.path)
344
+ request.log("debug details", "debug")
345
+ return {"ok": True}
346
+ ```
347
+
348
+ Logs are stored in the metrics database and can be queried with
349
+ `GET /logs/history?days=1&slug=<slug>`. The UI Logs view shows them alongside
350
+ invocations. The "Save logs" template in the editor is a ready-to-run example.
351
+
352
+ Metrics and logs are scoped to the authenticated user. A request that also
353
+ carries the deployment admin token (`X-Admin-Token`) can query all users
354
+ through the API; the admin token is not a login credential by itself.
355
+
356
+ Metrics and logs are pruned after `VLAMBDA_METRICS_RETENTION` days (default 7).
357
+ From the UI you can also prune data older than the selected period, or delete
358
+ all matching rows, with the current lambda filter applied.
359
+
360
+ ## Lambda Format
361
+
362
+ Every lambda must define a `handler` function. The canonical contract returns a
363
+ `Response`; returning a `dict`, `str` or `bytes` is still accepted as shorthand:
364
+
365
+ ```python
366
+ from vlambda import Response
367
+
368
+ def handler(request):
369
+ return Response.json(
370
+ {"msg": "hello", "path": request.path},
371
+ status=201,
372
+ headers={"X-Example": "yes"},
373
+ )
374
+ ```
375
+
376
+ The `request` object has: `method`, `path` (without the query string),
377
+ `query_string`, `query`, `headers`, `cookies`, `body`, `remote_ip`, `host`,
378
+ `scheme`, `request_id`, `slug`, `env`, and helpers `header()`, `json()`,
379
+ `form()` and `log()`.
380
+
381
+ `Response` supports `json()`, `text()`, `html()`, `redirect()`, `no_content()`,
382
+ status codes, headers, cookies and binary bodies.
383
+
384
+ Handlers may also be coroutine functions. vlambda awaits the coroutine and
385
+ serializes its value exactly like a synchronous return:
386
+
387
+ ```python
388
+ async def double(value):
389
+ return value * 2
390
+
391
+ async def handler(request):
392
+ return {"values": [await double(n) for n in (1, 2, 3)]}
393
+ ```
394
+
395
+ Await local coroutines or helpers you define with `async def`. The `asyncio`
396
+ module stays blocked because it exposes sockets indirectly.
397
+
398
+ Safe builtins: `abs`, `all`, `any`, `bool`, `dict`, `enumerate`, `filter`, `float`, `int`, `len`, `list`, `map`, `max`, `min`, `range`, `reversed`, `round`, `set`, `sorted`, `str`, `sum`, `tuple`, `zip`, `print`, etc.
399
+
400
+ Blocked modules: `os`, `posix`, `subprocess`, `sys`, `importlib`, `ctypes`, `socket`, `_socket`, `urllib`, `http`, `shutil`, `pathlib`, `io`, `pickle`, `marshal`, `resource`, `fcntl`, `mmap`, `sqlite3`, etc.
401
+
402
+ Safe modules: `json`, `math`, `re`, `datetime`, `collections`, `itertools`, `functools`, `hashlib`, `base64`, `string`, `random`, `statistics`, etc.
403
+
404
+ ### Security
405
+
406
+ With the Docker default (`VLAMBDA_SANDBOX=fork`), user code runs in a fresh
407
+ runner process confined with Landlock and seccomp.
408
+ Landlock limits the filesystem to `/opt`, `/usr`, `/lib`, `/etc`, the current
409
+ project/vendor and a private temporary directory; `/data`, `/proc`, `/sys` and
410
+ the rest of the server cannot be read or listed. seccomp blocks TCP/UDP and every
411
+ non-Unix socket, cross-process signals, `ptrace`, `mount`, namespace changes and
412
+ similar syscalls. Only `AF_UNIX` client sockets to the local capability broker
413
+ are allowed. Do not mount the Docker socket, cloud metadata proxies or other
414
+ privileged Unix sockets into the container: the sandbox needs Unix sockets for
415
+ the broker and cannot distinguish them from other local sockets. Resource
416
+ limits are applied too, and each invocation gets a fresh process.
417
+
418
+ The plain `python -m vlambda` command without `VLAMBDA_SANDBOX` uses the
419
+ in-process pool and is a development mode: lambdas run inside the server process
420
+ with only Python-level restrictions. Use `VLAMBDA_SANDBOX=fork` (Docker default),
421
+ `landlock`, `process` or `nsjail` for any untrusted code.
422
+
423
+ The production Docker image closes public registration by default. Create
424
+ users with `POST /admin/users` and `X-Admin-Token`, or set
425
+ `VLAMBDA_REGISTRATION=1` to open registration. Login attempts are throttled per
426
+ username and source IP after `VLAMBDA_LOGIN_MAX_FAILURES` failures.
427
+
428
+ At startup vlambda checks that the project, package and cache directories are
429
+ writable and, when `VLAMBDA_SANDBOX=fork`/`landlock` is selected, that Landlock
430
+ and libseccomp are available. It refuses to start instead of silently running
431
+ unsandboxed.
432
+
433
+ A daily data reset removes state, but it does not undo a kernel-level escape.
434
+ Keep this deployment disposable and do not store valuable secrets in it; for
435
+ stronger isolation use gVisor, Firecracker or one container per tenant.
436
+
437
+ ## Environment and secrets
438
+
439
+ Set per-lambda variables with `PUT /vlambda/<slug>/env`:
440
+
441
+ ```json
442
+ {
443
+ "vars": {"PLAIN": "hello"},
444
+ "secrets": {"TOKEN": "s3cret"}
445
+ }
446
+ ```
447
+
448
+ Secrets are encrypted at rest, masked by the API and decrypted only for that
449
+ lambda's runner. Code lambdas read them from `request.env`; projects also see
450
+ them in `os.environ`. Use a dedicated `VLAMBDA_ENCRYPTION_KEY` so rotating
451
+ `VLAMBDA_SECRET` (JWT signing) does not require re-encrypting secrets.
452
+
453
+ `request.headers` deliberately hides `Authorization`, `Proxy-Authorization`,
454
+ `Cookie`, `X-Api-Key` and `X-Admin-Token` from lambda code. A handler cannot
455
+ read or forward the caller's credentials.
456
+
457
+ To rotate the encryption key, stop the server and re-encrypt the stored secrets
458
+ offline:
459
+
460
+ ```bash
461
+ python -m vlambda backup --out before-rotate.tar.gz --encrypt
462
+ python -m vlambda secrets rotate \
463
+ --old-key "$OLD_ENCRYPTION_KEY" --new-key "$NEW_ENCRYPTION_KEY"
464
+ ```
465
+
466
+ The command is idempotent and reports how many rows it rotated. Every secret
467
+ carries a short key identifier, so a wrong old key fails closed instead of
468
+ writing garbage.
469
+
470
+ ## KV store
471
+
472
+ Every lambda has a small persistent key/value store, isolated by lambda and
473
+ accessible through an allow-listed capability broker rather than a database
474
+ connection in the sandbox.
475
+
476
+ ```python
477
+ def handler(request):
478
+ hits = request.kv.incr("hits")
479
+ request.kv.set("last", {"path": request.path}, ttl=3600)
480
+ return {"hits": hits, "last": request.kv.get("last")}
481
+ ```
482
+
483
+ Projects use the same API with `from vlambda import kv`. Values can be strings,
484
+ numbers, booleans, null, JSON documents or bytes; `incr()` is atomic and `ttl`
485
+ is optional. Limits are 256 keys, 64 KiB per value and 1 MiB per lambda.
486
+
487
+ Management API (owner only, `X-Admin-Token` not needed):
488
+
489
+ - `GET /vlambda/<slug>/kv?prefix=` — list
490
+ - `GET /vlambda/<slug>/kv/<key>` — read
491
+ - `PUT /vlambda/<slug>/kv/<key>` — write `{"value": ..., "ttl": 3600}`
492
+ - `DELETE /vlambda/<slug>/kv/<key>` — delete one key
493
+ - `DELETE /vlambda/<slug>/kv` — clear the store
494
+
495
+ The UI exposes a KV card in the code and project editors.
496
+
497
+ ## Egress
498
+
499
+ Lambdas cannot open TCP sockets. They can call allow-listed hostnames through
500
+ the capability broker:
501
+
502
+ ```python
503
+ def handler(request):
504
+ response = request.fetch("https://api.example.com/items", timeout=5)
505
+ return {"status": response.status, "data": response.json()}
506
+ ```
507
+
508
+ Projects use `from vlambda import fetch`. Supported methods are `GET`, `HEAD`,
509
+ `POST`, `PUT`, `PATCH` and `DELETE`; pass `data=` for raw bodies or
510
+ `json_payload=` for JSON. The response exposes `status`, `headers`, `body`,
511
+ `text` and `json()`.
512
+
513
+ Configure the allow-list per lambda (`GET/PUT /vlambda/<slug>/egress`):
514
+
515
+ ```bash
516
+ python -m vlambda egress <slug> --set api.example.com --set "*.example.org"
517
+ ```
518
+
519
+ Matching is exact, or `*.example.org` for the apex and subdomains. HTTPS is
520
+ required by default; set `VLAMBDA_EGRESS_ALLOW_HTTP=1` for local development.
521
+ Private, loopback, link-local and reserved addresses are rejected; set
522
+ `VLAMBDA_EGRESS_ALLOW_PRIVATE=1` only for tests. Redirects are not followed.
523
+ Each invocation is limited to 20 calls, 1 MiB request bodies and 2 MiB
524
+ responses, with a 10 s maximum timeout. Denied hosts are logged without query
525
+ strings.
526
+
527
+ ## Schedules
528
+
529
+ Create persistent cron jobs per lambda:
530
+
531
+ ```bash
532
+ python -m vlambda schedule create <slug> --name nightly --cron "0 3 * * *" \
533
+ --method POST --path /schedule --payload '{"job": "cleanup"}'
534
+ python -m vlambda schedule list <slug>
535
+ python -m vlambda schedule run <slug> <id>
536
+ python -m vlambda schedule runs <slug> <id>
537
+ python -m vlambda schedule delete <slug> <id>
538
+ ```
539
+
540
+ Supported expressions use five fields (`minute hour day-of-month month weekday`),
541
+ with lists, ranges and steps, plus month/day names and IANA timezones. The
542
+ scheduler runs one leader per database lease; overlapping runs are skipped and
543
+ windows missed by more than `VLAMBDA_SCHEDULE_GRACE` seconds are recorded as
544
+ `missed`. Run history is retained for `VLAMBDA_SCHEDULE_RETENTION` days (7 by
545
+ default, max 1000 runs per schedule).
546
+
547
+ API:
548
+
549
+ - `GET/POST /vlambda/<slug>/schedules`
550
+ - `PUT/DELETE /vlambda/<slug>/schedules/<id>`
551
+ - `POST /vlambda/<slug>/schedules/<id>/run`
552
+ - `GET /vlambda/<slug>/schedules/<id>/runs`
553
+
554
+ The UI exposes a schedules card in the code and project editors.
555
+
556
+ ## gVisor
557
+
558
+ For a second isolation boundary, run the container with the gVisor runtime:
559
+
560
+ ```bash
561
+ docker run --runtime=runsc ... ghcr.io/rroblf01/vlambda:latest
562
+ # or merge the compose override:
563
+ docker compose -f docker/compose.yml -f docker/compose.gvisor.yml up -d
564
+ ```
565
+
566
+ Kubernetes uses `runtimeClassName: gvisor` on the pod. The internal fork +
567
+ Landlock + seccomp sandbox remains active. `scripts/gvisor-smoke.sh` builds the
568
+ image, runs the health check under `runsc` and skips cleanly when gVisor is not
569
+ installed. Firecracker/microVM-per-invocation is not part of 1.0.
570
+
571
+ ## High availability (single host)
572
+
573
+ 1.0 supports multiple replicas on one host sharing a local `/data` volume.
574
+ SQLite WAL, a scheduler lease, task claiming and graceful drain keep scheduled
575
+ runs and tasks single-execution across replicas.
576
+
577
+ ```bash
578
+ docker compose -f docker/compose.ha.yml up -d --build --scale vlambda=2
579
+ ```
580
+
581
+ The sample puts nginx in front of two replicas. Do not place SQLite on NFS; use
582
+ a local volume on the same host. Multi-host HA needs an external database and is
583
+ not part of 1.0.
584
+
585
+ Relevant settings:
586
+
587
+ - `VLAMBDA_INSTANCE_ID` — unique replica name (defaults to hostname:pid)
588
+ - `VLAMBDA_DRAIN_TIMEOUT` — graceful shutdown wait (seconds, default 20)
589
+ - `VLAMBDA_TASK_LEASE` — task claim lease (seconds, default 600)
590
+ - `VLAMBDA_SCHEDULE_GRACE` / `VLAMBDA_SCHEDULE_RETENTION` — cron behavior
591
+ - `/ready` returns `503` while a replica is draining
592
+
593
+ ## OpenAPI
594
+
595
+ Every lambda can carry `summary`, `tags` and `description` metadata, editable
596
+ from the code/project editor or `PUT /vlambda/<slug>/meta`. The generated spec is
597
+ available at `/openapi.json` (authenticated and owner-scoped by default; set
598
+ `VLAMBDA_OPENAPI_PUBLIC=1` for a public spec). Import it into Postman, Insomnia,
599
+ Scalar, Swagger UI or any OpenAPI 3.1 client.
600
+
601
+ ```bash
602
+ python -m vlambda openapi --out openapi.json
603
+ ```
604
+
605
+ The spec describes `/f/<slug>` for every owned lambda, its method, request body
606
+ for write methods, generic JSON/text/binary responses and the `X-Request-Id`
607
+ header. Project static files are described under `/f/<slug>/{path}`.
608
+
609
+ ## CLI
610
+
611
+ The CLI talks to a running server and uses `VLAMBDA_URL`/`VLAMBDA_TOKEN` or
612
+ `--url`/`--token`:
613
+
614
+ ```bash
615
+ python -m vlambda deploy main.py --name my-lambda --method GET
616
+ python -m vlambda invoke <slug>
617
+ python -m vlambda logs --slug <slug> --days 1
618
+ python -m vlambda env <slug> --set PLAIN=hello --secret TOKEN=s3cret
619
+ python -m vlambda kv <slug> --set hits=0 --ttl 3600
620
+ python -m vlambda kv <slug> --get hits
621
+ python -m vlambda egress <slug> --set api.example.com
622
+ python -m vlambda schedule list <slug>
623
+ python -m vlambda openapi --out openapi.json
624
+ python -m vlambda task <task-id>
625
+ python -m vlambda backup --out backup.tar.gz
626
+ python -m vlambda restore --from backup.tar.gz --force
627
+ python -m vlambda secrets rotate --old-key "$OLD" --new-key "$NEW"
628
+ ```
629
+
630
+ ## Web UI
631
+
632
+ Open http://localhost:8080/ in your browser for the dashboard:
633
+ - Login/Register
634
+ - Lambda dashboard with search, filter and pagination
635
+ - CodeMirror editor with Python highlighting
636
+ - Multi-file project editor and ZIP upload
637
+ - Versions, rollback and aliases
638
+ - PyPI package installation
639
+ - API playground
640
+ - Persistent metrics with charts and filters
641
+ - Logs viewer with `request.log()`
642
+ - System status and frontend log drawer
643
+
644
+ ## Reset
645
+
646
+ The demo can be wiped with:
647
+
648
+ ```bash
649
+ python -m vlambda reset --yes --url http://127.0.0.1:8080 --token "$VLAMBDA_ADMIN_TOKEN"
650
+ ```
651
+
652
+ A reset also invalidates existing JWT sessions and API tokens.
653
+
654
+ 1.0 starts with a fresh schema and refuses to open a pre-1.0 database. To move
655
+ an existing deployment to 1.0, stop the server and wipe the database files:
656
+
657
+ ```bash
658
+ python -m vlambda reset --yes --wipe
659
+ ```
660
+
661
+ Install 1.0 first so this command exists. It removes the main and metrics
662
+ databases plus project, package and cache data. Copy the data volume first if
663
+ you need to keep anything; the old schema is not migrated automatically.
664
+
665
+ For a disposable demo, run it from cron every day. `--online-only` prevents the
666
+ CLI from touching SQLite directly if the server is down or rejects the request:
667
+
668
+ ```cron
669
+ 0 3 * * * flock -n /run/vlambda-reset.lock docker exec -e VLAMBDA_ADMIN_TOKEN="..." <container> /opt/venv/bin/python -m vlambda reset --yes --online-only --url http://127.0.0.1:8080 >> /var/log/vlambda-reset.log 2>&1
670
+ ```
671
+
672
+ ## Backup and restore
673
+
674
+ Backups are self-contained archives of the main SQLite database, the
675
+ metrics/logs database and the project tree. The main database is copied with
676
+ SQLite's online backup API, so a backup is safe while the server is running.
677
+ Restoring is offline: stop the server first.
678
+
679
+ ```bash
680
+ # Safe while the server is running
681
+ python -m vlambda backup --out /data/backups/vlambda-$(date +%F).tar.gz
682
+
683
+ # Stop the server before restoring
684
+ python -m vlambda restore --from /data/backups/vlambda-2026-11-04.tar.gz --force
685
+ ```
686
+
687
+ Add `--with-packages` to include the per-lambda/project package vendor
688
+ directories. Restores verify `PRAGMA integrity_check`, the schema version and the
689
+ encryption-key fingerprint. Use the same `VLAMBDA_SECRET` or
690
+ `VLAMBDA_ENCRYPTION_KEY`; if you accept that encrypted secrets will not decrypt,
691
+ pass `--allow-key-mismatch`.
692
+
693
+ Both databases expose a schema version through `PRAGMA user_version`. A build
694
+ refuses to open a database written by a newer schema, so an older backup is the
695
+ safe rollback path.
696
+
697
+ ## Performance
698
+
699
+ | Metric | Value |
700
+ |--------|-------|
701
+ | Cold start | 0ms in persistent mode; fresh sandbox process in Docker |
702
+ | Warm invocation (in-process) | ~0.3ms |
703
+ | Warm invocation (Docker fork sandbox) | ~10-20ms p50 |
704
+ | Throughput (concurrent, free-threaded) | ~3,000 req/s in-process |
705
+ | Response cache | Opt-in via `VLAMBDA_RESP_CACHE_TTL`; ~100x faster for stateless GETs |
706
+
707
+ ## Architecture
708
+
709
+ ```
710
+ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐
711
+ │ Browser │────▶│ V HTTP │────▶│ Python │
712
+ │ (UI) │◀────│ Server │◀────│ Pool │
713
+ └─────────────┘ │ (net.http) │ │ (workers) │
714
+ │ │ └─────────────┘
715
+ │ ┌────────┐ │ │
716
+ │ │ SQLite │ │ │
717
+ │ │ (WAL) │ │ ┌─────────────┐
718
+ │ └────────┘ │ │ Sandbox │
719
+ └──────────────┘ │ (restricted│
720
+ │ builtins) │
721
+ └─────────────┘
722
+ ```
723
+
724
+ ## Security
725
+
726
+ Report vulnerabilities through GitHub's private advisories or the contact in
727
+ [SECURITY.md](SECURITY.md). Do not open a public issue for a suspected sandbox
728
+ escape or authentication bypass.
729
+
730
+ ## License
731
+
732
+ MIT License - see [LICENSE](LICENSE) for details. Third-party browser libraries
733
+ bundled into the UI are listed in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
734
+
735
+ ## Author
736
+
737
+ Ricardo Robles Fernández - https://github.com/rroblf01/vlambda
738
+