> Complete content index: https://narsil.sondelali.com/llms.txt

# Container image

> Start a Narsil node from the published container image, search it from TypeScript, Python, or Go, choose between the TypeScript and Rust servers, and set the node up through environment variables.

URL: https://narsil.sondelali.com/docs/container
Section: Operations
Version: 0.4 (@delali/narsil@0.4.3, latest)

Narsil publishes container images at `ghcr.io/assetcorp/narsil`. Each image serves one Narsil node over HTTP and takes every setting from an environment variable, so you can deploy a search server without writing a startup program. The tag `<version>` holds the TypeScript server, while the tag `<version>-rust` holds the Rust server. The package is public, so Docker pulls either image with no sign-in.

On this page, you'll start a node with Docker Compose, add documents to it over HTTP, and search them from the TypeScript, Python, and Go clients. You'll then restart the node to see that the documents stay on its volume, switch the node to the Rust server, and change its settings. You need Docker with the Compose plugin, `curl`, and `openssl`, and to follow a client section, you need the toolchain of that language as well.

## Start a node

Create a folder for the node, download the Compose file into it, and write an admin key to `.env`:

```bash
mkdir narsil && cd narsil
curl -fsSLO https://raw.githubusercontent.com/assetcorp/narsil/main/packages/container/compose.yaml
export NARSIL_ADMIN_KEY="$(openssl rand -hex 32)"
echo "NARSIL_ADMIN_KEY=$NARSIL_ADMIN_KEY" > .env
docker compose up -d
```

The Compose file that you download holds one service:

```yaml title="compose.yaml"
name: narsil

services:
  narsil:
    image: ghcr.io/assetcorp/narsil:${NARSIL_IMAGE_TAG:-latest}
    restart: unless-stopped
    environment:
      NARSIL_ADMIN_KEY: ${NARSIL_ADMIN_KEY:?set NARSIL_ADMIN_KEY in .env to a key of at least 32 characters}
    ports:
      - "127.0.0.1:7700:7700"
    volumes:
      - narsil-data:/data

volumes:
  narsil-data:
```

Compose pulls the image under the tag in `NARSIL_IMAGE_TAG`, and it takes `latest` when `.env` holds no value for that variable. It publishes port 7700 on `127.0.0.1` alone, so only the programs on your machine can reach the node. It also mounts a volume called `narsil-data` at `/data`, which is the folder where the node keeps its indexes.

Compose reads `NARSIL_ADMIN_KEY` from `.env` each time that you start the node from this folder, and it stops with an error when the file holds no key. The node then refuses to start when the key holds fewer than 32 characters. The shell fills in `$NARSIL_ADMIN_KEY` in the commands on this page, so load `.env` into any new terminal with `set -a; . ./.env; set +a` before you go on.

Wait until the node reports that it is ready:

```bash
curl -fs --retry 30 --retry-delay 1 --retry-all-errors http://localhost:7700/readyz
```

```txt result open
{"status":"ready"}
```

The node answers `/readyz`, `/livez`, `/health`, and `/version` without a key, so that an orchestrator such as Kubernetes can probe the container. For every other route, the node expects the key in an `Authorization: Bearer` header, so it answers 401 with the code `UNAUTHORIZED` to a request without one.

## Add documents and search them

Create an index called `products`, with a text field for the name and a number field for the price:

```bash
curl -sS -X POST http://localhost:7700/indexes \
  -H "authorization: Bearer $NARSIL_ADMIN_KEY" \
  -H 'content-type: application/json' \
  -d '{"name":"products","config":{"schema":{"name":"string","price":"number"}}}'
```

```txt result open
{"name":"products"}
```

Add three bicycles in one batch:

```bash
curl -sS -X POST http://localhost:7700/indexes/products/documents/_batch \
  -H "authorization: Bearer $NARSIL_ADMIN_KEY" \
  -H 'content-type: application/json' \
  -d '{"documents":[
    {"id":"folding-metro","name":"Obi Metro folding bicycle","price":899},
    {"id":"folding-tourer","name":"Khoury Tourer folding bicycle","price":1150},
    {"id":"cargo-hauler","name":"Larsson Cargo hauler","price":3499}
  ]}'
```

```txt result open
{"succeeded":["folding-metro","folding-tourer","cargo-hauler"],"failed":[]}
```

The node writes the batch to its write-ahead log on the volume before it answers, so it keeps every document under `succeeded` in the answer across a restart. Search the names for `folding`:

```bash
curl -sS -X POST http://localhost:7700/indexes/products/search \
  -H "authorization: Bearer $NARSIL_ADMIN_KEY" \
  -H 'content-type: application/json' \
  -d '{"term":"folding"}'
```

```txt result open
{"hits":[{"id":"folding-metro","score":0.45315090947198405,"document":{"id":"folding-metro","name":"Obi Metro folding bicycle","price":899}},{"id":"folding-tourer","score":0.45315090947198405,"document":{"id":"folding-tourer","name":"Khoury Tourer folding bicycle","price":1150}}],"count":2,"countExact":true,"elapsed":2.349083000000064,"coverage":{"totalPartitions":1,"queriedPartitions":1,"timedOutPartitions":0,"failedPartitions":0}}
```

The node returns the two folding bicycles, because only their names hold the word. Each of those names holds `folding` once among four words, which is why the two hits share a score. `elapsed` is the time in milliseconds that the search takes on the node, so that figure will differ on your machine. The routes that the node serves are on [HTTP server](/docs/http-server).

## Search from TypeScript, Python, or Go

Each client takes the address of the node and the admin key, and it calls the same routes under the method names of its language. Create a folder for the client inside `narsil`, and install the client there, in a terminal where `NARSIL_ADMIN_KEY` is set:

<CodeGroup sync="language">

```bash title="pnpm" tab="TypeScript"
mkdir typescript && cd typescript
pnpm init
pnpm add -E @delali/narsil
```

```bash title="pip" tab="Python"
mkdir python && cd python
python3 -m venv .venv
.venv/bin/pip install narsil-client==0.2.0
```

```bash title="go get" tab="Go"
mkdir go && cd go
go mod init example.com/catalogue
go get github.com/assetcorp/narsil/packages/go@v0.1.3
```

</CodeGroup>

The TypeScript program needs Node.js 24, which executes a `.ts` file with no build step, and a `package.json` that sets `"type": "module"`. The Python client needs Python 3.11 or later, while the Go client needs Go 1.26 or later and no module beyond the standard library. Save the program below in the folder of its language, and start it from there with `node search.ts`, `.venv/bin/python search.py`, or `go run .`:

<CodeGroup sync="language">

```ts title="search.ts" tab="TypeScript"
import { createNarsilClient } from '@delali/narsil/client'

const client = createNarsilClient({ url: 'http://localhost:7700', apiKey: process.env.NARSIL_ADMIN_KEY })
const results = await client.query('products', { term: 'folding' })

for (const hit of results.hits) {
  console.log(hit.id)
}
```

```txt result open
folding-metro
folding-tourer
```

```python title="search.py" tab="Python"
import os

from narsil_client import NarsilClient

with NarsilClient("http://localhost:7700", api_key=os.environ["NARSIL_ADMIN_KEY"]) as client:
    results = client.query("products", {"term": "folding"})
    for hit in results.hits:
        print(hit.id)
```

```txt result open
folding-metro
folding-tourer
```

```go title="main.go" tab="Go"
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	narsil "github.com/assetcorp/narsil/packages/go"
)

func main() {
	client, err := narsil.New(narsil.Config{URLs: []string{"http://localhost:7700"}, APIKey: os.Getenv("NARSIL_ADMIN_KEY")})
	if err != nil {
		log.Fatal(err)
	}
	defer client.CloseIdleConnections()

	results, err := client.Query(context.Background(), "products", narsil.HTTPQueryParams{Term: narsil.Ptr("folding")})
	if err != nil {
		log.Fatal(err)
	}
	for _, hit := range results.Hits {
		fmt.Println(hit.ID)
	}
}
```

```txt result open
folding-metro
folding-tourer
```

</CodeGroup>

Each program prints the IDs of the two bicycles that the search over `curl` returns. On the [TypeScript client](/docs/client-sdk), [Python client](/docs/python-client), and [Go client](/docs/go-client) pages, a program follows a long task to its end and keeps working while one of two nodes is down.

## Keep the documents across a restart

`docker compose down` removes the container and keeps the `narsil-data` volume. From the `narsil` folder, start a new container and wait for it:

```bash
docker compose down
docker compose up -d
curl -fs --retry 30 --retry-delay 1 --retry-all-errors http://localhost:7700/readyz
```

```txt result open
{"status":"ready"}
```

Search the new container for `folding` again:

```bash
curl -sS -X POST http://localhost:7700/indexes/products/search \
  -H "authorization: Bearer $NARSIL_ADMIN_KEY" \
  -H 'content-type: application/json' \
  -d '{"term":"folding"}'
```

```txt result open
{"hits":[{"id":"folding-metro","score":0.45315090947198405,"document":{"id":"folding-metro","name":"Obi Metro folding bicycle","price":899}},{"id":"folding-tourer","score":0.45315090947198405,"document":{"id":"folding-tourer","name":"Khoury Tourer folding bicycle","price":1150}}],"count":2,"countExact":true,"elapsed":5.989125000000058,"coverage":{"totalPartitions":1,"queriedPartitions":1,"timedOutPartitions":0,"failedPartitions":0}}
```

As the new container starts, the node recovers the `products` index from the files under `/data/indexes`, so the search returns the same two bicycles with the same scores. `docker compose down --volumes` deletes the volume as well, which removes every index for good.

## Choose a tag

Each tag holds one release on one of the two servers:

| Tag | What the tag holds |
|-----|--------------------|
| `latest` | It holds the TypeScript server from the newest release. |
| `<major>.<minor>`, such as `0.4` | It holds the TypeScript server from the newest patch release of that minor version. |
| `<version>`, such as `0.4.3` | It holds the TypeScript server from one release, and Narsil never changes that image after it publishes the tag. |
| `next` | It holds the TypeScript server from the newest prerelease, which the publish workflow builds from each push to the main branch of the Narsil repository. |
| `latest-rust`, `<major>.<minor>-rust`, `<version>-rust`, and `next-rust` | It holds the Rust server from the same release as the tag without `-rust`. |

Each tag holds images for `linux/amd64` and `linux/arm64`, so Docker pulls the image that matches your machine. The publish workflow attaches SLSA provenance and an SBOM in SPDX format to each image, and `docker buildx imagetools inspect` prints both.

Pin a release in production, so that the node changes release only when you change the tag. Compose takes the tag from `NARSIL_IMAGE_TAG` in `.env`:

```bash
echo "NARSIL_IMAGE_TAG=0.4.3" >> .env
docker compose up -d
```

Compose replaces the container with one from the image under that tag, and it mounts the same volume in the new container. The node reports its release and the commit of its build at `GET /version`.

## Switch the node to the Rust server

Both servers read the same variables, serve the same routes, and keep their indexes in one file format, so you can switch a node between them by changing the tag alone. To switch the node on this page, change the line in `.env` to `NARSIL_IMAGE_TAG=0.4.3-rust`, then start the node again and wait for it:

```bash
docker compose up -d
curl -fs --retry 30 --retry-delay 1 --retry-all-errors http://localhost:7700/readyz
```

```txt result open
{"status":"ready"}
```

Search for `folding` once more:

```bash
curl -sS -X POST http://localhost:7700/indexes/products/search \
  -H "authorization: Bearer $NARSIL_ADMIN_KEY" \
  -H 'content-type: application/json' \
  -d '{"term":"folding"}'
```

```txt result open
{"hits":[{"id":"folding-metro","score":0.45315090947198405,"document":{"id":"folding-metro","name":"Obi Metro folding bicycle","price":899}},{"id":"folding-tourer","score":0.45315090947198405,"document":{"id":"folding-tourer","name":"Khoury Tourer folding bicycle","price":1150}}],"count":2,"countExact":true,"elapsed":0.308917,"coverage":{"totalPartitions":1,"queriedPartitions":1,"timedOutPartitions":0,"failedPartitions":0}}
```

The Rust server opens the index that the TypeScript server writes to the volume, so it returns the same two bicycles with the same scores. The client programs from the earlier section print the same two IDs against either server.

Only the files under `/data/indexes` have a format that both servers read. As a result, when a server can't read a task record under `tasks/` or a queued webhook delivery under `webhooks/`, it ignores that file and can delete it, so you can lose the history of finished tasks and the deliveries that wait in the queue when you switch.

The Rust image holds no `transformers` embedder or reranker, which is the kind that loads a model into the node. When a variable sets that kind, the startup program of the Rust image writes one line to standard error and exits with status 1:

```bash
docker run --rm \
  -e NARSIL_ADMIN_KEY="$NARSIL_ADMIN_KEY" \
  -e NARSIL_EMBEDDERS=minilm \
  -e NARSIL_EMBEDDER_MINILM_KIND=transformers \
  -e NARSIL_EMBEDDER_MINILM_DIMENSIONS=384 \
  ghcr.io/assetcorp/narsil:latest-rust
echo $?
```

```txt result open
NARSIL_EMBEDDER_MINILM_KIND must be openai, because this image leaves out the transformers kind
1
```

A node whose indexes use a `transformers` embedder or reranker therefore needs a tag without `-rust`, while the `openai` embedder and the `http` reranker work on both servers.

Only the TypeScript server works in cluster mode, so a node that joins a cluster has to use a tag without `-rust`. Each image serves one node, so to build the nodes of a cluster in code on the TypeScript server, follow [Cluster](/docs/cluster).

## Change a setting

Every setting is an environment variable whose name begins with `NARSIL_`. Add the variable under `environment` in `compose.yaml`, such as `NARSIL_LANGUAGES` to register a second language module, and start the node again with `docker compose up -d`:

```yaml title="compose.yaml"
name: narsil

services:
  narsil:
    image: ghcr.io/assetcorp/narsil:${NARSIL_IMAGE_TAG:-latest}
    restart: unless-stopped
    environment:
      NARSIL_ADMIN_KEY: ${NARSIL_ADMIN_KEY:?set NARSIL_ADMIN_KEY in .env to a key of at least 32 characters}
      NARSIL_LANGUAGES: english,french # [!code ++]
    ports:
      - "127.0.0.1:7700:7700"
    volumes:
      - narsil-data:/data

volumes:
  narsil-data:
```

To start a node without Compose, pass each variable to `docker run` with `-e`, and mount a volume at `/data` so that your indexes stay across a restart:

```bash
docker run --rm -p 7700:7700 \
  -e NARSIL_ADMIN_KEY="$NARSIL_ADMIN_KEY" \
  -v narsil-data:/data \
  ghcr.io/assetcorp/narsil:latest
```

The startup program checks every variable before it binds the port. When a value breaks its rule, the program writes one line to standard error that gives the variable and the rule, and it exits with status 1:

```bash
docker run --rm -e NARSIL_ADMIN_KEY=too-short ghcr.io/assetcorp/narsil:latest
echo $?
```

```txt result open
NARSIL_ADMIN_KEY must hold at least 32 characters
1
```

That line never holds the value of a key or a secret, so you can forward the logs of the container to a shared system.

An unset variable and an empty variable both take the default. Write a whole number in decimal digits alone, a boolean as `true` or `false`, and a list as items separated by commas. The startup program trims the spaces around each item of a list and refuses an empty item. For each variable that begins with `NARSIL_` and appears nowhere in the tables below, the program writes a warning line and goes on starting, because Kubernetes adds variables such as `NARSIL_SERVICE_HOST` for a service called `narsil`.

## Every setting that the image reads

Both images read every variable below with the same meaning, apart from the `transformers` kind of adapter, which only the TypeScript image accepts.

### Address and network

| Variable | Default | Meaning |
|----------|---------|---------|
| `NARSIL_HTTP_HOST` | `0.0.0.0` | The server binds to this address. |
| `NARSIL_HTTP_PORT` | `7700` | The server binds to this port, a whole number from 1 to 65,535. |
| `NARSIL_CORS_ORIGINS` | none | The server accepts cross-origin requests from the origins in this list, or from any origin when the value is `*`. |
| `NARSIL_ALLOW_INSECURE` | `false` | With `true`, the server may start with no key set. |
| `NARSIL_INSTANCE_ID` | the host name | The server stamps this identifier on every task that it owns. |

The host and port variables have `HTTP` in their names, because Kubernetes sets `NARSIL_PORT` to a URL in every pod beside a service called `narsil`. When neither key from the next section is set and `NARSIL_ALLOW_INSECURE` is `false`, the node exits with status 1.

### Keys and tokens

| Variable | Meaning |
|----------|---------|
| `NARSIL_ADMIN_KEY` | A request with this key may call every route. |
| `NARSIL_READ_KEY` | A request with this key may call the read routes. |

Each key has to hold at least 32 characters, and the two keys have to differ. A client sends a key as `Authorization: Bearer <key>`, while in a WebSocket upgrade, a client can send it as the `Sec-WebSocket-Protocol` value that follows `narsil.sync.v1` or `narsil.changes.v1`. The server compares each presented key with each configured key in constant time.

The read routes are every `GET` route except `GET /indexes/{name}/snapshot` and `GET /indexes/{name}/export`, along with the `POST` routes `/indexes/{name}/search`, `/indexes/{name}/search/preflight`, `/indexes/{name}/suggest`, `/indexes/{name}/documents/_list`, `/indexes/{name}/documents/_multi-get`, `/indexes/{name}/_wait-for-writes`, and `/indexes/{name}/query-suggestions/record`.

A backend can hand a browser or a phone a token in place of a key, so that the device holds a credential that expires. A token is a JSON Web Token with `alg` set to `HS256` and signed with the UTF-8 bytes of the admin key or of the read key, and the server grants it the routes of the key that verifies its signature. The server refuses a token whose `alg` is anything other than `HS256`, a token without `exp`, a token whose `exp` is no later than the current time, and a token whose `nbf` is more than 60 seconds later than the current time. A token can also hold these claims:

- `indexes` holds a list of index names, and the server then admits the token only to the probe routes and to the routes whose path holds one of those names.
- `sub` and `group` hold the person and the group that [query suggestions](#query-suggestions) count.

The server treats a token as a grant that expires at `exp`, so it closes a device sync feed or a change feed under that token with the close code 4401 at that time.

| Status | Code | When the server answers with it |
|--------|------|---------------------------------|
| 401 | `UNAUTHORIZED` | A request outside the probe routes has no credential, or it has a key or a token that the server can't verify. |
| 403 | `FORBIDDEN` | The server verifies the credential, but the route is outside its role or outside its `indexes`. |

### Storage on the volume

| Variable | Default | Meaning |
|----------|---------|---------|
| `NARSIL_STORAGE` | `filesystem` | With `filesystem`, the node keeps its data under `NARSIL_DATA_DIR`, while with `memory`, it keeps nothing across a restart. |
| `NARSIL_DATA_DIR` | `/data` | The node keeps its data in this folder. |
| `NARSIL_DURABILITY_MODE` | `sync` | The node writes its write-ahead log in this mode, `sync` or `async`, as [Persistence and durability](/docs/persistence-and-durability#choose-how-many-writes-you-can-lose-in-a-crash) describes. |

With `filesystem`, the node keeps four folders inside `NARSIL_DATA_DIR`. `indexes/` holds the indexes and their write-ahead log, `tasks/` holds the task records, `webhooks/` holds the deliveries that wait to go out, and `models/` holds the files of each `transformers` model. Because these folders stay on the volume, a node that restarts on the same volume keeps its documents, its task history, and the models that it downloads, so it can embed text without network access after the first download. With `memory`, the node writes a warning line that a restart loses every index, and it keeps the files of each model in the temporary folder of the operating system.

### Languages and worker threads

| Variable | Default | Meaning |
|----------|---------|---------|
| `NARSIL_LANGUAGES` | `english` | The node registers the language modules in this list before it creates the engine. |
| `NARSIL_WORKERS` | the default of the engine | The engine holds worker copies of an index on this many threads, and with `0`, the engine keeps no worker copies. |
| `NARSIL_PROMOTION_THRESHOLD` | `1000` | An index gains worker copies once it holds this many documents. |
| `NARSIL_ALLOW_REGEX` | `true` | The server accepts a `regex` test in a filter. |

The node exits with status 1 when `NARSIL_LANGUAGES` holds a name that the image has no module for. It also exits with status 1 when a saved index needs a language outside the list, and the error line then gives the index and the language. For the language modules, see [Language support](/docs/language-support), and for the worker copies, see [Partitions and workers](/docs/partitions-and-workers).

### Limits

The node sets each server limit from the variable with the matching name, and it keeps the default of the server when that variable is unset. For what the body, result window, and request limits do, see [HTTP server](/docs/http-server#set-limits-before-you-open-the-address).

| Variable | Default |
|----------|---------|
| `NARSIL_LIMIT_MAX_BODY_BYTES` | 16,777,216 |
| `NARSIL_LIMIT_MAX_IMPORT_BYTES` | 104,857,600 |
| `NARSIL_LIMIT_MAX_RESTORE_BYTES` | 68,719,476,736 |
| `NARSIL_LIMIT_MAX_LINE_BYTES` | 4,194,304 |
| `NARSIL_LIMIT_IMPORT_BATCH_SIZE` | 1,000 |
| `NARSIL_LIMIT_MAX_CONCURRENT_REQUESTS` | 0, which sets no bound |
| `NARSIL_LIMIT_MAX_BODY_BYTES_IN_FLIGHT_FRACTION` | 0.1, a decimal from 0 to 1 |
| `NARSIL_LIMIT_MAX_RESULT_WINDOW` | 10,000 |
| `NARSIL_LIMIT_MAX_RERANK_WINDOW` | 100 |
| `NARSIL_LIMIT_MAX_FETCH_DOCUMENTS` | 10,000 |
| `NARSIL_LIMIT_MAX_IMPORT_ERRORS` | 100 |
| `NARSIL_LIMIT_MAX_TASK_PAGE_SIZE` | 1,000 |
| `NARSIL_LIMIT_MAX_CONCURRENT_TASKS` | 4 |

### Embedding and rerank adapters

`NARSIL_EMBEDDERS` and `NARSIL_RERANKERS` each hold a list of adapter names, and you refer to an adapter by its name in an index or a query. A name has to match `[a-z0-9][a-z0-9_-]{0,63}`. The node reads the settings of each adapter from the variables with its infix, which is the name in upper case with every `-` written as `_`, so it reads the kind of an embedder called `support-minilm` from `NARSIL_EMBEDDER_SUPPORT_MINILM_KIND`. When two names give the same infix, the node exits with status 1.

| Variable | Default | Meaning |
|----------|---------|---------|
| `NARSIL_EMBEDDER_<INFIX>_KIND` | none, required | With `openai`, the adapter calls an embedding endpoint that follows the OpenAI format, while with `transformers`, it loads a model into the node. |
| `NARSIL_EMBEDDER_<INFIX>_URL` | none, required for `openai` | The adapter sends its requests to this base URL. |
| `NARSIL_EMBEDDER_<INFIX>_API_KEY` | none | The adapter sends this key to the endpoint. |
| `NARSIL_EMBEDDER_<INFIX>_MODEL` | required for `openai`, `Xenova/all-MiniLM-L6-v2` for `transformers` | The adapter embeds text with this model. |
| `NARSIL_EMBEDDER_<INFIX>_DIMENSIONS` | none, required | The adapter returns vectors of this length, which has to equal the length that the vector field declares. |
| `NARSIL_EMBEDDER_<INFIX>_TIMEOUT_MS` | 30,000 | The adapter abandons a request after this many milliseconds. |
| `NARSIL_EMBEDDER_<INFIX>_MAX_RETRIES` | 3 | The adapter tries a failed request again this many times. |

| Variable | Default | Meaning |
|----------|---------|---------|
| `NARSIL_RERANKER_<INFIX>_KIND` | none, required | With `http`, the adapter calls a `/rerank` endpoint in the request format that Cohere defines, while with `transformers`, it loads a cross-encoder model into the node. |
| `NARSIL_RERANKER_<INFIX>_URL` | none, required for `http` | The adapter sends its requests to this base URL. |
| `NARSIL_RERANKER_<INFIX>_API_KEY` | none | The adapter sends this key to the endpoint. |
| `NARSIL_RERANKER_<INFIX>_MODEL` | required for `http`, `Xenova/ms-marco-MiniLM-L-6-v2` for `transformers` | The adapter scores documents with this model. |
| `NARSIL_RERANKER_<INFIX>_TIMEOUT_MS` | 30,000 | The adapter abandons a request after this many milliseconds. |
| `NARSIL_RERANKER_<INFIX>_MAX_RETRIES` | 3 | The adapter tries a failed request again this many times. |
| `NARSIL_RERANKER_<INFIX>_MAX_DOCUMENTS_PER_REQUEST` | 1,000 | The adapter sends at most this many documents in one request. |

The startup program of the Rust image accepts only the `openai` embedder and the `http` reranker. For how an index and a query use each adapter, see [Embedding adapters](/docs/embedding-adapters) and [Reranking](/docs/reranking).

### Device sync and change feeds

| Variable | Default | Meaning |
|----------|---------|---------|
| `NARSIL_SYNC` | `false` | With `true`, the server turns on the routes for [device sync](/docs/device-sync). |
| `NARSIL_CHANGES` | `false` | With `true`, the server turns on the [change feed](/docs/change-capture). |

The node exits with status 1 when either variable is `true` and no key is set.

### Query suggestions

| Variable | Default | Meaning |
|----------|---------|---------|
| `NARSIL_QUERY_SUGGESTIONS` | `false` | With `true`, the server counts searches for [query suggestions](/docs/query-suggestions). |
| `NARSIL_QUERY_SUGGESTIONS_KEY` | none, required when `NARSIL_QUERY_SUGGESTIONS` is `true` | The node scrambles the ID of each person with this key, whose UTF-8 form has to hold at least 32 bytes. |

The node exits with status 1 when `NARSIL_QUERY_SUGGESTIONS` is `true` and the key is missing or shorter than 32 bytes. The server takes the person and the group of each search from the credential of that search:

- The server counts a search under a token for the `sub` and the `group` of that token.
- The server counts a search under the admin key for the person in the `Narsil-Person` header and the group in the `Narsil-Group` header.
- The server counts nothing for a search under the read key or for a search with no credential.

When a search has no person or no group, or when either value is in the wrong format, the server counts nothing for that search and answers it as usual.

### Events and webhooks

The node writes every engine event other than `write`, and every finished task, to standard output as one line of JSON, in the shape `{"type":"task.finished","timestamp":"...","data":{...}}`. With a webhook URL set, it also sends the same body to that URL.

| Variable | Default | Meaning |
|----------|---------|---------|
| `NARSIL_WEBHOOK_URL` | none | The node delivers events to this URL. |
| `NARSIL_WEBHOOK_SECRET` | none, required with a URL | The node signs each delivery with this secret, which is `whsec_` followed by the base64 of 24 to 64 random bytes. |
| `NARSIL_WEBHOOK_EVENTS` | every type | The node delivers only the types in this list. |

`echo "whsec_$(openssl rand -base64 32)"` prints a secret of 32 random bytes in that form. An event type is `engine.` followed by the name of the event, such as `engine.workerCrash`, or it is `task.finished`. The `write` event has no type, because the change feed delivers every write. The node exits with status 1 when `NARSIL_WEBHOOK_EVENTS` holds a name that matches no type.

The node signs each delivery under the [Standard Webhooks](https://www.standardwebhooks.com/) scheme, so a receiver can check it with a library for that scheme:

- Each delivery is a `POST` whose body holds `type`, a `timestamp` in RFC 3339 form, and `data`, which is the payload of the event or the task record.
- The `webhook-id` header holds a unique message ID, and `webhook-timestamp` holds the send time in whole seconds since the Unix epoch. `webhook-signature` holds `v1,` followed by the base64 of the HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<body>`, which the node computes with the decoded bytes of the secret as the key.
- The node keeps its queue of deliveries under `webhooks/` with `filesystem` storage, so delivery resumes after a restart. The queue holds at most 10,000 deliveries, so once it is full, the node drops the oldest delivery and writes the count of dropped deliveries to standard output.
- The node sends at most 4 deliveries at once, in any order, and it abandons a send after 15 seconds. It retries each delivery on a separate schedule, so one failing delivery delays no other.
- The node marks a delivery complete on a 2xx answer, while on a 410 answer, it stops every delivery until it restarts. After any other answer, or a failed send, the node tries again 5 seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours, 14 hours, 20 hours, and 24 hours after each failed try in turn. It lengthens each wait by up to 10% at random, so the last of the nine retries comes between about 75.6 and 83.1 hours after the first failure. When that retry fails, the node drops the delivery and writes a line to standard output.

### Shutdown

The startup program shuts the server and the engine down when the process receives `SIGTERM`, which `docker stop` and `docker compose down` send, or `SIGINT`. It exits with status 0 after a clean shutdown and with status 1 otherwise.

## Memory and file ownership

The TypeScript image sets `NODE_OPTIONS=--max-old-space-size-percentage=75`, so the heap of the engine can grow to three quarters of the memory that you give the container. Node.js ends the process once the heap outgrows that limit, so size the memory of the container for the indexes that you expect it to hold. Both images set `LD_PRELOAD` so that the process loads jemalloc, because jemalloc returns the memory that the threads of the server free to the system, while the default allocator in glibc can keep that memory.

The TypeScript server works as the `node` user and the Rust server as the `narsil` user. Both users have the user ID 1000, so you can mount one volume in either image. A folder that you mount at `/data` in place of a volume has to be writable by the user ID 1000.
