|
|
@@ -67,14 +67,16 @@ Arbitrary JSON CRUD under a `kind=json` collection.
|
|
|
|
|
|
- `POST /api/v1/projects/{project}/collections/{name}/documents` `{data:{...}}` or `{...}` - Insert a document. Returns `{id}`. Optional `?ttl_seconds=N` query param sets an expiry; absent means no expiry.
|
|
|
|
|
|
- **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values`, while a document **id** that is already taken is **409** `duplicate_id` (different remedies: change the value, versus choose another id or upsert with `PUT`) (the same slug `POST /indexes` returns), and `error.details` names the index: `field`, the colliding `value` when that field is at the top level of the body you sent, and `conflicting_document_id` (the document already holding it). A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write.
|
|
|
+ **Other slugs worth branching on.** From the database: `read_only` **503** (the database is refusing writes), `db_unavailable` **503**, `rate_limited` **429** raised by the DATABASE under pressure (distinct from a key's scope rate limit, same status), `internal` **500**. On the routes: `exists` **422** (duplicate collection name), `bad_project` **422**, `last_admin` **422** (refusing to remove the last admin key), `not_vector` **422** (a vector op on a json collection), `dimension_mismatch` **422**, `ambiguous_body` **422**, `file_too_large` **422**, `vector_replace_unsafe` **422**. On `/fn/*`: `function_error` **500** and `method_not_allowed` **405**. On function writes: `no_runner` and `runner_unreachable` both **503**; invoke answers **409** `function_invalid` or `function_disabled`. Inside a function: `jobs_unavailable` **503**, `job_depth_exceeded` **422**, `unsupported_combination` **422**, `body_too_large` **422**, `not_json` **422**, `embedding_timeout` **504**, `fetch_timeout` **504**.
|
|
|
+
|
|
|
+ **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values`, while a document **id** that is already taken is **409** `duplicate_id` (different remedies: change the value, versus choose another id or upsert with `PUT`) (the same slug `POST /indexes` returns), and `error.details` names the index: **`field`** when one field collided or **`fields`** when several, **`values`** (an OBJECT of the colliding field/value pairs, not a bare `value`), `conflicting_document_id` (the document already holding it), and `relation` or `current_version` where they apply. A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing collection is **404** only when its absence is CONFIRMED: if the database cannot be reached the answer is **503**, never a 404, so a 404 is always safe to treat as definitive and unretryable. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write. **On a `kind=vector` collection, a PUT whose body carries no vector is refused **422** `vector_replace_unsafe`.** A replace discards the stored embedding and the caller cannot prevent it, because no read returns the vector - so there is nothing to put back. Use `PATCH` for fields, or `POST .../vectors` to store a document together with its vector.
|
|
|
|
|
|
**Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`. The metadata fields below (`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by`, `_updated_by`) are stripped from every write body, so you can read a document, edit a field and send the whole thing back without storing stale metadata as real fields.
|
|
|
- `GET /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID. The body is the stored document **plus the database's read-only metadata**: `_id`, `_version` (an integer, starting at 1 and incremented by every write), `_created_at`, `_updated_at` (epoch ms), `_created_by`, `_updated_by`. `_version` is the value `?if_version=` takes, and it is also returned as an `ETag` header. These names are reserved: a field of your own called `_version` cannot be stored or read back.
|
|
|
- `PUT /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace the document at `{id}`, **creating it when it does not exist** (a real upsert, as the method means). Accepts the same two body shapes as POST. **201** `{id, created:true, version:1}` with a `Location` header when it created, **200** `{id, created:false, version:N}` when it replaced. A replace is not a merge: fields the body omits are dropped. Creating counts as an insert for authorization, so a capability-scoped key granted `update` but not `insert` on the collection gets **403** on a PUT to an id that does not exist yet and can only replace. PUT does not take `?ttl_seconds=`; use POST with an `id` to create with an expiry.
|
|
|
- `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (RFC 7396 merge: a `null` removes a field); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. Returns `{id, version}`. **404** when the document does not exist - unlike PUT, PATCH never creates, because merging fields into nothing has no defined result and a patch body is not a whole document. Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
|
|
|
|
|
|
- **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` and is not available on a `kind=vector` collection (**422** `conditional_unsupported` for both): the version-checked write has no expiry field, and it rewrites the whole document, which would drop the stored embedding.
|
|
|
+ **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` (**422** `conditional_unsupported`): the version-checked write has no expiry field, and silently dropping one of the two would be worse than refusing. It IS available on a `kind=vector` collection - a conditional PATCH is a server-side MERGE and preserves the stored embedding (measured). What is refused there is a whole-document **replace**: see `PUT` below.
|
|
|
- `POST /api/v1/projects/{project}/collections/{name}/documents/{id}/increment` `{field: n, ...}` (or `{data:{...}}`) - **Atomic increment.** Adds each number to the named field in ONE locked server-side read-modify-write, so concurrent increments cannot lose each other. Dotted keys address nested fields (`counts.sent`). Returns **200** `{id, values}` where `values` holds the NEW value of every field you named. An absent or null field counts as 0. Integer + integer stays an integer (overflow is refused); anything else becomes a double. A field holding a non-number is **422** `validation` and **nothing at all is applied** - the whole set applies or none of it does. Needs the `update` grant (it is a write, so a read-only scope gets **403**); it is a separate route rather than a flag on PATCH because `{"calls":1}` means "set calls to 1" on PATCH and "add 1 to calls" here.
|
|
|
|
|
|
**It requires the document to exist** (**404** otherwise) and never creates one: the starting document is yours to describe. The idiom for a counter that may not exist yet is: increment; on **404** `POST .../documents` the document under a fixed `id` with its starting values; on **409** `duplicate_values` (someone else just created it) increment again.
|
|
|
@@ -125,7 +127,7 @@ Relation names are per-project and **unqualified**: requests and responses alway
|
|
|
Requires a `kind=vector` collection. Vectors are stored with cosine-similarity indexing.
|
|
|
|
|
|
- `POST /api/v1/projects/{project}/collections/{name}/vectors` `{id?, text?, vector?, metadata?}` - Store a vector. Supply either `text` (the server embeds it, resolving the model as: the collection's `embedding_model` pin, else the project's embedding override, else the global default) or a pre-computed `vector` array. `vector` dimension must match the collection's `vector_dimension`. `metadata` is an arbitrary JSON object stored alongside the vector.
|
|
|
-- `POST /api/v1/projects/{project}/collections/{name}/search` `{query_text?, query_vector?, top_k?, min_score?, filters?}` - Cosine-similarity search. Supply either `query_text` or `query_vector`; neither is **422**. `top_k` caps the results, **default 5**. `min_score` (0-1) drops low-confidence matches, default 0. `filters` is an array of `field:op:value` strings applied to the vector's metadata, using the grammar and operators above - metadata is stored at the top level of the document, so a vector written with `metadata:{"colour":"red"}` is filtered as `colour:eq:red`.
|
|
|
+- `POST /api/v1/projects/{project}/collections/{name}/search` `{query_text?, query_vector?, top_k?, min_score?, filters?}` - Cosine-similarity search. Supply either `query_text` or `query_vector`; neither is **422**. `top_k` caps the results, **default 5**. `min_score` (0-1) drops low-confidence matches, default 0. `filters` is an array of `field:op:value` strings applied to the vector's metadata, using the grammar and operators above - metadata is stored at the top level of the document, so a vector written with `metadata:{"colour":"red"}` is filtered as `colour:eq:red`. The response also carries **`scan_capped`** (and `scanned`, plus `scan_cap` when capped): a filtered search walks the ranking only `scan_cap` deep, so on a collection larger than that a filter whose matches lie deeper returns FEWER hits than match. `scan_capped: false` means the answer is complete - including the ordinary case of a filter matching fewer rows than `top_k`. **Check it before treating a filtered result set as exhaustive.** Inside a function the return stays an array and the warning goes to the run's console instead.
|
|
|
|
|
|
Filtering is evaluated by the database, then intersected with the similarity ranking, so scores are identical with and without a filter and `min_score` means the same thing either way. The scan is bounded at 10000 candidates: within a collection of that size a filtered search returns exactly the true top-k, and beyond it a filter matching only very low-ranked vectors may return fewer.
|
|
|
|
|
|
@@ -135,6 +137,8 @@ Requires a `kind=vector` collection. Vectors are stored with cosine-similarity i
|
|
|
|
|
|
## Settings (admin)
|
|
|
|
|
|
+`PUT /api/v1/settings` also accepts **`function_egress_blocked_cidrs`** (an array of CIDRs, **422** `invalid_cidr` on a bad one) and **`function_egress_allow_private`** (a bool). The blocklist is **UNIONED** with the built-in defaults, never substituted for them, and `function_egress_allow_private` relaxes ONLY the private ranges - the metadata endpoint, link-local, multicast and the IPv6 spellings of an IPv4 address stay blocked whatever it is set to. **`max_file_bytes` is returned by GET but is NOT settable over the API**; it is read from the stored settings document.
|
|
|
+
|
|
|
All settings endpoints require an admin key.
|
|
|
|
|
|
- `GET /api/v1/settings` - Return current settings as JSON. `openai_api_key` is masked: the field is absent and `openai_api_key_set` (bool) indicates whether a key is configured.
|
|
|
@@ -198,7 +202,7 @@ Server-side JavaScript that serves HTTP routes. These routes require a key grant
|
|
|
A function is an ES module exporting a trigger declaration and a default handler:
|
|
|
|
|
|
```js
|
|
|
-export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' };
|
|
|
+export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' }; **`type` is `http` (the default), `cron`, `db` or `job`.** `cron` needs `schedule` (five-field) and optionally `tz`, an IANA zone validated against the host's time-zone database at PUSH time - an unknown zone is refused, never silently UTC. `db` needs `table` and `event` (INSERT/UPDATE/DELETE). `job` is reached only by being enqueued. **`singleFlight` defaults to TRUE for cron** and false otherwise.
|
|
|
|
|
|
export default async function (ctx) {
|
|
|
const docs = await ctx.collections('kb_chunks')
|
|
|
@@ -215,14 +219,32 @@ export default async function (ctx) {
|
|
|
`ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
|
|
|
|
|
|
- `ctx.collections(name)` - a chainable builder. `.filter('field:op:value')`, `.limit(n)`, `.offset(n)`, `.sort('field')` or `.sort('-field')` for descending, then a terminal: `.find()` returns an **array**, `.get(id)` returns the document or **null**, `.insert(doc)` returns `{id}`, `.update(id, doc)` returns `{id}`, `.patch(id, fields)` returns `{id, version}`, `.increment(id, {field: n})` returns the **new values** object (the same atomic increment as the HTTP route, needing the `update` grant; a missing document throws), `.delete(id)` returns `{deleted}`. Filters use the same `field:op:value` grammar as `?filter=`, parsed by the same code and evaluated by the database, so a filter means the same thing here as over HTTP.
|
|
|
+- **Write options**, previously undocumented. `ttl_seconds` is accepted by `.insert()`, `.update()`, `.patch()` and `.store()`; it sets or clears a document's expiry, and **absent is not zero** - omitting it leaves an existing expiry untouched while `0` clears it, so a plain `.patch()` cannot accidentally make a temporary document permanent. **`ifVersion: n`** makes the write conditional on the document still being at version `n` (as returned in `_version`); a lost race is **409** `version_conflict` carrying `current_version`, which means "someone else has it" and should be handled by dropping the work or re-reading, never by retrying the same write. `ifVersion` must be a positive integer - version 0 does not exist, since a first write produces 1. It is accepted by **`.update()` and `.patch()` only**: `.insert()` refuses it by name, because there is no existing version for a document that does not yet exist. `ttl_seconds` together with `ifVersion` is refused (`unsupported_combination`) rather than silently dropping one. A conditional `.update()` returns `{id, version}`; the unconditional form returns `{id}`.
|
|
|
- Vector collections additionally take `.search({query_text|query_vector, top_k, min_score, filters, embedTimeoutMs?})`, returning an **array** of hits, and `.store({text|vector, metadata, embedTimeoutMs?})`. Embedding resolves through the normal precedence, so a project's provider override applies.
|
|
|
- **`embedTimeoutMs` bounds the whole embedding call, connect phase included**, and is narrowing only - it cannot exceed what is left of the run's budget. Exceeding it is **504** `embedding_timeout`. A non-integer or non-positive value is **422**: it is validated rather than ignored, because an option that is accepted and does nothing is worse than one that is refused.
|
|
|
- **A blocking host call cannot be interrupted.** The run's wall budget is enforced between bytecode operations, so while an embedding or `ctx.fetch` request is in flight the deadline cannot be noticed - the budget ends the run once the call returns. Host calls are bounded by giving them timeouts that already fit the remaining budget (connect **and** read together), not by preemption. For a hard latency ceiling, catch the error and have a fallback path.
|
|
|
- `ctx.fetch(url, {method, headers, body, timeoutMs, responseType})` - outbound HTTP, **SSRF-guarded**: loopback, private and link-local destinations are refused, which means a function cannot call this API back. The refusal is reported in the run's console rather than as a network error.
|
|
|
+- **A job, cron or db run's `ctx` is NOT the HTTP shape.** It carries `trigger`, `depth`, `enqueued_by` and `enqueued_at_ms`, with your payload under **`ctx.body`** - there is no `ctx.method`, `ctx.path`, `ctx.query` or `ctx.params`. A cron payload is `{schedule, scheduled_at}`; a database-event payload is `{collection, table, id, event, document}`.
|
|
|
+- **The `ctx.fetch` response** carries `status`, `headers`, `body`, `bodyEncoding` and a `res.json()` helper. `res.json()` on a base64 response throws `not_json` rather than parsing bytes as text.
|
|
|
+- `ctx.files.list()` returns at most **100** entries and does not page. `ctx.crypto.hmacSha256` accepts `{base64:'...'}` for either `key` or `data`, not only strings.
|
|
|
+- `.insert(doc)` honours an **`id` inside the document object** - the idiom for an idempotent write.
|
|
|
+- `.store()` also accepts `id` and `ttl_seconds`. A `.filter(...)` accumulated on the chain is **appended** to an explicit `filters` array in `.search({...})`, never replaced by it.
|
|
|
+- `ctx.jobs.enqueue(functionId, payload, options?)` - put work on the job queue, returning the **job id as a plain string** (not an object). The project is NOT an argument: a function enqueues into its own project or not at all. **This is where slow work belongs** - a job run gets the job wall ceiling (far higher than an HTTP run's) and draws from its own pool lane, so it cannot starve interactive routes. Options: `runAt` (a `Date` or epoch milliseconds) **or** `delaySec`, never both - reconciling them would be a guess at what the author meant, so it is **422** `ambiguous_body`; and `dedupeKey`, a non-empty string of at most 512 characters that collapses repeated enqueues of the same logical work. An unknown option name is refused **by name** rather than ignored.
|
|
|
+- `ctx.jobs.cancel(id)` - cancel a job that has not been claimed yet. Returns a **boolean**: false when there was nothing cancellable.
|
|
|
+- **Job delivery is at-least-once.** A claim that goes stale is reclaimed and the job runs AGAIN, so anything reached by a job, a cron or a database event must be idempotent. A function that throws is NOT retried (one attempt, the author's to fix); what re-runs work is reclaim. See the error table above for `version_conflict`, which is how a conditional claim reports losing the race.
|
|
|
+- `ctx.crypto.hmacSha256(key, data, encoding?)` - HMAC-SHA256, `encoding` being `hex` (default) or `base64`. For verifying a provider's webhook signature.
|
|
|
+- `ctx.crypto.timingSafeEqual(a, b)` - constant-time string comparison. Use it to compare a signature rather than `===`, which leaks the position of the first difference.
|
|
|
+- `ctx.crypto.randomUUID()` - a version 4 UUID.
|
|
|
+- `ctx.time.parts(epochMs, zone)` - civil fields for an instant in an IANA zone: `{year, month, day, hour, minute, second, weekday, offsetSec, zone}`. Available without `Intl` having to be loaded.
|
|
|
+- `ctx.time.fromParts(parts, zone)` - the reverse. It reports a local time that does not exist (the DST spring-forward gap) rather than inventing one, and tells you when a local time is ambiguous (the autumn repeat).
|
|
|
+- `ctx.time.zoneKnown(zone)` - whether the host's time-zone database knows that name. An unknown zone is a catchable error everywhere else, never a silent fall back to UTC.
|
|
|
+- `ctx.time.format(epochMs, zone, pattern, locale?)` - format an instant, e.g. `format(ms, 'Europe/Budapest', 'YYYY. MMMM D., dddd', 'hu')`. An unknown locale is refused rather than served in English.
|
|
|
+- `Intl.DateTimeFormat` also works inside a function, installed per context.
|
|
|
- **`responseType: 'base64'` returns a BINARY response body** as base64. Needed for anything that is not text: the value handed to the engine is serialised as JSON, and a JSON string cannot hold a byte outside a valid UTF-8 sequence, so a non-text body is either base64 or it is refused. The refusal names this fix rather than surfacing a raw UTF-8 decode error.
|
|
|
- **`timeoutMs` narrows the call, never widens it**, and is capped by what is left of the run's budget. There is no connection pooling: every call builds its own client, so there is no keep-alive socket to go stale.
|
|
|
- **Exceeding the budget is 504 `fetch_timeout`, not `fetch_failed`.** The connect, read and write timeouts are set to the run's REMAINING budget, so a provider slower than that is cut off by us - and the underlying library words that as "Failed to read connection", which reads like a network fault. The error says how long the call took and how long it was allowed, so the two are distinguishable. A long provider call belongs on a **job** trigger, whose ceiling is far higher than an HTTP run's.
|
|
|
-- Sending a binary REQUEST body is not supported yet: `body` is a string.
|
|
|
+- **Sending a BINARY request body is supported** - this was previously undocumented, and a consumer concluded it was missing. `body` is text (a JS string). For bytes use **`bodyBase64`** (a base64 string, decoded before sending) or **`bodyBytes`** (an array of 0-255 integers). Exactly ONE of the three, never two: supplying both is refused with `ambiguous_body` rather than resolved by precedence, because reading `body` and ignoring a `bodyBase64` beside it would silently send the wrong payload. Invalid base64 is **422**.
|
|
|
+- **`Content-Type` is defaulted to `application/json` only for the TEXT shape.** A binary body is never given a default: labelling arbitrary bytes as JSON would be a lie a provider then rejects or mis-parses, so a caller sending bytes must say what they are.
|
|
|
- `ctx.env.<NAME>` - secrets for THIS project only, from two merged sources: the project's own secrets set over the API (see "Project secrets") and the runner's environment (`SVAPI_FN_<project>__<NAME>` in `runner.env`). A host variable wins over a stored secret of the same name. Never another project's, and never the runner's own configuration.
|
|
|
- `ctx.log(...)` - captured into the run's `console`, bounded.
|
|
|
|
|
|
@@ -269,6 +291,7 @@ export default async function (ctx) {
|
|
|
|
|
|
Public (no auth required):
|
|
|
|
|
|
+- `GET /version` and `GET /api/v1/version` - `{name, version, commit, db_client}`. The root one needs **no credential**; the `/api/v1` one needs any valid key (a scoped key is fine), because everything under `/api/` is authenticated. Ask it rather than probing a behaviour to work out which server you are talking to.
|
|
|
- `GET /healthz` - Liveness probe; always 200 while the process is running.
|
|
|
- `GET /readyz` - Readiness probe; 200 when the database is reachable, 503 otherwise.
|
|
|
- `GET /openapi.json` - OpenAPI 3.1 machine-readable spec.
|