Clients

TypeScript client

Reach a Narsil server from Node, a browser, or an edge function with the same calls as the embedded engine, spread the requests across several servers, and handle the tasks, deadlines, and failures of a network call.

@delali/narsil/client sends your calls to a Narsil server over HTTP. Its methods have the same names and arguments as the methods of the embedded engine, with the request settings as an extra last argument, so a query that you write against one works against the other. The client sends each request through fetch and holds no connection open, so it works in Node, in a browser, and in an edge function. A Python program reaches the same server through the Python client, while a Go program reaches it through the Go client.

On this page, you'll build search-client.ts, a program that searches a server, writes documents to it, follows a rebalance that the server continues after the call returns, and keeps working while one of two servers is down. Each code block below holds the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.

createNarsilClient takes the server's address, along with an apiKey that the client sends as a bearer token on every request. In the first block of the file, an engine and a server start in the same process to stand in for the server that you deploy. The server's onRequest hook accepts only the requests with the key, as the HTTP server page describes. With workers: { enabled: false }, the engine behind that server keeps its work on the main thread, so the example starts no worker threads.

search-client.ts
import { createNarsil } from '@delali/narsil'
import { createNarsilClient } from '@delali/narsil/client'
import { createServer } from '@delali/narsil/server'
 
const API_KEY = process.env.NARSIL_API_KEY ?? 'support-desk-key'
 
const engine = await createNarsil({ workers: { enabled: false } })
const server = createServer(engine, {
  host: '127.0.0.1',
  port: 7700,
  onRequest: (request) =>
    request.headers.authorization === `Bearer ${API_KEY}`
      ? undefined
      : { status: 401, code: 'UNAUTHORISED', message: 'Send the API key as a bearer token.' },
})
 
await server.listen()
 
const client = createNarsilClient({ url: 'http://127.0.0.1:7700', apiKey: API_KEY })
 
await client.createIndex('articles', { schema: { title: 'string', body: 'string' } })
await client.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.' },
  { id: 'refund-currency', title: 'Refunds in another currency', body: 'Your bank converts a refund at the rate on the day it arrives.' },
])
await client.waitForWrites('articles')
 
const found = await client.query('articles', { term: 'refund', document: { include: ['title'] } })
 
console.log(JSON.stringify(found.hits.map((hit) => ({ id: hit.id, title: hit.document?.title })), null, 2))
 
await server.shutdown()
[
  {
    "id": "refund-timing",
    "title": "How a refund reaches your bank"
  },
  {
    "id": "refund-currency",
    "title": "Refunds in another currency"
  }
]

The server answers with the hits that query returns in process. A write returns once the server's main copy of the index holds it, while the engine applies it to any worker copies afterwards, so the program calls waitForWrites to hold the search back until every copy holds the three articles.

Write a document under an id that you choose

put writes a document at the id that you give it and returns created, which is true when the call creates the document and false when it replaces one. On the embedded engine, you will have to combine insert and update for the same effect, because insert fails on an id that the index contains and update fails on one that it lacks, as the errors page shows. get resolves to undefined for an id that the index lacks. On an index with a vector field, the server leaves the vector fields out of the document that get returns unless you pass { vectors: true } as the last argument of get, while getMultiple takes { document: { vectors: true } }.

search-client.ts
import { createNarsil } from '@delali/narsil'
import { createNarsilClient } from '@delali/narsil/client'
import { createServer } from '@delali/narsil/server'
 
const API_KEY = process.env.NARSIL_API_KEY ?? 'support-desk-key'
 
const engine = await createNarsil({ workers: { enabled: false } })
const server = createServer(engine, {
  host: '127.0.0.1',
  port: 7700,
  onRequest: (request) =>
    request.headers.authorization === `Bearer ${API_KEY}`
      ? undefined
      : { status: 401, code: 'UNAUTHORISED', message: 'Send the API key as a bearer token.' },
})
 
await server.listen()
 
const client = createNarsilClient({ url: 'http://127.0.0.1:7700', apiKey: API_KEY })
 
await client.createIndex('articles', { schema: { title: 'string', body: 'string' } })
await client.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.' },
  { id: 'refund-currency', title: 'Refunds in another currency', body: 'Your bank converts a refund at the rate on the day it arrives.' },
])
await client.waitForWrites('articles')
 
const found = await client.query('articles', { term: 'refund', document: { include: ['title'] } }) 
const created = await client.put('articles', 'password-reset', { 
  title: 'Reset your password',
  body: 'Request a reset link from the sign-in page.',
})
const replaced = await client.put('articles', 'password-reset', {
  title: 'Reset your password',
  body: 'Request a reset link from the sign-in page, and it expires after one hour.',
})
const missing = await client.get('articles', 'gift-cards')
 
console.log(JSON.stringify(found.hits.map((hit) => ({ id: hit.id, title: hit.document?.title })), null, 2)) 
console.log(JSON.stringify({ created, replaced, missing: missing ?? null }, null, 2))
 
await server.shutdown()
{
  "created": {
    "id": "password-reset",
    "created": true
  },
  "replaced": {
    "id": "password-reset",
    "created": false
  },
  "missing": null
}

The first put creates the article, while the second replaces it, so created holds true and then false.

Follow the work that outlasts a request

A rebalance, a restore, an analysis rebuild, a vector optimisation, and a started import can take longer than a request should wait. For each of them, the server answers at once with a task record and continues the work. With waitForTask(id), the client then asks the server for that task every 250 ms until the work finishes.

search-client.ts
import { createNarsil } from '@delali/narsil'
import { createNarsilClient } from '@delali/narsil/client'
import { createServer } from '@delali/narsil/server'
 
const API_KEY = process.env.NARSIL_API_KEY ?? 'support-desk-key'
 
const engine = await createNarsil({ workers: { enabled: false } })
const server = createServer(engine, {
  host: '127.0.0.1',
  port: 7700,
  onRequest: (request) =>
    request.headers.authorization === `Bearer ${API_KEY}`
      ? undefined
      : { status: 401, code: 'UNAUTHORISED', message: 'Send the API key as a bearer token.' },
})
 
await server.listen()
 
const client = createNarsilClient({ url: 'http://127.0.0.1:7700', apiKey: API_KEY })
 
await client.createIndex('articles', { schema: { title: 'string', body: 'string' } })
await client.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.' },
  { id: 'refund-currency', title: 'Refunds in another currency', body: 'Your bank converts a refund at the rate on the day it arrives.' },
])
await client.waitForWrites('articles')
 
const created = await client.put('articles', 'password-reset', {
  title: 'Reset your password',
  body: 'Request a reset link from the sign-in page.',
})
const replaced = await client.put('articles', 'password-reset', {
  title: 'Reset your password',
  body: 'Request a reset link from the sign-in page, and it expires after one hour.',
})
const missing = await client.get('articles', 'gift-cards')
 
console.log(JSON.stringify({ created, replaced, missing: missing ?? null }, null, 2)) 
await client.updatePartitionConfig('articles', { maxPartitions: 2 }) 
const started = await client.rebalance('articles', 2)
const finished = await client.waitForTask(started.id, { waitTimeoutMs: 60_000 })
const stats = await client.getStats('articles')
 
console.log(
  JSON.stringify(
    {
      started: { type: started.type, status: started.status },
      finished: finished.status,
      partitionCount: stats.partitionCount,
    },
    null,
    2
  )
)
 
await server.shutdown()
{
  "started": {
    "type": "rebalance",
    "status": "running"
  },
  "finished": "succeeded",
  "partitionCount": 2
}

The server answers the rebalance with a record whose status is running. waitForTask then resolves once the status reaches succeeded, by which point the index holds two partitions. A task can also end as failed, with the error in the record's error field, or as cancelled after cancelTask(id). waitForTask resolves for a failed task without throwing, because the record of a part-finished import holds the count of the documents that the server indexes before the failure, so check the status of the record that it returns. With waitTimeoutMs, waitForTask fails with CLIENT_TASK_TIMEOUT once that time passes, while the server continues the task.

Keep working while one server is down

url also takes a list of addresses, such as one for each node of a cluster or each copy of a server behind your load balancer. The client sends each request to the next address in the list after the address of the previous request, so that the requests spread across the list. When a server refuses the connection, the client retries the request on the next address and skips the refused address for 1 second, doubling that wait after each further refusal, up to 30 seconds. urlSkipMs and maxUrlSkipMs set those two intervals. In the block below, nothing listens on port 7701, which stands in for a stopped server.

search-client.ts
import { createNarsil } from '@delali/narsil'
import { createNarsilClient } from '@delali/narsil/client'
import { createServer } from '@delali/narsil/server'
 
const API_KEY = process.env.NARSIL_API_KEY ?? 'support-desk-key'
 
const engine = await createNarsil({ workers: { enabled: false } })
const server = createServer(engine, {
  host: '127.0.0.1',
  port: 7700,
  onRequest: (request) =>
    request.headers.authorization === `Bearer ${API_KEY}`
      ? undefined
      : { status: 401, code: 'UNAUTHORISED', message: 'Send the API key as a bearer token.' },
})
 
await server.listen()
 
const client = createNarsilClient({ url: 'http://127.0.0.1:7700', apiKey: API_KEY })
 
await client.createIndex('articles', { schema: { title: 'string', body: 'string' } })
await client.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.' },
  { id: 'refund-currency', title: 'Refunds in another currency', body: 'Your bank converts a refund at the rate on the day it arrives.' },
])
await client.waitForWrites('articles')
 
const created = await client.put('articles', 'password-reset', {
  title: 'Reset your password',
  body: 'Request a reset link from the sign-in page.',
})
const replaced = await client.put('articles', 'password-reset', {
  title: 'Reset your password',
  body: 'Request a reset link from the sign-in page, and it expires after one hour.',
})
const missing = await client.get('articles', 'gift-cards')
 
await client.updatePartitionConfig('articles', { maxPartitions: 2 })
const started = await client.rebalance('articles', 2)
const finished = await client.waitForTask(started.id, { waitTimeoutMs: 60_000 })
const stats = await client.getStats('articles')
 
console.log( 
  JSON.stringify(
    {
      started: { type: started.type, status: started.status },
      finished: finished.status,
      partitionCount: stats.partitionCount,
    },
    null,
    2
  )
)
const nodes = createNarsilClient({ url: ['http://127.0.0.1:7701', 'http://127.0.0.1:7700'], apiKey: API_KEY }) 
const written = await nodes.put('articles', 'gift-cards', {
  title: 'Pay with a gift card',
  body: 'Enter the gift card code at checkout.',
})
const reads: number[] = []
for (let attempt = 0; attempt < 3; attempt++) {
  reads.push((await nodes.query('articles', { term: 'gift' })).count)
}
 
console.log(JSON.stringify({ written, reads }, null, 2))
 
await server.shutdown()
{
  "written": {
    "id": "gift-cards",
    "created": true
  },
  "reads": [
    1,
    1,
    1
  ]
}

The write and all three searches succeed, because the client retries each request that fails on port 7701 on port 7700. The client retries a read on the next address after a refused connection, a timeout, or an answer of 502, 503, or 504. Once every address fails that way, it sends the read once more, so a list of N addresses can take N + 1 requests. The client retries a write only when it sends no byte of the request, as with a refused connection, or when the server answers NODE_NOT_READY. Once the client sends any byte of a write, or the write times out, the server can apply that write, so the client returns the failure to you and sends nothing more. Because a browser reports no reason for a failed connection, the client in a browser retries a write only after NODE_NOT_READY.

Set deadlines and handle failures

The client gives every try of a request 30 seconds, after which the request fails with CLIENT_REQUEST_TIMEOUT. Set timeoutMs on the client to change that for every request, or pass { timeoutMs } as the last argument of one call, and a value of 0 makes the client wait for as long as the server takes. The methods that can move a whole corpus, a whole index, or a long list wait without a deadline unless you set timeoutMs on the client or on the call. Those methods are importDocuments, startImport, snapshot, restore, exportDocuments, importDocumentExport, syncSnapshot, and listBackups. A call that you cancel through { signal } fails with CLIENT_REQUEST_ABORTED.

The client throws each failure as a NarsilError. For a failure that the server reports, the client keeps the server's code and adds the HTTP status to details, while CLIENT_CONNECTION_FAILED means that the client can reach no server at any address. createNarsilClient checks the addresses at once and fails with CONFIG_INVALID for an empty list or for a value that it cannot parse as an http or https URL or as a path. Read Errors for the codes and for why isNarsilError is the test to use.

In a browser, pass a path such as /search-api as the url, which the browser resolves against the page. Have your backend forward the requests under that path to Narsil with the key attached, so that the key stays off the page. When a page calls the Narsil server from another origin, list that origin in the server's cors option. With maxResponseBytes, the client stops reading an answer past that many bytes and fails with CLIENT_INVALID_RESPONSE, so that an answer that grows without limit can't exhaust the memory of a browser tab.

Where to go next

  • Read Python client and Go client for the same routes from those languages, with the same rules for retrying on another server.
  • Read React hooks for the hooks that wrap this client, with a search box as the example.
  • Read Device sync for a copy of one user's index that a device searches while it is offline.
  • Read Errors for the codes that the client throws and the entry points that share them.