dream_opensearch/client

OpenSearch HTTP client

This module provides a simple HTTP client for interacting with OpenSearch (or Elasticsearch) clusters. It handles the low-level HTTP communication needed for document operations, searches, and index management.

Quick Start

Create a client and index a document Tested snippet

import dream_opensearch/client.{type Client, type OpenSearchError}
import dream_opensearch/document

pub fn create_client() -> Result(Client, OpenSearchError) {
  client.new("http://localhost:9200")
}

pub fn index_alice(
  opensearch: Client,
  index: String,
) -> Result(String, OpenSearchError) {
  document.index(opensearch, index, "123", "{\"name\":\"Alice\"}")
}

Two ways to make a client

Each request of the client starts from the same base request. It keeps the scheme, the host, the port, the headers, the timeouts and the recorder of the base request, and sets the method, the path, the query and the body.

Base URL

The base URL should point to your OpenSearch cluster. It can include a user name and password, which the client sends as HTTP Basic authentication on every request:

Percent-encode @, : and / in the user name or password (%40, %3A, %2F). The client decodes them before it builds the authorization header.

Errors

Every function returns OpenSearchError for a failure. Match on its variants to decide what to do, and use describe_error for a log line.

Types

OpenSearch client configuration

A connection to an OpenSearch cluster: the base request that every request of the client starts from. Make one with new or from_request, and read the base request with base_request.

The type is opaque, so a Client always holds a base request that new or from_request made.

pub opaque type Client

Why an OpenSearch request failed.

No variant holds the user name or the password of the base URL.

Variants

  • InvalidUrl: new cannot use the base URL. reason says why, for example the URL has no host. Only new returns it, and no request is sent.
  • Unavailable: the request got no HTTP answer. The connection was refused or closed, the host name did not resolve, the TLS handshake failed, or the HTTP/2 stream or connection failed. reason is the text of the dream_http_client transport error, for example Connection failed: Connection refused.
  • TimedOut: no answer came within the timeout of the request, which is 30000 ms unless the base request sets another. The request was sent, and the cluster can still finish it. timeout_ms is that timeout.
  • Rejected: OpenSearch answered with status 400 or more. body is its answer, which usually holds the error details as JSON.
  • InvalidResponseBody: the answer body is not valid UTF-8. status is the status of the answer, with any value.
  • NoRecording: the base request has a dream_http_client recorder in playback mode, and no recording matches the request. Nothing is sent. method and url name the request, and details is the text of dream_http_client, which shows the nearest recordings.
pub type OpenSearchError {
  InvalidUrl(reason: String)
  Unavailable(reason: String)
  TimedOut(timeout_ms: Int)
  Rejected(status: Int, body: String)
  InvalidResponseBody(status: Int)
  NoRecording(method: String, url: String, details: String)
}

Constructors

  • InvalidUrl(reason: String)

    new cannot use the base URL.

  • Unavailable(reason: String)

    The request got no HTTP answer.

  • TimedOut(timeout_ms: Int)

    No answer came within the timeout of the request.

  • Rejected(status: Int, body: String)

    OpenSearch answered with status 400 or more.

  • InvalidResponseBody(status: Int)

    The answer body is not valid UTF-8.

  • NoRecording(method: String, url: String, details: String)

    A playback recorder has no recording for the request.

Values

pub fn base_request(client: Client) -> client.ClientRequest

The base request of a client

Returns the dream_http_client request that every request of client starts from. For a client from new, it holds the scheme, the host, the port, the path prefix and the authorization header of the base URL.

The authorization header holds the password in base64. Do not print or log it.

Example

Read the host of a client Tested snippet

import dream_http_client/client as http_client
import dream_opensearch/client.{type Client}

pub fn host_of(opensearch: Client) -> String {
  http_client.get_host(client.base_request(opensearch))
}
pub fn describe_error(error: OpenSearchError) -> String

Turn an error into one line of text

The text names the kind of failure and its details, for a log or a message to an operator. It never holds the user name or password of the base URL. A Rejected error holds the body of the OpenSearch answer.

Returns

  • InvalidUrl(reason): Invalid OpenSearch URL: <reason>
  • Unavailable(reason): OpenSearch is unavailable: <reason>
  • TimedOut(timeout_ms): OpenSearch sent no answer within <timeout_ms> ms
  • Rejected(status, body): OpenSearch rejected the request with status <status>: <body>
  • InvalidResponseBody(status): The OpenSearch response body is not valid UTF-8 (status <status>)
  • NoRecording(method, url, details): No recording for the OpenSearch request: <details>. details can have more than one line.

Example

Log an error Tested snippet

import dream_opensearch/client.{type Client}
import gleam/http

pub fn health_line(opensearch: Client) -> String {
  case client.send_request(opensearch, http.Get, "/_cluster/health", "") {
    Ok(_body) -> "OpenSearch is healthy"
    Error(error) -> client.describe_error(error)
  }
}
pub fn from_request(base: client.ClientRequest) -> Client

Create a new OpenSearch client from a dream_http_client request

Every request of the client starts from base. It keeps the scheme, the host, the port, the headers, the timeouts, the connection pool, the certificate authority file and the recorder of base. For each request, the client sets the method, the body and the header content-type: application/json, which replaces a content-type header of base. The path of the request is the path of base with the API path added after it, so the path of base is a prefix. A query in the API path replaces the query of base.

Parameters

  • base: The dream_http_client request that every request starts from

Returns

A Client for the cluster of base.

See Also

  • new: makes a client from a base URL.
  • base_request: reads the base request back.

Example

Create a client with a timeout and a recorder Tested snippet

import dream_http_client/client as http_client
import dream_http_client/recorder.{type Recorder}
import dream_opensearch/client.{type Client}
import gleam/http

pub fn create_recorded_client(recorder: Recorder) -> Client {
  http_client.new()
  |> http_client.scheme(http.Http)
  |> http_client.host("localhost")
  |> http_client.port(9201)
  |> http_client.timeout(5000)
  |> http_client.recorder(recorder)
  |> client.from_request
}
pub fn new(base_url: String) -> Result(Client, OpenSearchError)

Create a new OpenSearch client from a base URL

The base URL must have the scheme http or https and a host. It can have a port, a path prefix, and a user name and password. A trailing slash is removed.

A user name and password in the URL (https://user:pass@host:9200) make every request send the header authorization: Basic <base64(user:password)>. The user name and password are percent-decoded first, and a URL with no password sends an empty password. They are not sent in the request line or the host header.

Parameters

  • base_url: The base URL of the OpenSearch cluster

Returns

  • Ok(Client): a client for the cluster at base_url.
  • Error(InvalidUrl(reason)): the URL cannot be used. reason is one of:
    • the URL cannot be parsed
    • the URL scheme must be http or https
    • the URL has no host
    • the URL has a query or a fragment
    • the user name or password has invalid percent-encoding

No reason contains the user name or password.

See Also

  • from_request: makes a client from a dream_http_client request.
  • send_request: sends a request to the cluster of this client.

Example

Create a client Tested snippet

import dream_opensearch/client.{type Client, type OpenSearchError}

pub fn create_local_client() -> Result(Client, OpenSearchError) {
  client.new("http://localhost:9200")
}

pub fn create_client_with_credentials() -> Result(Client, OpenSearchError) {
  client.new("https://user:pass@search.example.com:9200")
}
pub fn send_request(
  client: Client,
  method: http.Method,
  path: String,
  body: String,
) -> Result(String, OpenSearchError)

Send HTTP request to OpenSearch

Sends a raw HTTP request to the OpenSearch cluster. The dream_opensearch/document module uses it for every operation. Most applications should use that module instead.

The request starts from the base request of the client (see from_request) and has the header content-type: application/json.

Parameters

  • client: The OpenSearch client
  • method: The HTTP method (GET, POST, PUT, DELETE, etc.)
  • path: The API path (e.g., “/users/_doc/123” or “/users/_search”), sent after the path prefix of the client as it is. A ? starts the query. This function does not percent-encode the path: encode an index name or a document ID with characters outside A-Z a-z 0-9 - . _ ~ yourself. The dream_opensearch/document functions encode them for you.
  • body: The request body as a JSON string

Returns

  • Ok(String): The response body as a string (status < 400)
  • Error(OpenSearchError): See Errors.

Errors

  • Rejected(status, body): the response status is 400 or more. body is the response body, unchanged.
  • Unavailable(reason): the request got no answer. For example Connection failed: Connection refused, or Connection failed: DNS resolution failed (NXDOMAIN) for a host name that does not resolve. When the server closes the connection with no answer, the reason is Remote closed connection: for GET, HEAD, PUT and DELETE, the HTTP client sends the request once more on a new connection before it returns this error. It sends a POST one time only.
  • TimedOut(timeout_ms): the server sent no answer within the timeout (30000 ms unless the base request sets another). The request was sent, and the cluster can still finish it.
  • InvalidResponseBody(status): the response body is not valid UTF-8, with any status.
  • NoRecording(method, url, details): a playback recorder of the base request has no recording for the request. Nothing is sent.

No error contains the user name or password of the base URL.

See Also

  • new and from_request: create the client.
  • describe_error: turns an error into one line of text.
  • dream_opensearch/document: the operations built on this function.

Example

Get a document Tested snippet

import dream_opensearch/client.{type Client, type OpenSearchError}
import gleam/http

pub fn get_user(
  opensearch: Client,
  index: String,
) -> Result(String, OpenSearchError) {
  client.send_request(opensearch, http.Get, "/" <> index <> "/_doc/123", "")
}
✨ Search Document