Operations

HTTP server

Serve an engine over HTTP from TypeScript or Rust, admit only the callers that hold a token, call it from TypeScript, Python, or Go, generate a client from its OpenAPI description, and stop it so that the process exits cleanly.

@delali/narsil/server puts a REST API in front of an engine that you configure yourself, so you keep control of the durability, the embedding adapters, and the worker threads. The delali-narsil-server crate serves the same single-node routes from a Rust program. The programs that call either server can use the TypeScript, Python, or Go client. To serve a node without writing a startup program, start the container image, whose tags that end in -rust contain the Rust server.

On this page, you'll build server.ts, a program that starts a server, admits only the callers that hold a token, and leaves the server working until the process receives a signal to stop. You'll then build the same server in Rust, and client, a program that searches the server and copies an index through the export and import routes. Each code block below contains the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.

Install the peer dependency

The server uses uWebSockets.js, which the package declares as an optional peer dependency, so install it from its GitHub release beside Narsil.

pnpm
pnpm add -E uWebSockets.js@github:uNetworking/uWebSockets.js#v20.70.0

The feeds for device sync and change capture require v20.69.0 or v20.70.0. An earlier release can drop a feed connection as soon as it opens, while v20.71.0 fails to load as an ES module.

Start a server

createServer(engine, options) accepts the engine and an address, while listen() resolves once the server accepts connections. A server bound to 127.0.0.1 accepts callers only from the same machine, which suits a first test. The program then calls the search route of its server, whose body accepts the same options as query.

server.ts
import { createNarsil } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'
 
const engine = await createNarsil()
 
await engine.createIndex('articles', { schema: { title: 'string', body: 'string' } })
await engine.insertBatch('articles', [
  { id: 'refund-timing', title: 'How a refund reaches your bank', body: 'A refund returns to the card that paid for the order.' },
  { id: 'parcel-tracking', title: 'Track a parcel after dispatch', body: 'Every dispatched order has a tracking code.' },
])
 
const server = createServer(engine, { host: '127.0.0.1', port: 7700 })
 
await server.listen()
 
const response = await fetch('http://127.0.0.1:7700/indexes/articles/search', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ term: 'refund', document: { include: ['title'] } }),
})
 
console.log(response.status, JSON.stringify((await response.json()).hits))
 
await server.shutdown()
200 [{"id":"refund-timing","score":1.3862943611198906,"document":{"title":"How a refund reaches your bank"}}]

POST /indexes/articles/search returns the same hits that query returns in the process. On Node.js, the server receives requests on the worker threads that contain the worker copies of the index, with one thread for each thread in workers.count. server.requestThreadCount reports the number of request threads that the server starts, which is 8 on an 11-core machine. Once an index has worker copies, a request thread answers a search on that index from the copy on the thread, while it passes every write and every admin request to the main thread. A write therefore returns before every copy contains it, so pass options.wait: true with the write, or call POST /indexes/{name}/_wait-for-writes, before a search that has to include it.

Admit only the callers that hold a token

The server calls onRequest before every routed request, with the method, the path, the headers keyed by lower-case name, and the peer address. Return a denial with a status, a code, and a message to refuse the request, or return undefined to let the request through. Without an onRequest hook, createServer fails with CONFIG_INVALID for any address other than loopback, because a caller of the admin routes can drop, clear, and restore indexes. With allowInsecure: true, the server skips that check, which suits a trusted private network.

server.ts
import { createNarsil } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'
 
const engine = await createNarsil()
 
await engine.createIndex('articles', { schema: { title: 'string', body: 'string' } })
await engine.insertBatch('articles', [
  { id: 'refund-timing', title: 'How a refund reaches your bank', body: 'A refund returns to the card that paid for the order.' },
  { id: 'parcel-tracking', title: 'Track a parcel after dispatch', body: 'Every dispatched order has a tracking code.' },
])
 
const server = createServer(engine, { host: '127.0.0.1', port: 7700 }) 
const API_TOKEN = process.env.NARSIL_API_TOKEN ?? 'support-desk-token'
 
const server = createServer(engine, {
  host: '127.0.0.1',
  port: 7700,
  onRequest: (request) =>
    request.headers.authorization === `Bearer ${API_TOKEN}`
      ? undefined
      : { status: 401, code: 'UNAUTHORISED', message: 'Send the API token as a bearer token.' },
})
 
await server.listen()
 
const response = await fetch('http://127.0.0.1:7700/indexes/articles/search', { 
  method: 'POST', 
  headers: { 'content-type': 'application/json' }, 
  body: JSON.stringify({ term: 'refund', document: { include: ['title'] } }), 
}) 
const search = (token?: string): Promise<Response> =>
  fetch('http://127.0.0.1:7700/indexes/articles/search', {
    method: 'POST',
    headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
    body: JSON.stringify({ term: 'refund', document: { include: ['title'] } }),
  })
 
const denied = await search()
const allowed = await search(API_TOKEN)
 
console.log(response.status, JSON.stringify((await response.json()).hits)) 
console.log(denied.status, await denied.text()) 
console.log(allowed.status, JSON.stringify((await allowed.json()).hits))
 
await server.shutdown()
401 {"error":{"code":"UNAUTHORISED","message":"Send the API token as a bearer token."}}
200 [{"id":"refund-timing","score":1.3862943611198906,"document":{"title":"How a refund reaches your bank"}}]

The server answers the request without a token with 401 and the denial as its error envelope, while it answers the request with the token with the hits. The server answers /livez, /readyz, /health, /version, and /capabilities without calling the hook, so that a load balancer can probe the server without credentials. The server starts with the device sync feed or the change capture feed turned on only when it has an onRequest hook, because each feed sends whole documents.

Keep the server working until the process stops

A server process usually goes on working until its supervisor sends SIGTERM, or until you press Ctrl+C in a terminal, which sends SIGINT. In this step, you remove the two test searches from the last step, and the program stops the server when the process receives either signal.

server.ts
import { createNarsil } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'
 
const engine = await createNarsil()
 
await engine.createIndex('articles', { schema: { title: 'string', body: 'string' } })
await engine.insertBatch('articles', [
  { id: 'refund-timing', title: 'How a refund reaches your bank', body: 'A refund returns to the card that paid for the order.' },
  { id: 'parcel-tracking', title: 'Track a parcel after dispatch', body: 'Every dispatched order has a tracking code.' },
])
 
const API_TOKEN = process.env.NARSIL_API_TOKEN ?? 'support-desk-token'
 
const server = createServer(engine, {
  host: '127.0.0.1',
  port: 7700,
  onRequest: (request) =>
    request.headers.authorization === `Bearer ${API_TOKEN}`
      ? undefined
      : { status: 401, code: 'UNAUTHORISED', message: 'Send the API token as a bearer token.' },
})
 
await server.listen()
 
const search = (token?: string): Promise<Response> =>
  fetch('http://127.0.0.1:7700/indexes/articles/search', {
    method: 'POST',
    headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
    body: JSON.stringify({ term: 'refund', document: { include: ['title'] } }),
  })
 
const denied = await search()
const allowed = await search(API_TOKEN)
 
console.log(denied.status, await denied.text())
console.log(allowed.status, JSON.stringify((await allowed.json()).hits))
 
await server.shutdown()
const stop = async (): Promise<void> => { 
  await server.shutdown()
  process.exit(0)
}
 
process.once('SIGTERM', stop)
process.once('SIGINT', stop)
 
console.log(`Narsil answers on port ${server.listeningPort}`)
Narsil answers on port 7700

server.shutdown() stops the server and then shuts the engine down, which ends the worker threads. In measured tests, each way of stopping a server after it answers a search ends the process in the way that this table shows:

The program callsThe process
await server.shutdown()exits with 0.
await server.close(), then await engine.shutdown()exits with 0.
await server.close() alonegoes on working, because Node.js exits a process only once the threads of the engine stop.

server.close() stops the server from taking requests and leaves the engine working. That suits a process that puts two servers in front of one engine, because the process can shut the engine down after it closes the last server. The server answers /readyz and /health with 503 from the moment that shutdown begins, so a load balancer that probes either route stops sending traffic to the server before it closes.

Serve the same index from Rust

The delali-narsil-server crate serves an engine from the Rust crate over the same single-node routes as @delali/narsil/server, with the same statuses, error codes, and limits, so every client on this page can call it unchanged. Add it beside the engine crate, together with Tokio, which is the async runtime that the server uses:

cargo
cargo add delali-narsil delali-narsil-server
cargo add tokio --features rt-multi-thread,macros,signal

NarsilServer::new takes the engine in an Arc and a ServerOptions, which has a field for every option of createServer apart from cluster, under its snake-case name, such as on_request and allow_insecure.

The accept_queue_length field requires delali-narsil-server 0.1.6 or later. It sets how many TCP connections the operating system queues for the server until the server accepts them. By default, the server requests the largest queue that the operating system allows. On Linux, net.core.somaxconn sets that limit. If you set accept_queue_length to zero, NarsilServer::new returns CONFIG_INVALID.

The on_request hook receives a RequestContext with the method, the path, the headers keyed by lower-case name, and the peer address. It returns RequestDecision::Allow to let the request through, or RequestDecision::Deny with a status, a code, and a message to refuse it. The program below does the same work as server.ts from the last step:

src/main.rs
use std::sync::Arc;
 
use narsil::{IndexConfig, Map, Narsil, NarsilConfig, Value, parse_json};
use narsil_server::{
    BoxError, NarsilServer, RequestContext, RequestDecision, RequestDenial, ServerOptions,
};
 
fn article(id: &str, title: &str, body: &str) -> Map {
    let mut document = Map::new();
    document.insert("id", Value::String(id.into()));
    document.insert("title", Value::String(title.into()));
    document.insert("body", Value::String(body.into()));
    document
}
 
async fn stop_signal() -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use tokio::signal::unix::{SignalKind, signal};
 
        let mut terminate = signal(SignalKind::terminate())?;
        tokio::select! {
            _ = terminate.recv() => Ok(()),
            interrupted = tokio::signal::ctrl_c() => interrupted,
        }
    }
    #[cfg(not(unix))]
    {
        tokio::signal::ctrl_c().await
    }
}
 
#[tokio::main]
async fn main() -> Result<(), BoxError> {
    let engine = Arc::new(Narsil::open(NarsilConfig::default())?);
 
    engine.create_index(
        "articles",
        IndexConfig {
            schema: parse_json(r#"{ "title": "string", "body": "string" }"#)?,
            ..IndexConfig::default()
        },
    )?;
    engine.insert_batch(
        "articles",
        vec![
            article(
                "refund-timing",
                "How a refund reaches your bank",
                "A refund returns to the card that paid for the order.",
            ),
            article(
                "parcel-tracking",
                "Track a parcel after dispatch",
                "Every dispatched order has a tracking code.",
            ),
        ],
    )?;
 
    let api_token =
        std::env::var("NARSIL_API_TOKEN").unwrap_or_else(|_| "support-desk-token".to_string());
    let expected = format!("Bearer {api_token}");
    let check = move |request: RequestContext| {
        let allowed = request.headers.get("authorization") == Some(&expected);
        async move {
            Ok::<_, BoxError>(if allowed {
                RequestDecision::Allow
            } else {
                RequestDecision::Deny(RequestDenial {
                    status: 401,
                    code: "UNAUTHORISED".to_string(),
                    message: "Send the API token as a bearer token.".to_string(),
                })
            })
        }
    };
 
    let server = NarsilServer::new(
        engine,
        ServerOptions {
            host: Some("127.0.0.1".to_string()),
            port: Some(7700),
            on_request: Some(Arc::new(check)),
            ..ServerOptions::default()
        },
    )?;
 
    server.listen().await?;
 
    println!(
        "Narsil answers on port {}",
        server.listening_port().await.unwrap_or_default()
    );
 
    stop_signal().await?;
    server.shutdown().await?;
    Ok(())
}
Narsil answers on port 7700

Once you start the program with cargo run, every client program in the next section prints the same lines against it as against server.ts. The server answers a search without the token with the same 401 and the same error envelope as the TypeScript server, and the process exits with 0 on SIGTERM or Ctrl+C. The Rust server sends every search, write, and import to Tokio's blocking pool, so it goes on answering other requests while a slow search or import is under way.

shutdown stops the server from taking connections, closes the connections of the requests that remain in progress after 30 seconds, stops the tasks that are under way, and shuts the engine down. close takes only the first two of those steps, so the tasks and the engine go on working after it returns. The Rust server answers /livez, /readyz, /health, and /version without calling the hook, while it calls the hook for GET /capabilities as well, so a caller of that route has to send the token. GET /version reports the version of the crate, such as 0.1.4, unless the build option sets one. A Rust server in front of one engine answers every cluster route, every backup route, GET /cluster/health, and GET /metrics with 501 CLUSTER_OPERATION_UNSUPPORTED, as a TypeScript server without a cluster does. When you build the crate with its cluster feature, the server can join a cluster beside TypeScript nodes and serve those routes, following the steps on the Cluster page.

Start the Rust server without writing a program

When you install the crate with cargo install, you get narsil-server, a binary that serves one engine and takes every setting from an environment variable:

cargo install delali-narsil-server
NARSIL_API_KEY=support-desk-token NARSIL_DURABILITY_DIR=./narsil-data narsil-server
Narsil HTTP server listening on http://127.0.0.1:7700

While NARSIL_API_KEY is set, the binary accepts a request only when the key is in an authorization: Bearer header or in an x-api-key header, so each client on this page can call it with that key as its token. It answers the four probes without the key. The binary starts with no indexes, so create articles through a client, as with createIndex and insertBatch in TypeScript, before the client programs below can search it. With NARSIL_DURABILITY_DIR set, the binary opens the same indexes again after a restart. While NARSIL_API_KEY is unset or empty, the binary refuses to start on any address other than loopback, unless NARSIL_ALLOW_INSECURE is true. It stops on SIGTERM or SIGINT once the requests in progress finish.

VariableWhat the variable sets
NARSIL_HOST, NARSIL_PORTThe address and the port, which are 127.0.0.1 and 7700 by default.
NARSIL_API_KEYThe key that the binary requires on every request apart from the probes.
NARSIL_ALLOW_INSECUREWith true, the binary starts on an address other than loopback without a key.
NARSIL_DURABILITY_DIRThe directory for the write-ahead log and the checkpoints. While it is unset, the binary stores every index in memory only.
NARSIL_MAX_BODY_BYTES, NARSIL_MAX_IMPORT_BYTESThe largest JSON body and the largest NDJSON import that the binary accepts.
NARSIL_MAX_CONCURRENTThe number of requests that the binary answers at once.
NARSIL_SYNC, NARSIL_CHANGESWith true, the binary serves the device sync feed or the change capture feed.
NARSIL_INSTANCE_IDThe identifier that the binary stamps on each of its tasks.
NARSIL_BUILD_VERSION, NARSIL_BUILD_GIT_SHA, NARSIL_BUILD_DIRTYThe build that GET /version reports.

To deploy the Rust server without Cargo, start the container image under a tag that ends in -rust. The startup program in that image takes the variables that are on the container page, which differ from the ones above.

Call the server from TypeScript, Python, or Go

Each client has one method for every route, under the name of the matching engine method in that language, and it sends the token as a bearer token. Narsil publishes no Rust client, so a Rust program has to call the routes with an HTTP library or with a client that you generate from the OpenAPI description in the next section.

pnpm add -E @delali/narsil

You import the TypeScript client from @delali/narsil/client, and it works in Node.js, a browser, or an edge function. The Python package requires Python 3.11 or later, while the Go module depends only on the standard library. Start server.ts or the Rust program from the earlier steps, then start the program below in a second terminal.

import { createNarsilClient } from '@delali/narsil/client'
 
const client = createNarsilClient({
  url: 'http://127.0.0.1:7700',
  apiKey: process.env.NARSIL_API_TOKEN ?? 'support-desk-token',
})
 
const found = await client.query('articles', { term: 'refund', document: { include: ['title'] } })
 
for (const hit of found.hits) {
  console.log(hit.id, hit.score?.toFixed(2), hit.document?.title)
}
refund-timing 1.39 How a refund reaches your bank

The three clients receive the same hit as the test search in the first step of the server program. A search is a read, so a client with a list of addresses can send it to the next address after a refused connection or an answer of 502, 503, or 504. The client sends a write to a second address only when the server at the first address receives none of the write, as after a refused connection.

Copy an index through the export and import routes

A server on release 0.4 or later serves GET /indexes/{name}/export, which streams the documents of the index as JSON Lines, and POST /indexes/{name}/import, which accepts that stream and loads it as a task. In this step, the program streams the export of articles straight into an import under the name articles-copy. It then awaits waitForTask, which returns once the task finishes, and then counts the documents in the copy.

import { createNarsilClient } from '@delali/narsil/client'
 
const client = createNarsilClient({
  url: 'http://127.0.0.1:7700',
  apiKey: process.env.NARSIL_API_TOKEN ?? 'support-desk-token',
})
 
const found = await client.query('articles', { term: 'refund', document: { include: ['title'] } })
 
for (const hit of found.hits) {
  console.log(hit.id, hit.score?.toFixed(2), hit.document?.title)
}
 
const exported = await client.exportDocuments('articles') 
const task = await client.importDocumentExport('articles-copy', exported)
const finished = await client.waitForTask(task.id)
 
console.log(finished.status, await client.countDocuments('articles-copy'))
refund-timing 1.39 How a refund reaches your bank
succeeded 2

The server writes each upload to a temporary file as the bytes arrive, and it pauses the upload whenever 8 MiB of the upload are in its memory, so the server uses the same memory for an upload of any size. The server answers once the upload ends, while the engine imports the file in the task. waitForTask polls the task every 250 ms until it reaches succeeded, failed, or cancelled. For a failed task, waitForTask returns the task with its error set and throws no exception, because a part-finished import reports the documents that it loads. GET /indexes/{name}/snapshot and POST /indexes/{name}/restore move a whole index as an archive in the same way, and a comparison of the two formats is on the Persistence and durability page.

Generate a client from the OpenAPI description

The npm package contains openapi.json, an OpenAPI 3.1 description of every route that the server of the same release serves, apart from the two WebSocket feeds, so you can generate a client in any language from it. When a route matches one method of the TypeScript client, the operationId of the route is the name of that method, as in createIndex. The program below counts the operations and lists the ones that have x-narsil-repeatable.

openapi.ts
import openapi from '@delali/narsil/openapi.json' with { type: 'json' }
 
const operations = Object.values(openapi.paths).flatMap((route) => Object.values(route))
 
console.log(
  JSON.stringify(
    {
      version: openapi.openapi,
      operations: operations.length,
      repeatable: operations
        .filter((operation) => 'x-narsil-repeatable' in operation)
        .map((operation) => operation.operationId),
    },
    null,
    2
  )
)
{
  "version": "3.1.0",
  "operations": 70,
  "repeatable": [
    "listDocuments",
    "getMultiple",
    "query",
    "preflight",
    "suggest"
  ]
}

The five repeatable routes accept a POST body, although they only read data, so a generated client can send one of them again after a connection failure. Before you send any other POST again, check whether the index contains the write, because the server can store a write and then lose the connection before it answers.

Set limits before you open the address

Use limits to cap what one caller can ask of the engine. The server answers a body larger than maxBodyBytes, which is 16 MiB by default, with 413 PAYLOAD_TOO_LARGE. It answers a limit or an offset past maxResultWindow, which is 10,000 by default, with 400 INVALID_REQUEST. Above maxConcurrentRequests, which has no ceiling by default, the server sheds each extra request with 429 TOO_MANY_REQUESTS, and it counts the requests on every request thread together. In three measured rounds of 60 concurrent searches against a ceiling of 1, the server answers 7 or 8 searches and sheds the rest. maxRerankWindow, which is 100 by default, caps the documents that one search can send to a reranking model.

cors sets the origins from which a browser can call the server. With allowRegex: false, the server refuses every filter that contains a regular expression with 400 SEARCH_INVALID_FILTER, which suits a public address. The server closes a connection after 8 to 12 seconds without a request, because uWebSockets.js fixes that limit, so set the idle timeout of a connection pool or a reverse proxy in front of the server below 8 seconds.

See every route

AreaRoutes
Probes and serverGET /livez, GET /readyz, GET /health, GET /version, GET /capabilities, and GET /stats/memory
IndexesPOST /indexes, GET /indexes, and DELETE /indexes/{name}, with GET /indexes/{name}/stats, GET /indexes/{name}/partitions, GET /indexes/{name}/count, POST /indexes/{name}/_clear, POST /indexes/{name}/_open, and POST /indexes/{name}/_close
DocumentsPOST /indexes/{name}/documents, and GET, PUT, PATCH, and DELETE on /indexes/{name}/documents/{id}, with GET /indexes/{name}/documents/{id}/_exists
BulkPOST /indexes/{name}/documents/_batch, POST /indexes/{name}/documents/_multi-get, POST /indexes/{name}/documents/_list, POST /indexes/{name}/documents/_import, and POST /indexes/{name}/_wait-for-writes
SearchPOST /indexes/{name}/search, POST /indexes/{name}/search/preflight, and POST /indexes/{name}/suggest
Analysis and scoringPOST /indexes/{name}/_rebuild-analysis, POST /indexes/{name}/_change-analysis, GET and POST /indexes/{name}/synonyms, and POST /indexes/{name}/bm25
StoragePOST /indexes/{name}/_checkpoint, GET /indexes/{name}/snapshot, POST /indexes/{name}/restore, GET /indexes/{name}/export, and POST /indexes/{name}/import
Partitions and vectorsPOST /indexes/{name}/_rebalance, POST /indexes/{name}/partition-config, GET /indexes/{name}/vector-maintenance, POST /indexes/{name}/vectors/_compact, and POST /indexes/{name}/vectors/_optimize
Device sync and change captureGET and PUT /indexes/{name}/sync, GET /indexes/{name}/sync/snapshot, GET and PUT /indexes/{name}/changes, and the WebSocket feeds at /indexes/{name}/sync/feed and /indexes/{name}/changes/feed
Popular query suggestionsGET and PUT /indexes/{name}/query-suggestions, with record, build, preview, bans, remove, and manual under that path
ClusterGET /cluster, GET /cluster/health, GET /metrics, GET /indexes/{name}/cluster, PUT /indexes/{name}/replication-factor, POST /indexes/{name}/backups, GET /backups, POST /backups/{backup}/_restore, and DELETE /backups/{backup}
TasksGET /tasks, GET /tasks/{id}, and POST /tasks/{id}/_cancel

The routes for synonyms, BM25 settings, analysis changes, exports and imports, device sync, change capture, and popular query suggestions require release 0.4 or later, along with every cluster route except GET /cluster and GET /indexes/{name}/cluster. A server in front of a single engine answers every cluster route with 501 CLUSTER_OPERATION_UNSUPPORTED, while what those routes return on a cluster node is on the Cluster page. GET /capabilities lists the optional routes that a server serves, so a client can check for a route before it calls a server from an earlier release, which answers such a route with 404.

Both servers leave the vector fields out of every document that a document route or a search returns, unless you ask for them. Add ?vectors=true to GET /indexes/{name}/documents/{id} to get them back, or ?vectors=false to leave them out of an index that you create with returnVectors: true. The server answers any other value of vectors with 400 SEARCH_INVALID_FIELD. The bodies of _multi-get, _list, and search take a document projection with the same vectors and include settings as get on Indexes and documents. In the TypeScript client, get takes { vectors: true } and getMultiple takes { document: { vectors: true } } as their last argument. In the Python client, get takes vectors=True, while in the Go client, Get takes narsil.GetParams{Vectors: narsil.Ptr("true")} after the id.

The routes for long work, such as an import, a restore, a rebalance, and a rebuild, answer 202 with a task record, and you can follow the task with GET /tasks/{id}. By default, the server stores up to 1,000 task records in memory and works on at most 4 tasks at once, so it answers a request for a fifth task with 429 TOO_MANY_REQUESTS.

Where to go next

  • Read Persistence and durability for the durable engine that you usually put behind a server, and for the snapshot and export formats.
  • Read Change capture for the feed that streams every write on an index to a backend service.
  • Read Cluster for the routes with which you can check and back up a cluster.