Wire client
BrainClient over the BRN0 protocol — connect, ClientConfig, the two auth methods, act_as, multiplexing, the connection pool, and the id helpers.
BrainClient.connect
static connect(host: string, port: number, config: ClientConfig): Promise<BrainClient>The handshake runs inside connect: HELLO, version negotiation, AUTH. A
server that negotiates a version the client did not offer rejects with
VersionMismatch rather than proceeding.
ClientConfig
authAuthrequiredThe credential. See below.
clientIdstringoptionalIdentifies the client to the server. Defaults to
"brain-db-sdk-typescript".
supportedVersionsnumber[]optionalWire versions this client accepts. Defaults to [1] — the only version
Brain speaks today.
capabilitiesHelloCapabilitiesoptionalWhat the client supports. Defaults to
{ streaming: true, compressionZstd: false, serverPush: false }.
connectTimeoutMsnumberoptionalDeadline for the connect and handshake. Defaults to 10_000.
requestTimeoutMsnumberoptionalDeadline for an ordinary request. Defaults to 30_000.
derivedWriteTimeoutMsnumberoptionalDeadline for an encode under WaitMode.Derived only. Defaults to
DEFAULT_DERIVED_WRITE_TIMEOUT_MS — 120 s. It exists because the
30 s request timeout would fire before the derivation pipeline finished.
Auth
A discriminated union with two arms:
type Auth =
| { kind: "token"; token: Uint8Array }
| { kind: "mtls"; certFingerprint: Uint8Array; assertedSubject: string };{ kind: "token", token }Uint8ArrayrequiredA bearer token as bytes, not a string — encode it yourself with
new TextEncoder().encode(...).
{ kind: "mtls", certFingerprint, assertedSubject }—optionalMutual TLS: the client certificate's fingerprint plus the subject it claims. The server checks the assertion against the presented cert.
import { BrainClient } from "@brain-db/sdk";
const client = await BrainClient.connect("127.0.0.1", 9090, {
auth: { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) },
requestTimeoutMs: 15_000,
});
try {
// ... verbs
} finally {
await client.close(); // sends BYE, then closes
}ConnectionInfo
What the handshake established, available on client.connection with no
round trip:
namespacestringalwaysspaceIdUint8ArrayalwaysserverIdstringalwayschosenVersionnumberalwaysconnectionIdUint8ArrayalwaysboundShardIdnumberalwaysWhich shard the connection is pinned to. A request for data on another
shard is WrongShard, not a transparent redirect.
permissionsSpacePermissionsalwaysserverFeaturesServerFeaturesalwaysclient.namespace, client.spaceId and client.isClosed are shorthands.
Multiplexing
One connection carries many concurrent requests, demultiplexed by
stream_id. You do not manage streams — issue calls concurrently and the
MuxConnection underneath sorts the responses out.
const [answer, entities, caps] = await Promise.all([
client.recall(recallReq),
client.listEntities(listReq),
client.capabilities(),
]);Streaming verbs — anything with a …Frames form, plus subscribe — each
occupy one stream for their duration. cancelStream(streamId) ends one early;
see Subscriptions.
act_as
Every tenant-scoped wire request carries an optional actAs selector:
interface ActAs {
namespace: string;
space: string;
grant?: number; // ActAsGrant.SchemaUpload (1 << 4) | ActAsGrant.Admin (1 << 5)
}It is what lets one connection serve many spaces. The credential fixes the
namespace; act_as selects the space per request. The builders expose it as
.actAs(namespace, space); hand-built requests set the field directly.
act_as is a grant, not a claim
A principal without the canActAs grant — or one naming a namespace outside
its allowlist — gets ActAsDenied (0x0033). isActAsDenied(err) is the
predicate. The two optional grant bits, SchemaUpload and Admin, are
requested per call and must also be held.
This is the mechanism behind per-tenant isolation at scale: one pooled connection, a storage-key prefix per end user, and no credential per user. See Namespaces.
Pool
A fixed-size set of connections handed out round-robin.
Pool.connect(host, port, size, config)Promise<Pool>requiredOpens size connections, each running its own handshake. Every member
shares the credential, so the server binds them to the same agent; they
stay individually identifiable by session id. size < 1 throws. On a
mid-open failure it closes the members already opened and re-throws.
pool.get()BrainClientrequiredThe next connection, round-robin. No liveness check.
pool.getHealthy()Promise<BrainClient>requiredThe next connection, reconnected first if its socket died. Concurrent callers landing on the same dead slot share one reconnect rather than opening a socket each.
pool.size()numberoptionalpool.close()Promise<void>optionalBYE and close every member, best-effort.
A pooled member outlives any single request, so a server restart leaves
every borrower holding the same dead socket until the process is bounced.
get() will hand it to you; getHealthy() dials a replacement in place.
Requests already in flight on the old connection fail either way.
Id helpers
newId()Uint8ArrayrequiredA fresh random 16-byte id. Use it for requestId and txnId on
hand-built requests; the builders call it for you.
deriveSpaceId(namespace, space)Uint8ArrayoptionalThe space id the server derives at ingress:
UUIDv5(UUIDv5(ROOT, namespace), space). Folding the namespace in is what
makes equal space strings under different namespaces diverge. The seed is
frozen and pinned by a golden test on both sides.
Do not let the derived space id leave Brain
Clients only ever send the space string. deriveSpaceId exists for
the rare local case — naming the effective space by its resolved id in a
subscription filter. It is Brain's internal identifier, not your
control-plane's; using it as an external key couples two id spaces that are
deliberately separate. See Namespaces.
Was this page helpful?