|
@@ -0,0 +1,202 @@
|
|
|
|
|
+# Function runtime (QuickJS) - design
|
|
|
|
|
+
|
|
|
|
|
+Server-side JavaScript in smartbotic-vectorapi: user-supplied functions that
|
|
|
|
|
+serve HTTP routes, and later run on a schedule or on database events.
|
|
|
|
|
+
|
|
|
|
|
+Status: approved 2026-10-06. This document is the contract for implementation.
|
|
|
|
|
+
|
|
|
|
|
+## Why
|
|
|
|
|
+
|
|
|
|
|
+n8n covers orchestration well, but two things it cannot do: react to database
|
|
|
|
|
+changes (only vectorapi holds the `subscribe()` streams), and run logic next to
|
|
|
|
|
+the data (a chunk-embed-upsert loop costs one HTTP hop per item through n8n).
|
|
|
|
|
+
|
|
|
|
|
+## Shape
|
|
|
|
|
+
|
|
|
|
|
+```
|
|
|
|
|
+person / LLM ──POST /projects/{p}/functions──▶ vectorapi
|
|
|
|
|
+ │ validate on a runner, then store
|
|
|
|
|
+ ▼
|
|
|
|
|
+ <project>:vectorapi_functions
|
|
|
|
|
+ │
|
|
|
|
|
+ HTTP request ──▶ route match ──dispatch(sync)──▶ ┌──────────┐
|
|
|
|
|
+ │ runner │ QuickJS pool
|
|
|
|
|
+ cron / DB event ──▶ enqueue ──claim──▶ job queue │ (N inst)│ reads registry + data itself
|
|
|
|
|
+ └────┬─────┘
|
|
|
|
|
+ ▼
|
|
|
|
|
+ smartbotic-database
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+The runner is a second binary in this repo linking `vectorapi_core`. It holds
|
|
|
|
|
+its own `DbGateway`, so `ctx.collections(...)` is a direct call - never loopback
|
|
|
|
|
+HTTP to vectorapi - and it enforces policy with the same `KeyScope` code
|
|
|
|
|
+vectorapi uses. One implementation of authorization, two processes.
|
|
|
|
|
+
|
|
|
|
|
+vectorapi does NOT link QuickJS.
|
|
|
|
|
+
|
|
|
|
|
+## Identity and policy
|
|
|
|
|
+
|
|
|
|
|
+A function is a principal, not a key holder. No secret: it never authenticates
|
|
|
|
|
+over the wire, it *is* the server.
|
|
|
|
|
+
|
|
|
|
|
+```cpp
|
|
|
|
|
+struct FunctionIdentity { std::string project; std::string id; KeyScope scope; };
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- **`id` is declared in the script** (`export const on = { id: 'kb-search', ... }`).
|
|
|
|
|
+ The file path is incidental, so renames and moves carry the policy with them.
|
|
|
|
|
+ Duplicate ids fail the load (both marked invalid). A missing id is an error,
|
|
|
|
|
+ never a silent path fallback.
|
|
|
|
|
+- **Policy is server state**, stored on the function's registry row and edited by
|
|
|
|
|
+ an admin. Pushing code can never widen access.
|
|
|
|
|
+- **First registration inherits** `default_function_policy` from the project's
|
|
|
|
|
+ settings document (beside the per-project embedding overrides).
|
|
|
|
|
+- A function whose source is removed keeps its row marked `missing` rather than
|
|
|
|
|
+ being deleted, so a mistake cannot silently drop a policy.
|
|
|
|
|
+
|
|
|
|
|
+### The Principal refactor
|
|
|
|
|
+
|
|
|
|
|
+`requireCapability()` today takes an `ApiKey`. It becomes:
|
|
|
|
|
+
|
|
|
|
|
+```cpp
|
|
|
|
|
+struct Principal { std::vector<std::string> projects; bool admin; const KeyScope* scope; };
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+with `ApiKey` and `FunctionIdentity` both convertible to it. This is the only
|
|
|
|
|
+way function access and HTTP access cannot drift apart. Mechanical but broad: it
|
|
|
|
|
+touches every handler's auth call.
|
|
|
|
|
+
|
|
|
|
|
+## The ctx.* surface
|
|
|
|
|
+
|
|
|
|
|
+Mirrors vectorapi's own concepts and its documented `field:op:value` filter
|
|
|
|
|
+grammar, so knowledge transfers from the HTTP API.
|
|
|
|
|
+
|
|
|
|
|
+```js
|
|
|
|
|
+export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' };
|
|
|
|
|
+
|
|
|
|
|
+export default async function (ctx) {
|
|
|
|
|
+ const docs = await ctx.collections('kb_chunks')
|
|
|
|
|
+ .filter(`topic:eq:${ctx.params.topic}`).limit(20).find();
|
|
|
|
|
+ const hits = await ctx.collections('kb_chunks')
|
|
|
|
|
+ .search({ query_text: ctx.query.q, top_k: 5, filters: ['lang:eq:hu'] });
|
|
|
|
|
+ await ctx.collections('audit').insert({ topic: ctx.params.topic });
|
|
|
|
|
+ return { status: 200, body: { docs, hits } };
|
|
|
|
|
+}
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- documents: `.filter() .limit() .offset() .sort()` then
|
|
|
|
|
+ `.find() .get(id) .insert(doc) .update(id, doc) .patch(id, fields) .delete(id)`
|
|
|
|
|
+- vectors: `.search({query_text|query_vector, top_k, min_score, filters})`,
|
|
|
|
|
+ `.store({text|vector, metadata})` - embedding resolves through the existing
|
|
|
|
|
+ precedence, so a project's provider override applies
|
|
|
|
|
+- `ctx.env` (secrets), `ctx.fetch` (SSRF-guarded egress), `ctx.log`
|
|
|
|
|
+- NOT in slice 1: filesystem, storage
|
|
|
|
|
+
|
|
|
|
|
+Host calls are synchronous; `await` works because awaiting a non-promise is a
|
|
|
|
|
+no-op. The ergonomic builder is a JS prelude over a few native bindings
|
|
|
|
|
+(`__hostDb`, `__hostFetch`), keeping common logic in C++ and scripts small.
|
|
|
|
|
+
|
|
|
|
|
+`ctx.*` makes no loopback HTTP call. `.search({query_text})` does make an
|
|
|
|
|
+OUTBOUND call to the embedding provider - that is not loopback.
|
|
|
|
|
+
|
|
|
|
|
+## Storage
|
|
|
|
|
+
|
|
|
|
|
+One document per function in `<project>:vectorapi_functions`:
|
|
|
|
|
+
|
|
|
|
|
+```
|
|
|
|
|
+{ function_id, path, source, content_hash, descriptor, policy,
|
|
|
|
|
+ enabled, valid, last_error, created_at, updated_at }
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+`function_id`, not `id`: the database client strips a top-level `id` from stored
|
|
|
|
|
+bodies (the same reason API keys store `key_id`).
|
|
|
|
|
+
|
|
|
|
|
+## HTTP surface
|
|
|
|
|
+
|
|
|
|
|
+| Route | Who |
|
|
|
|
|
+|---|---|
|
|
|
|
|
+| `GET/POST /api/v1/projects/{p}/functions` | project-manage |
|
|
|
|
|
+| `GET/PUT/DELETE .../functions/{id}` | project-manage |
|
|
|
|
|
+| `PUT .../functions/{id}/policy` | **admin** |
|
|
|
|
|
+| `PUT .../functions/{id}/enabled` | project-manage |
|
|
|
|
|
+| `POST .../functions/{id}/invoke` | project-manage |
|
|
|
|
|
+| `GET .../functions/{id}/logs` | project-manage |
|
|
|
|
|
+
|
|
|
|
|
+Code and capability are split on purpose: developers write functions, admins
|
|
|
|
|
+grant what they may touch - mirroring keys, which are already admin-only.
|
|
|
|
|
+
|
|
|
|
|
+**Validation runs on a runner**, not in vectorapi: a write is compiled and its
|
|
|
|
|
+`on` block parsed before storage, and rejected with the compile error otherwise.
|
|
|
|
|
+The engine that validates is therefore the engine that will execute. Creating a
|
|
|
|
|
+function with no healthy runner returns 503.
|
|
|
|
|
+
|
|
|
|
|
+## Runner protocol
|
|
|
|
|
+
|
|
|
|
|
+Runner discovery is a static list in vectorapi's config, health-checked.
|
|
|
|
|
+Dynamic registration waits until autoscaling actually exists.
|
|
|
|
|
+
|
|
|
|
|
+HTTP functions, synchronous, retried on the next healthy runner:
|
|
|
|
|
+
|
|
|
|
|
+```
|
|
|
|
|
+POST /run { project, function_id, trigger:{method,path,params,query,headers,body} }
|
|
|
|
|
+ -> { status, headers, body, console[], duration_ms, error? }
|
|
|
|
|
+POST /validate { source, path } -> { ok, descriptor?, error? }
|
|
|
|
|
+GET /health
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+The payload is small because the runner reads source, `content_hash` and policy
|
|
|
|
|
+from the registry itself and caches compiled bytecode by hash.
|
|
|
|
|
+
|
|
|
|
|
+Cron and DB-event jobs go through one global `vectorapi_function_jobs`
|
|
|
|
|
+collection with a `project` field:
|
|
|
|
|
+
|
|
|
|
|
+```
|
|
|
|
|
+{ project, function_id, trigger, state: pending|claimed|done|failed,
|
|
|
|
|
+ claimed_by, claimed_at, attempts, depth, run_after }
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+A runner claims with `updateIfVersion()`; a version conflict means another
|
|
|
|
|
+runner won it. A claim older than a timeout returns to `pending`, which is how a
|
|
|
|
|
+runner dying mid-job gets retried elsewhere.
|
|
|
|
|
+
|
|
|
|
|
+The **scheduler stays in vectorapi**: there must be exactly one, or N runners
|
|
|
|
|
+each fire every cron. vectorapi is already the singleton and already holds the
|
|
|
|
|
+subscribe streams DB events will need.
|
|
|
|
|
+
|
|
|
|
|
+## Safety
|
|
|
|
|
+
|
|
|
|
|
+- Per-run limits: memory, wall time (descriptor `timeoutMs`, clamped to a
|
|
|
|
|
+ configured max), stack. A fresh `JSContext` per run so nothing leaks between
|
|
|
|
|
+ tenants. The pool recycles a runtime whose allocation stays high.
|
|
|
|
|
+- SSRF guard: CIDR blocklist from settings with built-in defaults, DNS resolve
|
|
|
|
|
+ then classify every returned address, fail closed on unparseable input. It
|
|
|
|
|
+ blocks loopback, so a function cannot call its own API. Intentional.
|
|
|
|
|
+- `rateLimitPerMin` already exists in `KeyScope` and applies unchanged.
|
|
|
|
|
+- The job record carries `depth` from day one, though nothing reads it until DB
|
|
|
|
|
+ events land: retrofitting a self-trigger guard is how you get an infinite loop
|
|
|
|
|
+ in production.
|
|
|
|
|
+
|
|
|
|
|
+## Slice 1
|
|
|
|
|
+
|
|
|
|
|
+**In**: runner binary (pool, host context, policy enforcement, `/run`,
|
|
|
|
|
+`/validate`, `/health`), functions CRUD, HTTP dispatch on route match, manual
|
|
|
|
|
+invoke, run logs.
|
|
|
|
|
+
|
|
|
|
|
+**Out**, each its own later cycle: cron, DB events, shared modules (needs a
|
|
|
|
|
+module loader with path jailing - a security boundary, not a convenience),
|
|
|
|
|
+filesystem, storage API, git export.
|
|
|
|
|
+
|
|
|
|
|
+## Testing
|
|
|
|
|
+
|
|
|
|
|
+Unit: descriptor parsing, route matching, policy enforcement, limit enforcement,
|
|
|
|
|
+SSRF classification. Integration through `packaging/devstack`, extended to run a
|
|
|
|
|
+runner alongside: deploy a function, call it, then assert the things that must
|
|
|
|
|
+FAIL - a denied collection, a wall-time timeout, a blocked egress.
|
|
|
|
|
+
|
|
|
|
|
+## Risks
|
|
|
|
|
+
|
|
|
|
|
+- Two binaries that must version together, the same discipline as the client ABI
|
|
|
|
|
+ pin.
|
|
|
|
|
+- The `Principal` refactor is broad, touching every handler's auth call.
|
|
|
|
|
+- HTTP functions gain a network hop; measure the latency before anyone builds a
|
|
|
|
|
+ chatty endpoint on it.
|