|
|
@@ -499,7 +499,11 @@ export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method:
|
|
|
|
|
|
export default async function (ctx) {
|
|
|
const docs = await ctx.collections('kb_chunks')
|
|
|
- .filter(`topic:eq:${ctx.params.topic}`).limit(20).find();
|
|
|
+ // JSON.stringify, NOT bare interpolation: a filter value is JSON-parsed
|
|
|
+ // with a fallback to a literal string, so a bare topic of `2026` or `true`
|
|
|
+ // is read as a number or a boolean and matches nothing, answering 200 with
|
|
|
+ // an empty array - indistinguishable from an empty collection.
|
|
|
+ .filter(`topic:eq:${JSON.stringify(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'] });
|
|
|
ctx.log('found', docs.length, 'documents');
|
|
|
@@ -522,10 +526,11 @@ export default async function (ctx) {
|
|
|
- **A project can be denied the network entirely.** `PUT /api/v1/projects/{p}/settings/functions` with `{"network_egress":"deny"}` (admin only) stops **both** `ctx.fetch` and `ctx.mail` for that project, refused as `egress_blocked` **before any name is resolved** - so a denied project emits no DNS query either. `"allow"` restores it, `null` inherits. The GET returns the effective value plus `network_egress_set`, which says whether it was chosen for the project or inherited. The default is **allow**, for compatibility rather than preference: `ctx.fetch` shipped with no gate, so defaulting to deny would have stopped every already-deployed function that makes an outbound call. One setting covers both surfaces on purpose - gating one and not the other would let an operator believe a tenant was offline while the other stayed open.
|
|
|
- **A BINARY request body arrives as base64, not in `ctx.body`.** When the bytes are not valid UTF-8 - an image, a PDF, a protobuf - `ctx.body` is **`null`**, `ctx.bodyBase64` carries the bytes and `ctx.bodyEncoding` is `"base64"`. They go under their own keys rather than into `ctx.body` on purpose: base64 in `ctx.body` would hand a function that knows nothing of binary a plausible-looking string that is not the body that was sent, and silent corruption is worse than an obvious `null`. `ctx.bodyEncoding` is **absent** for a text body, so a function written before this behaves exactly as it did. Note the bytes decide and the content type does not: a body declared `application/json` that cannot be a JSON string is still offered as base64.
|
|
|
|
|
|
-- `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.
|
|
|
-- **THE FUNCTION BUILDER ASSIGNS DOCUMENT IDS. A function CANNOT choose one, and there is no upsert.** This is the single most important difference between `ctx.collections(...)` and the HTTP routes, and this file previously implied the opposite. `.insert(doc)` returns `{id}` with an id the SERVER generated: an `id` or `_id` in the body is stripped (the same reserved-field strip the HTTP route does), and `.insert(doc, {id})` is refused by name because `ttl_seconds` is the only option it takes. `.update(id, doc)` on a document that does not exist is **404 `not_found`** - it is a replace, never an upsert - and `.increment(id, deltas)` likewise requires the row to exist.
|
|
|
- **SO THE COUNTER PATTERN THIS FILE AND OUR OWN MESSAGES RECOMMENDED IS IMPOSSIBLE HERE, AND IT FAILS SILENTLY RATHER THAN LOUDLY.** The advice was "increment; on NotFound insert with the starting value at a FIXED id; on AlreadyExists increment again". That is correct for the **C++ client**, where an id is an argument, and it was transplanted here without checking that this surface has the capability. From a function, "insert at a fixed id" is really "insert a NEW row", so the `AlreadyExists` branch is **unreachable** - there is never a collision - and a throttle built this way creates a fresh row per call, every one at `1`. Measured by a consumer on prod: **six of six calls admitted against a limit of three.** Fourteen of their unit tests passed, because their fake honoured the id in the body, which the real API discards.
|
|
|
- **THE PATTERN THAT WORKS, and it needs an index**: find the window row by FILTER rather than by id, and make the create race safe with a **composite unique index** on the identifying fields (for a throttle: kind, key, bucket). Two runs racing to create the same window means one gets **409 `duplicate_values`**, and the loser re-finds the winner's row and increments that. Verified live by the consumer who found this: six sequential calls on a limit of three gave 3 allowed then 3 refused, and **five SIMULTANEOUS calls gave exactly 3 allowed and 2 refused with one window row at `3`**. Without the index the concurrent case silently allows **twice** the limit, which is the only condition a throttle exists for - so the index is not an optimisation here, it is the correctness.
|
|
|
+- `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. **QUOTE ANY CALLER-SUPPLIED FILTER VALUE WITH `JSON.stringify`.** The value is run through `json::parse` with a fallback to a literal string, so a path parameter or query value that happens to parse as JSON changes type under you: a topic of `2026` becomes the number 2026 and a topic of `true` becomes a boolean, neither of which matches the string stored in the field. The result is **200 with an empty array**, which is indistinguishable from the collection genuinely having no such rows - so it fails silently and in the direction nobody checks.
|
|
|
+- **`.insert(doc)` HONOURS AN `id` INSIDE THE DOCUMENT OBJECT - that is the idiom for an idempotent write - BUT `_id` IS SILENTLY IGNORED, AND THAT ASYMMETRY IS THE WHOLE TRAP.** `id` becomes the document's identity and is stripped from the stored BODY (it is the row's name, not one of its fields), so it reads back as `_id` and not as `id`. `_id` in the body is stripped as read-only metadata and **does NOT set the identity**, so an insert keyed on `_id` quietly gets a server-generated id instead - the row is stored, the call returns `{id}`, and the id is not the one you asked for. A taken id is **409**, carrying `duplicate_id` against database 2.12.1 or newer and `duplicate_values` against anything older - that refusal is what makes the pattern idempotent rather than silently duplicating. **A NON-STRING `id` IS NOT HONOURED AND IS STILL REMOVED**, so `{id: 123}` loses the field AND gets a server-generated id: quote it. `.insert(doc, {id})` is refused by name, because the id belongs in the document and **`ttl_seconds` is the only option `.insert()` takes** - `ifVersion` is refused on an insert too, since a document that does not yet exist has no version to be conditional on. **`.store()` PLACES THE ID DIFFERENTLY, and the difference is exactly the kind that caused this entry's own error**: `.store()` takes ONE object, so `id` sits beside `text` in that call (`.store({id, text})`) rather than inside a nested document - and an `id` tucked inside `metadata` is discarded, the same silent ignoring `_id` gets on an insert. `.update(id, doc)` on a document that does not exist is **404 `not_found`** - it is a replace, never an upsert - and `.increment(id, deltas)` likewise requires the row to exist.
|
|
|
+ **THIS FILE SAID THE OPPOSITE FROM 0.22.3 UNTIL 2026-11-21 - "the builder assigns document ids, a function CANNOT choose one" - AND IT WAS SIMPLY WRONG.** Refuted by a consumer measuring the deployed 0.22.3 (`.insert({id:'chosen-one'})` returns `{id:'chosen-one'}` and reads back at that `_id`; a second insert at it is 409; `_id` is ignored) and confirmed in the source of the serving artefact: `insert()` reads `payload.doc.id` and passes it as the document id, in code dating from the commit that created the runner, so **the behaviour has never changed and only the documentation moved.** The wrong sentence was written while correcting a different error and corrected past the truth. A consumer's live reviewer registration depends on e-mail-as-id, and had anyone made the server match this file, that would have locked out every new reviewer.
|
|
|
+ **WHAT THE RETRACTED PARAGRAPH GOT RIGHT IS THE SYMPTOM, AND THE CAUSE IS ONE CHARACTER AWAY FROM WHAT IT CLAIMED.** A counter built as "increment; on NotFound insert the starting value at a FIXED id; on AlreadyExists increment again" **does work** when the key is `id`: the collision is real, so the `AlreadyExists` branch is reachable. It fails exactly as described - a fresh row per call, every one at `1`, **six of six calls admitted against a limit of three**, measured on prod - when the id is passed as `_id` or as an option, because then nothing sets the identity and every "insert at a fixed id" is an insert of a NEW row. So the failure was real and the diagnosis was one layer off: the capability exists and that spelling does not reach it. **An insert whose chosen id does not come back in `{id}` is the tell**, and it is worth asserting rather than assuming, because the row stores and the call succeeds either way.
|
|
|
+ **THE INDEX-BASED PATTERN REMAINS CORRECT AND IS STILL THE ONE TO REACH FOR WHEN THE WINDOW IS NOT ADDRESSABLE BY ID**: find the row by FILTER, and make the create race safe with a **composite unique index** on the identifying fields (for a throttle: kind, key, bucket). The loser of a race gets **409 `duplicate_values`**, re-finds the winner's row and increments that. Verified live: six sequential calls on a limit of three gave 3 allowed then 3 refused, and **five SIMULTANEOUS calls gave exactly 3 allowed and 2 refused with one window row at `3`**. Where the window IS addressable by a deterministic id, the fixed-id insert is race-safe for the same reason by way of `duplicate_id`, and needs no index.
|
|
|
- **A FILTERED `.find()` NEEDS THE `list` GRANT, NOT `read`.** `read` covers `.get(id)` only. A policy of read/insert/update therefore throws on every `.find()`, and because the scope refusal deliberately cannot distinguish "not granted" from "does not exist", the symptom is simply that your function fails - which reads as the feature being broken rather than as a missing grant. The message does name `operation 'list'`; read it rather than inferring. Op to grant, in full: `.find()` is `list`, `.get()` is `read`, `.insert()`/`.store()` are `insert`, `.update()`/`.patch()`/`.increment()` are `update`, `.delete()` is `delete`, `.search()` is `search`.
|
|
|
- **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.
|