GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Docs
  • GitHub
  • Home
  • Why WaveHouse?
  • Architecture
  • Ingest Pipeline
  • Access Control
  • Named Pipes
  • API Reference
  • Overview
  • Queries
  • Streaming & Live Queries
  • Pipes
  • Admin & System

This view

  • Original page
  • New address

GeezerVison is showing wavehouse.dev — SDKs

  • Claude
  • ChatGPT
  • Cursor
  • View as Markdown

SDKs

WaveHouse has two client SDKs. They share no code, but they follow the same server protocol and are meant to behave the same; where they differ by design, these pages say so. Each page covers one topic for both languages, and the code tabs switch together: pick a language once and every tab on the site follows it.

TypeScript® Go
Package @wavehouse/sdk on npm github.com/Wave-RF/wavehouse-sdk-go, package wavehouse
Runtime Node 22 or newer, modern browsers, Deno, Bun Go 1.26 or newer
Runtime dependencies one: eventsource-parser (~1.4 KB gzipped, itself dependency-free), which frames the SSE stream none: the standard library only
Source, issues and releases Wave-RF/wavehouse-sdk-js Wave-RF/wavehouse-sdk-go

The server’s API reference defines the protocol both follow. Each SDK’s changelog and releases page, linked above, say what changed in a given version. Report an SDK bug in its own repository, and a server bug in Wave-RF/WaveHouse.

Installation

Section titled “Installation”
  • TypeScript
  • Go
  • pnpm
  • npm
  • yarn
  • bun
  • deno
Terminal window
pnpm add @wavehouse/sdk
Terminal window
npm install @wavehouse/sdk
Terminal window
yarn add @wavehouse/sdk
Terminal window
bun add @wavehouse/sdk
Terminal window
deno add npm:@wavehouse/sdk

All five install the same package.

No build step (CDN). The SDK also loads straight into an HTML page, with no bundler or package manager. Modern browsers run the ES module natively:

<script type="module">
import { createClient } from 'https://esm.sh/@wavehouse/sdk';
const wh = createClient({ baseURL: 'https://<project_id>.wavehouse.app' });
const { data, error } = await wh.from('clicks').select('page').limit(10);
console.log(data ?? error);
</script>

jsDelivr (https://cdn.jsdelivr.net/npm/@wavehouse/sdk/+esm) and unpkg (https://unpkg.com/@wavehouse/sdk?module) serve the same module. A bare CDN URL serves the latest release, so pin a version on a production page (@<version>): before 1.0 a minor release may break the API (see the SDK’s changelog). The @dev tag serves unreleased builds from the SDK repository’s main. Streaming runs on fetch, so a CDN page needs no polyfill.

IIFE global (<script src>). For pages that cannot use ES modules, dist/index.global.js is a self-contained minified bundle that exposes every export on a WaveHouse global (window.WaveHouse). CDNs serve it through the unpkg/jsdelivr fields in package.json:

<script src="https://cdn.jsdelivr.net/npm/@wavehouse/sdk"></script>
<script>
const wh = WaveHouse.createClient({ baseURL: 'https://your-wavehouse.example.com' });
wh.from('clicks').select('page').limit(10).then(({ data }) => console.log(data));
</script>

Pin a version here too, on a production page.

Terminal window
go get github.com/Wave-RF/wavehouse-sdk-go@latest

The module needs Go 1.26 or newer. Its import path is github.com/Wave-RF/wavehouse-sdk-go and its package name is wavehouse.

Imports & Runtimes

Section titled “Imports & Runtimes”
  • TypeScript
  • Go
import { createClient } from '@wavehouse/sdk';

The same line works with every package manager, Deno included (it resolves the bare specifier from deno.json after deno add). From a CDN, import the URL (see Installation). The package works in any bundler-based framework: React, Vue, Svelte, Angular, Astro, SolidJS or plain Vite.

Node CommonJS (require). The package ships a CommonJS build at dist/index.cjs (the "require" condition in the exports map), so a Node project that has not adopted "type": "module" can use:

const { createClient } = require('@wavehouse/sdk');

TypeScript projects under node16/nodenext resolution get the matching dist/index.d.cts declarations through the same require condition, so a CommonJS project type-checks without importing ESM-typed declarations.

import wavehouse "github.com/Wave-RF/wavehouse-sdk-go"

The package name is wavehouse, so the alias only makes it explicit. One *wavehouse.Client is safe for concurrent use: create it once and share it.

Runtime support

Section titled “Runtime support”
  • TypeScript
  • Go

Browsers. Every feature works natively. fetch, AbortController and ReadableStream are built into every modern browser, so no polyfill is needed.

Node.js®. Every feature, streaming included, works in Node 22 and later (the package’s minimum, per engines.node). Its unit tests run on Node 22, and the build is smoke-tested on 22 and 24; older releases are past end-of-life upstream. Streaming runs on the same fetch and ReadableStream globals as the rest of the SDK, so it needs no EventSource polyfill.

Go 1.26 or newer, on any platform the standard library supports. The SDK uses net/http and nothing outside the standard library.

Quick Start

Section titled “Quick Start”
  • TypeScript
  • Go
import { createClient } from '@wavehouse/sdk';
const wh = createClient({
baseURL: 'http://localhost:8080',
auth: () => tokenCache.get(), // omit for unauthenticated access
});
// Query
const { data, error } = await wh.from('clicks').select('page').limit(10);
// Insert
await wh.from('clicks').insert({ page: '/home', button: 'signup', score: 1 });
// Stream
const stream = wh.from('clicks').stream();
const unsub = stream.subscribe({
next: (event) => console.log(event.data),
status: (s) => console.log('Stream:', s),
});
package main
import (
"context"
"fmt"
"log"
"os"
wavehouse "github.com/Wave-RF/wavehouse-sdk-go"
)
func main() {
// Omit WithToken for unauthenticated access.
wh, err := wavehouse.New("http://localhost:8080", wavehouse.WithToken(os.Getenv("WAVEHOUSE_TOKEN")))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
type click struct {
Page string `json:"page"`
Button string `json:"button"`
Score float64 `json:"score"`
}
// Insert: a struct, a map, or a slice of either.
if _, err := wh.From("clicks").Insert(ctx, []click{{"/home", "signup", 3}, {"/about", "nav", 7}}); err != nil {
log.Fatal(err)
}
// Query: a chain that ends in Scan, into structs or maps. Rows reach ClickHouse
// in batches (up to 5 s after the insert by default), so this read may not see them yet.
var top []click
err = wh.From("clicks").
Select("page", "button", "score").
Where("score", wavehouse.Gt, 5).
OrderBy("score", wavehouse.Desc).
Limit(10).
Scan(ctx, &top)
if err != nil {
log.Fatal(err)
}
fmt.Println(top)
// Stream
sub, err := wh.Subscribe(ctx, "clicks", nil)
if err != nil {
log.Fatal(err)
}
defer sub.Close()
for sub.Next() {
fmt.Println(sub.Event().Row())
}
if err := sub.Err(); err != nil {
log.Fatal(err)
}
}

Creating a Client

Section titled “Creating a Client”
  • TypeScript
  • Go
import { createClient } from '@wavehouse/sdk';
import type { Database } from './my-types'; // optional, see Type-Safe Tables
const wh = createClient<Database>({
baseURL: 'https://<project_id>.wavehouse.app',
auth: () => myAuthProvider.getCachedToken(),
options: {
maxRetries: 2,
attemptTimeoutMs: 8_000,
},
});
wh, err := wavehouse.New("https://wavehouse.example.com",
wavehouse.WithTokenSource(fetchToken),
wavehouse.WithRetry(wavehouse.RetryPolicy{MaxAttempts: 3, AttemptTimeout: 8 * time.Second}),
wavehouse.WithUserAgent("my-tool/1.0"),
)
if err != nil {
log.Fatal(err)
}

New applies the options in order and reports every invalid value, or combination, in one error rather than picking one.

Client options

Section titled “Client options”
  • TypeScript
  • Go

ClientConfig<DB>, the configuration createClient takes:

Field Type Default Description
baseURL string — The server’s URL, optionally with a path prefix (required; see Base URL)
auth () => Promise<string> | string — Token provider, called before every attempt (Authentication). Omit for unauthenticated access
options.maxRetries number 2 Retries after the first attempt of a REST call, for the calls and answers that may be resent (Retries and timeouts). A negative, fractional or non-finite value throws a TypeError. Stream reconnects are unbounded and never consult it
options.attemptTimeoutMs number off A deadline for each attempt on its own, so a stalled attempt is retried instead of holding the call (Attempt timeouts)
options.maxRetryAfterMs number 30000 The longest Retry-After a REST call waits before resending; a longer ask is clamped to it
options.headers Record<string, string> or a function returning one — Headers added to every request (Custom headers)
options.fetchOptions RequestInit — Extra RequestInit fields merged into every request (details)
options.fetch FetchLike the global fetch The HTTP implementation for every request (details)

Every REST call’s options also take headers, fetchOptions, fetch and attemptTimeoutMs for that call alone; see Per-call options.

New takes these options:

Option Default Description
WithToken(token) — A fixed JWT, sent as Authorization: Bearer <token>. An empty token is an error from New, so an unset environment variable can’t turn into an unauthenticated client
WithTokenSource(fn) — A token from fn(ctx) (string, error), called before every attempt (Authentication)
WithOperatorKey(key) — The server’s operator key, sent as Authorization: Operator <key>. It reaches every route, /v1/ops/* included, without a JWT. Only one of WithToken, WithTokenSource and WithOperatorKey may be given
WithHeader(key, value) — A header on every request (Custom headers)
WithHeaderFunc(fn) — Headers from fn(ctx) (http.Header, error), called before every attempt
WithRetry(RetryPolicy{…}) MaxAttempts 3, MinBackoff 500ms, MaxBackoff 30s, AttemptTimeout 0 (off) How often and how patiently a failed call is retried (Retries and timeouts). A zero field keeps its default; a negative field, or MinBackoff above MaxBackoff, is an error from New
WithHTTPClient(hc) an *http.Client with no overall timeout The client requests go through (details)
WithUserAgent(ua) — Prepended to the SDK’s own User-Agent, wavehouse-sdk-go/<version>

Every call that does I/O takes a context.Context first; bound or cancel the call with it. Queries, pipe calls and SQL calls take a per-call Header(key, value), and a subscription takes SubscribeOptions.Header.

Base URL

Section titled “Base URL”

Both SDKs read the base URL by the same rules, so one input resolves to the same base in either:

  • The scheme is optional. Without one, a loopback host (localhost, *.localhost, 127.0.0.0/8, ::1) gets http:// and any other host gets https://, so localhost:8080 and wavehouse.example.com both work. An explicit scheme is never changed, so an http:// is never upgraded. It must be http or https: Go’s New and TypeScript’s createClient both refuse any other, ws:// and wss:// included, since streaming is plain HTTP and there is no WebSocket endpoint.
  • It must name a host. A bare path such as /api/wavehouse names none, so it is refused rather than read as a host called api. A browser app that talks to a same-origin WaveHouse builds an absolute base: `${location.origin}/api/wavehouse`.
  • No query string or fragment. Request paths are joined onto the base, so either could only be dropped; both are refused.
  • A path prefix is kept, and a trailing slash is optional (see below).

The TypeScript createClient throws a TypeError for a base with no host, a scheme other than http/https, a query or a fragment. A base that is otherwise unusable fails per call: a REST call rejects with a TypeError, and a stream reports a terminal SSE_CONNECT_ERROR to the subscriber’s error callback. Go’s New returns an error for every one of these.

Serving under a path prefix

Section titled “Serving under a path prefix”

The base URL may carry a path prefix, for a WaveHouse reachable somewhere other than the root of an origin: behind a backend-for-frontend (BFF), an app-server route, or a path-routed ingress. Every request path is appended to it, REST calls and streams alike:

  • TypeScript
  • Go
const wh = createClient({ baseURL: 'https://app.example.com/api/wavehouse' });
// queries → https://app.example.com/api/wavehouse/v1/query
// streams → https://app.example.com/api/wavehouse/v1/stream
wh, err := wavehouse.New("https://app.example.com/api/wavehouse")
if err != nil {
log.Fatal(err)
}
// queries → https://app.example.com/api/wavehouse/v1/query
// streams → https://app.example.com/api/wavehouse/v1/stream

The proxy in front must strip the prefix before forwarding, since WaveHouse itself always serves at /v1/…; see Behind a reverse proxy → Path prefixes.

Authentication

Section titled “Authentication”
  • TypeScript
  • Go
const wh = createClient({
baseURL: 'https://wavehouse.example.com',
// Called before EVERY attempt: each retry, and each stream (re)connect.
auth: () => tokenCache.get(),
});

auth returns a JWT, or a promise of one, sent as Authorization: Bearer <token>; an empty string sends no Authorization header. A rejection throws out of a REST call (it is never retried) and is a retryable SSE_AUTH_ERROR on a stream. The SDK has no operator-key option: send the operator key as an X-Operator-Key header through options.headers.

// fetchToken stands in for an identity-provider client that caches its token.
fetchToken := func(context.Context) (string, error) { return tokens.Current(), nil }
wh, err := wavehouse.New("https://wavehouse.example.com", wavehouse.WithTokenSource(fetchToken))
if err != nil {
log.Fatal(err)
}

The token source gets the context of the call it authorizes, so a server that forwards each user’s own token can put it in the context and read it back there. A returned "" sends no Authorization header. A returned error fails the attempt without sending it: a REST call returns it, Subscribe returns it from the first connect, and once a stream has been live it is retried like a dropped connection. WithToken sends a fixed token, and WithOperatorKey the operator key.

The contract, in both SDKs: the token provider runs before every attempt. Each retry of a REST call calls it again, and so does each connect and reconnect of a stream, so a token that changed during a backoff is the one the retry sends, and a stream that outlives its token reconnects with a fresh one. It therefore sits on the path of every request and must be cheap. Caching, refreshing, and de-duplicating concurrent refreshes are the caller’s job, not the SDK’s. A function-valued options.headers (TypeScript) and WithHeaderFunc (Go) follow the same contract.

The token always travels in the Authorization header, streams included, and never in the URL. The server still accepts a ?token= query parameter for clients that cannot set headers (API reference → Authentication), but neither SDK uses it, so a token never reaches a proxy’s or CDN’s access log.

Custom headers

Section titled “Custom headers”

Headers added to every request, streams included. The usual reason is a header-gated proxy in front of WaveHouse, such as a Cloudflare® Access service token:

  • TypeScript
  • Go
const wh = createClient({
baseURL: 'https://<project_id>.wavehouse.app',
options: {
headers: {
'CF-Access-Client-Id': process.env.CF_ACCESS_CLIENT_ID!,
'CF-Access-Client-Secret': process.env.CF_ACCESS_CLIENT_SECRET!,
},
},
});
// For a credential that rotates, a function, called before every attempt:
const rotating = createClient({
baseURL: 'https://<project_id>.wavehouse.app',
options: { headers: () => ({ 'X-Access-Secret': secretCache.get() }) },
});
// One call's own headers:
await wh.from('clicks').selectAll().fetch({ headers: { 'X-Trace-Id': traceId } });

A stream takes per-subscription headers in StreamOptions.headers. A rejecting header function throws out of a REST call and is a retryable SSE_AUTH_ERROR on a stream, like auth.

From a browser, a cross-origin custom header must also survive the CORS preflight, and WaveHouse allow-lists a fixed set (Accept, Authorization, Content-Type, Last-Event-ID and X-Request-ID among them) with no setting to change it. Any other header works server-side, or from a browser when a proxy in front answers the preflight itself, which is usually the same proxy the header is for. Server-side callers never preflight.

wh, err := wavehouse.New("https://wavehouse.example.com",
wavehouse.WithHeader("CF-Access-Client-Id", os.Getenv("CF_ACCESS_CLIENT_ID")),
wavehouse.WithHeader("CF-Access-Client-Secret", os.Getenv("CF_ACCESS_CLIENT_SECRET")),
// For a credential that rotates, a function, called before every attempt:
wavehouse.WithHeaderFunc(func(ctx context.Context) (http.Header, error) {
s, err := secrets.Current(ctx)
if err != nil {
return nil, err
}
return http.Header{"X-Access-Secret": {s}}, nil
}),
)
if err != nil {
log.Fatal(err)
}
// One call's own headers:
rows, err := wh.From("clicks").Header("X-Trace-Id", "abc123").Limit(10).Fetch(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(len(rows))

PipeCall.Header, SQLCall.Header and SubscribeOptions.Header do the same for a pipe call, a SQL call and a stream. An invalid header name or value is an error before anything is sent: from New for WithHeader, from the call for a per-call header.

The layers, lowest to highest:

TypeScript Go
1 options.headers (an object, or the function’s result) WithHeader, then WithHeaderFunc over it
2 the call’s headers, or StreamOptions.headers the call’s Header, or SubscribeOptions.Header
3 auth’s Authorization the token’s or operator key’s Authorization
4 the SDK’s own Content-Type and Accept (and Last-Event-ID on a stream) the SDK’s own Content-Type, Accept and User-Agent (and Last-Event-ID on a stream)

Names match case-insensitively, as HTTP requires, so authorization and Authorization are one header. A higher layer replaces a header of the same name and is never joined with it: a header joined rather than replaced is how a request ends up sending Content-Type: application/json, image/png. So a custom header can’t displace the credential: when the SDK has a token to send, its Authorization wins. When it has none, a custom Authorization header is sent as given, in both SDKs. Any custom header counts as a credential when the SDK decides whether to follow a redirect (Redirects).

Request and transport options

Section titled “Request and transport options”
  • TypeScript
  • Go

Extra RequestInit fields. options.fetchOptions is merged into the RequestInit of every request, streams included, for settings that aren’t headers and don’t warrant replacing the whole transport:

const wh = createClient({
baseURL: 'https://wavehouse.example.com',
options: { fetchOptions: { cache: 'no-store', mode: 'cors' } },
});
// One call's own fields, merged over the client's field by field:
await wh.from('clicks').selectAll().fetch({ fetchOptions: { next: { tags: ['clicks'] } } as RequestInit });

It carries any RequestInit field (mode, cache, keepalive, credentials, redirect) plus runtime-specific extensions such as Next.js’s next: { tags }, which tags the cached response for on-demand revalidation. Only those extensions need a cast; the standard fields are declared on RequestInit already. The fields the SDK controls (method, headers, body and signal) always win, so this can’t corrupt the request itself; in particular a headers field here is ignored, so use options.headers. A request that carries a credential has its redirect set to manual whatever you set (Redirects).

Two of those fields don’t apply to streams

On .stream() and .liveQuery()’s live connection the transport keeps cache (always no-store) and redirect for itself, because there they are correctness rather than preference. credentials stays yours, forwarded in a browser and dropped elsewhere, because some runtimes throw if it is set at all. Everything else reaches streams normally.

credentials: 'include' needs a proxy that owns CORS

Sending cookies cross-origin is a common reason to reach for this, but it can’t work against WaveHouse’s own CORS: it deliberately never emits Access-Control-Allow-Credentials (it is a bearer-token API), so a browser blocks the response. It works where a fronting proxy answers CORS itself; see Behind a reverse proxy. Same-origin deployments already send cookies without it.

Supplying your own fetch. options.fetch replaces the HTTP implementation the SDK uses, and a per-call fetch replaces it for one call (a framework’s request-scoped fetch, such as SvelteKit’s in load()). Reach for it to route through a proxy, attach client certificates, wrap requests in your own middleware (logging, tracing, circuit breaking), stub HTTP in tests without monkey-patching a global, or work around a transport bug in the runtime:

const wh = createClient({
baseURL: 'https://<project_id>.wavehouse.app',
options: {
fetch: async (url, init) => {
const started = performance.now();
const res = await fetch(url, init);
console.log(res.status, url, `${Math.round(performance.now() - started)}ms`);
return res;
},
},
});

Retries go through the same function, so middleware sees every attempt.

The SDK always calls your function with a string URL and a plain RequestInit, and it aborts init.signal to cancel a call or close a stream, so honor the signal: an implementation that ignores it keeps a request, or a stream’s socket, running after the caller let go of it. Off the response, the REST path reads .type, .status, .ok and .headers always, .text() on success, and .statusText plus .json() when the response is not ok. A stub used with .stream() or .liveQuery() needs .ok, .status, .type, .headers carrying content-type: text/event-stream, and a live, unread .body, plus .statusText and .json() if it ever answers a stream with a non-ok response.

On REST, if your function rejects, the request becomes a NETWORK_ERROR and is retried with backoff on reads and ingest. wh.sql() and pipe calls are resent only when the connection was certainly never made (which calls are resent). If the AbortSignal you passed has been aborted, the result is ABORTED and nothing is retried. That is decided from the signal rather than from what your function threw, so an implementation that signals an abort its own way (AbortSignal.timeout() raises a TimeoutError, node-fetch its own AbortError class) is reported the same way. On a stream a rejection is reported as SSE_NETWORK_ERROR and re-dialed, an AbortError included: only an abort the stream raised itself, through .close(), ends it.

Streaming asks more of a custom fetch

.stream() and .liveQuery() read the response as it arrives, so an options.fetch used with them must return a response with a live streaming body. A response handed back with an absent or already-consumed body fails fast with SSE_NO_STREAM_BODY. What the SDK cannot rescue is a wrapper that awaits the body before returning (await res.text(), or the res.clone().text() a logging wrapper reaches for), because on a stream that never ends it never resolves and your function never returns. Both satisfy every REST call, which is what makes the trap easy to walk into.

The option’s type is exported as FetchLike. It is written out rather than as typeof fetch, which resolves differently depending on whether your TypeScript lib includes DOM. Its URL parameter is string, all the SDK ever passes, which, because function parameters are contravariant, accepts more implementations than the wider spelling would: the global fetch fits, and so does hand-written (url: string, init?: RequestInit) => Promise<Response> middleware. Let TypeScript infer the parameters ((url, init) => …) and it fits without annotation.

Swapping in undici. The motivating case is a transport bug in the runtime’s own HTTP stack, which you can’t fix from inside the SDK: for example undici #5600, where reusing a keep-alive socket while the event loop is idle stalls the request before it goes out. How bad it gets varies with the runtime and the idle gap: the upstream report measured ~450–465 ms against a 10 ms server, and we have measured anything from ~100 ms to tens of seconds on a server answering instantly. It affects undici 8.8.0–8.9.0, and Node 26 bundles 8.9.0.

Upgrading undici is the actual fix: it landed in 8.10.0. What options.fetch buys you is a way to get there without waiting for a new runtime: install undici yourself and route requests through it. The one non-obvious part is that you must pass its dispatcher explicitly.

import { createClient } from '@wavehouse/sdk';
import { Agent, fetch as undiciFetch } from 'undici'; // npm install undici — 8.10.0+
// Explicit, not implied — see below.
const dispatcher = new Agent();
const wh = createClient({
baseURL: 'https://<project_id>.wavehouse.app',
options: {
fetch: (url, init) =>
undiciFetch(url, { ...init, dispatcher } as never) as unknown as Promise<Response>,
},
});

Importing a fixed undici is not enough on its own

undici keeps its connection pool on a shared globalThis symbol, and whichever copy loads first claims it. Node claims it for the bundled copy the first time anything touches one of its web globals (a fetch() call, but equally a new Headers() or new Response()), not at startup. So which undici owns the pool comes down to a load order you don’t really control, and auditing your own code for fetch calls won’t tell you: any dependency can claim it first, and so can this SDK, which constructs a Headers on some error paths. Call undiciFetch without a dispatcher and it resolves whatever is on that symbol, so requests can go through the buggy pool even though you imported a fixed undici.

Measured with 8.9.0 loaded first and 8.10.0’s fetch doing the request, 1.5 s idle gaps against a 10 ms server:

per-request ms
no explicit dispatcher 21 1514 1495 583 ← still stalling
explicit new Agent() 17 14 12 13

An explicit dispatcher wins because the request never consults the shared symbol at all. An explicit setGlobalDispatcher call (below) wins the other way round: it overwrites the symbol after the first copy claimed it.

Both casts are load-bearing, for one reason: undici declares its own request and response types, separate from the ones behind your global fetch, so the two aren’t structurally assignable. { ...init, dispatcher } as never covers the split on RequestInit, which differs on body and headers (never is assignable to either spelling, so one snippet compiles whether or not your lib includes DOM), and the return cast handles the Response mismatch. The URL needs no cast: FetchLike declares it as string, which undici’s RequestInfo accepts. They are safe because of the narrow runtime contract above.

If you’re genuinely pinned to an affected undici, the same snippet fixes it with a dispatcher that never reuses a keep-alive socket: new Agent({ pipelining: 0 }). That costs a fresh connection per request, so prefer upgrading. Tuning keepAliveTimeout does not help: the retirement timer is starved by the same idle event loop that triggers the bug, so the socket is still there to be reused.

To change the transport process-wide instead of per client, an installed undici’s setGlobalDispatcher(new Agent()) is picked up by Node’s built-in global fetch, with no options.fetch needed. That is an explicit write, so it wins the race described above, but only if the installed undici is 8.10.0 or later.

Supplying your own http.Client. WithHTTPClient sets the *http.Client requests go through, for a custom transport, proxy or TLS setup:

hc := &http.Client{Transport: &http.Transport{MaxIdleConnsPerHost: 32}}
wh, err := wavehouse.New("http://localhost:8080", wavehouse.WithHTTPClient(hc))
if err != nil {
log.Fatal(err)
}

The default client has no overall Timeout, because streams are long-lived; bound each call with its context instead, or give each attempt a deadline with RetryPolicy.AttemptTimeout. Don’t set Timeout on a client you hand to the SDK, since it would also end a stream. The client’s own CheckRedirect applies to requests that carry no credential; a credentialed request never follows a redirect (Redirects).

Type-Safe Tables

Section titled “Type-Safe Tables”
  • TypeScript
  • Go

Pass a Database type to get autocomplete on table names and row types:

interface Database {
clicks: { page: string; button: string; score: number; received_timestamp: string };
users: { id: string; name: string; email: string };
}
const wh = createClient<Database>({ baseURL: '...' });
const clicks = wh.from('clicks'); // autocompletes
const { data } = await clicks.select('page', 'button').limit(10);
// data is Array<{ page: string; button: string; score: number; received_timestamp: string }> | null

The codegen CLI generates the Database interface from a running server.

Scan rows into your own structs, matched by json tag:

var top []struct {
Page string `json:"page"`
Views uint64 `json:"views"` // exact, even above 2^53
}
err := wh.From("clicks").Select("page").Count("*", "views").GroupBy("page").Scan(ctx, &top)
if err != nil {
log.Fatal(err)
}

Or Fetch rows as []wavehouse.Row and read them with typed accessors (Reading rows). The Go SDK has no codegen.

Result Type

Section titled “Result Type”
  • TypeScript
  • Go

Every async REST call returns a Result<T>, a discriminated union that never throws for anything the server returns (caller and environment errors do throw; see Error handling):

type Result<T> =
| { ok: true; data: T; error: null; hasMore?: boolean; next?: () => Promise<Result<T>> }
| { ok: false; data: null; error: WaveHouseError; hasMore?: false; next?: undefined }
interface WaveHouseError {
status: number; // HTTP status (0 when no response arrived)
code: string; // e.g. 'HTTP_400', 'clickhouse.rejected', 'NETWORK_ERROR', 'ABORTED'
message: string; // human-readable
details?: unknown; // the response body, when there was one
retryable: boolean; // the server's verdict, else true for a 5xx, 408 or 429
}

Branch on result.ok, or destructure { data, error }:

const result = await wh.from('clicks').select('page').limit(10);
if (result.ok) {
console.log(result.data); // TypeScript knows data is non-null here
} else {
console.error(result.error.code, result.error.message);
}

Every call returns its value and an error. An answer the server gave is an *wavehouse.APIError; match a status with errors.Is and the sentinels, or read the fields with errors.As:

_, err := wh.DLQStats(ctx)
switch {
case errors.Is(err, wavehouse.ErrForbidden):
// a 403
case wavehouse.IsRetryable(err):
// safe to send this call again later
}
if apiErr, ok := errors.AsType[*wavehouse.APIError](err); ok {
// Quote RequestID when reporting a failure: the server logged the request under it.
fmt.Println(apiErr.StatusCode, apiErr.Code, apiErr.RequestID)
}

A failure that got no HTTP answer is a transport error that unwraps to its cause, so errors.Is(err, context.Canceled) works.

The codes, the sentinels and what each SDK retries are in Error handling.

Where the SDKs differ

Section titled “Where the SDKs differ”

The SDKs mean to behave the same. The main differences by design (others are noted where they apply):

  • A single-row insert is sent as JSON by the TypeScript SDK and as one line of NDJSON by the Go SDK, so Go returns the per-record summary for one row as for many (Inserting rows).
  • The default row limit is 1000 in TypeScript, which sends it on every query that sets none; Go sends none, and the server’s query.default_max_rows (10,000 by default) applies (Limit).
  • Times are typed in Go: TimeRange takes time.Time, Last a time.Duration, and Row.Time and Event.ReceivedAt parse what the server sends. TypeScript takes a Date or a string and hands timestamps back as strings.
  • The operator key is a first-class option in Go (WithOperatorKey, sent as Authorization: Operator <key>); TypeScript sends it as an X-Operator-Key header through options.headers.
  • Live queries (liveQuery) are TypeScript only. So are pagination (hasMore/next), client-side stream filtering, and the codegen CLI. The Go SDK has none of these yet: live queries and pagination wait for server support (#951, #452).

Known server limitations

Section titled “Known server limitations”

These are the server’s, so both SDKs inherit them:

  • A group_by key comes back only if it is also selected (#295): select the key as well as grouping by it.
  • Nothing says a result was capped (#999): a query over the row cap returns exactly the cap’s worth of rows, and nothing tells that apart from a complete answer.
  • Result rows carry no column order or types (#1000): /v1/query and pipes return each row as a JSON object whose keys come back in alphabetical order, not select order, with no types, and an empty result says nothing about its columns.
  • A read can’t be joined exactly to a stream (#951): a query result doesn’t say how far into the stream it reaches, and a replay past the retained history resumes with a hole and no signal. TypeScript’s liveQuery deduplicates on a best-effort basis until that lands (Live queries).

Explore the SDK

Section titled “Explore the SDK”
QueriesThe query builder, filters, time windows, inserts, pagination and raw SQL.
Streaming & Live QueriesReal-time SSE streams, reconnects and resumption, and backfill-then-live queries.
PipesRun named query pipes and read their definitions.
Admin & SystemSchema introspection, settings reload, DLQ stats, health and version.
Reference & CLIRetries, timeouts, redirects, error codes, the API at a glance, codegen and E2E testing.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.