You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by pi...@apache.org on 2026/07/28 05:58:57 UTC
(iggy) 01/01: feat(js): add VSR framing to the Node SDK
This is an automated email from the ASF dual-hosted git repository.
spetz pushed a commit to branch vsr_ts_sdk
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit 79fe8c3ed915afb0d3617e3dee8d3895f58d4c66
Author: spetz <pi...@gmail.com>
AuthorDate: Tue Jul 28 07:58:43 2026 +0200
feat(js): add VSR framing to the Node SDK
---
.github/actions/node-npm/pre-merge/action.yml | 49 ++-
.github/config/components.yml | 2 +-
.github/workflows/_test.yml | 13 +-
codecov.yml | 8 +-
foreign/node/README.md | 86 ++++-
foreign/node/package-lock.json | 4 +-
foreign/node/package.json | 8 +-
foreign/node/scripts/check-vsr-protocol.mjs | 301 ++++++++++++++++
foreign/node/src/bdd/raw.ts | 7 +-
foreign/node/src/client/client.config.test.ts | 95 +++++
foreign/node/src/client/client.config.ts | 56 +++
foreign/node/src/client/client.connection.ts | 196 +++++++----
foreign/node/src/client/client.frame.test.ts | 127 +++++++
foreign/node/src/client/client.frame.ts | 77 ++++
foreign/node/src/client/client.socket.test.ts | 387 +++++++++++++++++++++
foreign/node/src/client/client.socket.ts | 363 ++++++++++++++++---
foreign/node/src/client/client.ts | 13 +-
foreign/node/src/client/client.type.ts | 25 +-
foreign/node/src/client/index.ts | 1 +
foreign/node/src/e2e/tcp.cluster.e2e.ts | 25 +-
foreign/node/src/e2e/tcp.consumer-group.e2e.ts | 8 +-
foreign/node/src/e2e/tcp.consumer-stream.e2e.ts | 8 +-
foreign/node/src/e2e/tcp.raw.e2e.ts | 71 +++-
foreign/node/src/e2e/test-client.utils.ts | 2 +
foreign/node/src/index.ts | 2 +
foreign/node/src/wire/command-set.test.ts | 106 +++++-
foreign/node/src/wire/command-set.ts | 37 +-
foreign/node/src/wire/command.code.ts | 3 +
.../node/src/wire/consumer-group/group.utils.ts | 7 +
foreign/node/src/wire/consumer-group/index.ts | 1 +
.../wire/consumer-group/sync-group.command.test.ts | 99 ++++++
.../src/wire/consumer-group/sync-group.command.ts | 68 ++++
foreign/node/src/wire/error.utils.ts | 22 +-
.../node/src/wire/message/poll-messages.command.ts | 98 +++++-
foreign/node/src/wire/topic/topic.utils.test.ts | 45 +++
foreign/node/src/wire/topic/topic.utils.ts | 4 +-
foreign/node/src/wire/vsr/header.test.ts | 99 ++++++
foreign/node/src/wire/vsr/header.ts | 165 +++++++++
foreign/node/src/wire/vsr/index.ts | 152 ++++++++
foreign/node/src/wire/vsr/namespace.test.ts | 251 +++++++++++++
foreign/node/src/wire/vsr/namespace.ts | 214 ++++++++++++
foreign/node/src/wire/vsr/operation.test.ts | 160 +++++++++
foreign/node/src/wire/vsr/operation.ts | 206 +++++++++++
foreign/node/src/wire/vsr/register.test.ts | 93 +++++
foreign/node/src/wire/vsr/register.ts | 116 ++++++
foreign/node/src/wire/vsr/reply.test.ts | 177 ++++++++++
foreign/node/src/wire/vsr/reply.ts | 165 +++++++++
foreign/node/src/wire/vsr/session.test.ts | 57 +++
foreign/node/src/wire/vsr/session.ts | 113 ++++++
foreign/node/src/wire/vsr/vsr.test.ts | 110 ++++++
50 files changed, 4329 insertions(+), 173 deletions(-)
diff --git a/.github/actions/node-npm/pre-merge/action.yml b/.github/actions/node-npm/pre-merge/action.yml
index fa065e67e..bf55583bf 100644
--- a/.github/actions/node-npm/pre-merge/action.yml
+++ b/.github/actions/node-npm/pre-merge/action.yml
@@ -20,7 +20,7 @@ description: Node.js pre-merge testing github iggy actions
inputs:
task:
- description: "Task to run (lint, test, build, e2e)"
+ description: "Task to run (lint, test, build, e2e, e2e-vsr)"
required: true
runs:
@@ -39,11 +39,11 @@ runs:
shell: bash
- name: Setup Rust with cache
- if: inputs.task == 'e2e'
+ if: inputs.task == 'e2e' || inputs.task == 'e2e-vsr'
uses: ./.github/actions/utils/setup-rust-with-cache
- name: Install netcat
- if: inputs.task == 'e2e'
+ if: inputs.task == 'e2e' || inputs.task == 'e2e-vsr'
run: sudo apt-get update && sudo apt-get install -y netcat-openbsd
shell: bash
@@ -82,8 +82,6 @@ runs:
echo "Warning: dist directory not found after build"
fi
shell: bash
-
-
- name: Test
if: inputs.task == 'test'
run: |
@@ -115,6 +113,47 @@ runs:
IGGY_SERVER_TCP_PORT: 8090
shell: bash
+ - name: Start Iggy VSR server
+ id: iggy-vsr
+ if: inputs.task == 'e2e-vsr'
+ uses: ./.github/actions/utils/server-start
+ with:
+ cargo-bin: iggy-server-ng
+ pid-file: ${{ runner.temp }}/iggy-node-vsr.pid
+ log-file: ${{ runner.temp }}/iggy-node-vsr.log
+ wait-timeout-seconds: "90"
+ env:
+ IGGY_SYSTEM_PATH: ${{ runner.temp }}/iggy-node-vsr-data
+
+ - name: VSR E2E tests
+ if: inputs.task == 'e2e-vsr'
+ run: |
+ cd foreign/node
+ mkdir -p ../../reports/node-coverage/e2e-vsr
+ npx c8 --reporter=lcov \
+ --reports-dir=../../reports/node-coverage/e2e-vsr \
+ npm run test:e2e:vsr
+ env:
+ IGGY_SERVER_HOST: 127.0.0.1
+ IGGY_SERVER_TCP_PORT: 8090
+ IGGY_TEST_PROTOCOL: vsr
+ shell: bash
+
+ - name: Stop Iggy VSR server
+ if: always() && inputs.task == 'e2e-vsr'
+ uses: ./.github/actions/utils/server-stop
+ with:
+ pid-file: ${{ steps.iggy-vsr.outputs.pid_file }}
+ log-file: ${{ steps.iggy-vsr.outputs.log_file }}
+
+ - name: Upload VSR server logs
+ if: always() && inputs.task == 'e2e-vsr'
+ uses: actions/upload-artifact@v7
+ with:
+ name: iggy-node-vsr-server-logs
+ path: ${{ steps.iggy-vsr.outputs.log_file }}
+ if-no-files-found: ignore
+
- name: Stop Iggy server (plain)
if: always() && inputs.task == 'e2e'
uses: ./.github/actions/utils/server-stop
diff --git a/.github/config/components.yml b/.github/config/components.yml
index 2d30025cb..a2ec096d5 100644
--- a/.github/config/components.yml
+++ b/.github/config/components.yml
@@ -250,7 +250,7 @@ components:
- "ci-infrastructure" # CI changes trigger full regression
paths:
- "foreign/node/**"
- tasks: ["lint", "test", "build", "e2e"]
+ tasks: ["lint", "test", "build", "e2e", "e2e-vsr"]
sdk-go:
depends_on:
diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml
index 3bfdb057d..18d477127 100644
--- a/.github/workflows/_test.yml
+++ b/.github/workflows/_test.yml
@@ -124,13 +124,20 @@ jobs:
task: ${{ inputs.task }}
- name: Upload Node coverage to Codecov
- if: inputs.component == 'sdk-node' && (inputs.task == 'test' || inputs.task == 'e2e')
+ if: >-
+ inputs.component == 'sdk-node' &&
+ (inputs.task == 'test' ||
+ inputs.task == 'e2e' ||
+ inputs.task == 'e2e-vsr')
uses: codecov/codecov-action@v7.0.0
with:
token: ${{ secrets.CODECOV_TOKEN }}
- files: reports/node-coverage/${{ inputs.task == 'test' && 'unit' || 'e2e' }}/lcov.info
+ files: >-
+ reports/node-coverage/${{
+ inputs.task == 'test' && 'unit' || inputs.task
+ }}/lcov.info
disable_search: true
- flags: node
+ flags: node-${{ inputs.task }}
fail_ci_if_error: false
verbose: true
override_pr: ${{ github.event.pull_request.number }}
diff --git a/codecov.yml b/codecov.yml
index 2fcd7103b..691c1ae79 100644
--- a/codecov.yml
+++ b/codecov.yml
@@ -62,7 +62,13 @@ flag_management:
- name: php
paths:
- foreign/php/
- - name: node
+ - name: node-test
+ paths:
+ - foreign/node/
+ - name: node-e2e
+ paths:
+ - foreign/node/
+ - name: node-e2e-vsr
paths:
- foreign/node/
- name: go
diff --git a/foreign/node/README.md b/foreign/node/README.md
index 65e6fa333..ab5506d37 100644
--- a/foreign/node/README.md
+++ b/foreign/node/README.md
@@ -30,6 +30,89 @@ npm i --save apache-iggy
## basic usage
+### VSR framing
+
+Classic framing remains the default. Select VSR explicitly when connecting to
+an Iggy VSR server:
+
+```typescript
+import {
+ BinaryRequestKind,
+ SimpleClient,
+ getRawClient,
+} from "apache-iggy";
+
+const config = {
+ protocol: "vsr" as const,
+ transport: "TCP" as const,
+ options: { host: "127.0.0.1", port: 8090 },
+ credentials: { username: "iggy", password: "iggy" },
+};
+const client = new SimpleClient(getRawClient(config));
+const response = await client.sendBinaryRequest(
+ BinaryRequestKind.NonReplicated,
+ 60_000,
+ Buffer.from("opaque mutation"),
+);
+```
+
+VSR is a runtime protocol choice in Node.js, not a build feature. Custom
+non-replicated codes use `Operation::NonReplicated`; custom replicated codes
+are rejected until a server-side replicated extension registry exists.
+
+The same npm package supports both framing modes. VSR currently supports TCP
+only and restricts `Client` to one pooled connection because authentication,
+request sequencing, and consumer-group assignments belong to one consensus
+session. Configurations requesting VSR over TLS or more than one pooled
+connection fail before a socket is opened.
+
+Response frames larger than `maxResponseFrameSize` (default 64 MiB) are
+rejected and close the connection under both framing modes. Raise the limit
+in the client configuration when polling very large batches.
+
+VSR authentication translates the existing password and personal-access-token
+login APIs into the register handshake required by the consensus protocol. A
+disconnect or eviction invalidates the session, and later work must register a
+new session. Transient not-committed responses retry the exact encoded request
+within one bounded deadline. A disconnected mutation is never replayed under a
+new session.
+
+`sendBinaryRequest` has one intentionally breaking signature:
+
+```typescript
+sendBinaryRequest(
+ kind: BinaryRequestKind,
+ code: number,
+ payload: Buffer,
+): Promise<Buffer>
+```
+
+Migrate calls from:
+
+```typescript
+await client.sendBinaryRequest(code, payload);
+```
+
+to:
+
+```typescript
+await client.sendBinaryRequest(
+ BinaryRequestKind.NonReplicated,
+ code,
+ payload,
+);
+```
+
+There is no compatibility overload or `sendBinaryRequestWithKind` method.
+Known command tables remain authoritative under VSR: a conflicting declaration
+is rejected, unknown non-replicated codes reach the server, and unknown
+replicated codes fail locally until the extension registry exists. The kind is
+not serialized by classic framing, so classic request bytes remain unchanged.
+
+The client includes its npm package version and the binary protocol crate
+version in VSR registration. An incompatible server rejects registration with
+a protocol-version error instead of accepting a mismatched wire contract.
+
```ts
import { Client } from "apache-iggy";
@@ -60,7 +143,8 @@ npm run build
### test
-note: use env var `IGGY_TCP_ADDRESS="host:port"` to set server address for bdd and e2e tests.
+note: use env var `IGGY_TCP_ADDRESS="host:port"` to set the server
+address for bdd and e2e tests.
#### unit tests
diff --git a/foreign/node/package-lock.json b/foreign/node/package-lock.json
index fcecccd64..9d4877ee2 100644
--- a/foreign/node/package-lock.json
+++ b/foreign/node/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "apache-iggy",
- "version": "0.8.1-edge.2",
+ "version": "0.8.1-edge.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "apache-iggy",
- "version": "0.8.1-edge.2",
+ "version": "0.8.1-edge.3",
"license": "Apache-2.0",
"dependencies": {
"debug": "4.4.3",
diff --git a/foreign/node/package.json b/foreign/node/package.json
index 0437623c3..6a8839aa4 100644
--- a/foreign/node/package.json
+++ b/foreign/node/package.json
@@ -1,7 +1,7 @@
{
"name": "apache-iggy",
"type": "module",
- "version": "0.8.1-edge.2",
+ "version": "0.8.1-edge.3",
"description": "Official Apache Iggy NodeJS SDK",
"keywords": [
"iggy",
@@ -37,12 +37,14 @@
"scripts": {
"test:unit": "node --import @swc-node/register/esm-register --test --experimental-test-coverage './src/**/*.test.ts'",
"test:e2e": "node --import @swc-node/register/esm-register --test --experimental-test-coverage --test-force-exit './src/e2e/*.e2e.ts'",
+ "test:e2e:vsr": "IGGY_TEST_PROTOCOL=vsr node --import @swc-node/register/esm-register --test --experimental-test-coverage --test-force-exit './src/e2e/tcp.*.e2e.ts'",
"test:bdd": "cucumber-js --exit",
"test": "npm run test:unit && npm run test:bdd && npm run test:e2e",
"clean": "rm -Rf dist/",
- "lint": "eslint src/**/*.ts",
+ "lint": "eslint 'src/**/*.ts'",
"commitlint": "commitlint --edit",
- "build": "tsc -p tsconfig.json",
+ "build": "tsc -p tsconfig.json && npm run check:vsr-protocol",
+ "check:vsr-protocol": "node scripts/check-vsr-protocol.mjs",
"start": "node dist/index.js",
"prepare": "husky || true"
},
diff --git a/foreign/node/scripts/check-vsr-protocol.mjs b/foreign/node/scripts/check-vsr-protocol.mjs
new file mode 100644
index 000000000..af1a0a4cf
--- /dev/null
+++ b/foreign/node/scripts/check-vsr-protocol.mjs
@@ -0,0 +1,301 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import assert from 'node:assert/strict';
+import { access, readFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const rootCandidates = [
+ resolve(import.meta.dirname, '../..'),
+ resolve(import.meta.dirname, '../../..')
+];
+let root;
+for (const candidate of rootCandidates) {
+ try {
+ await access(resolve(candidate, 'core/binary_protocol/src/codes.rs'));
+ root = candidate;
+ break;
+ } catch {
+ // Try the monorepo layout after the isolated test layout.
+ }
+}
+assert.ok(root, 'Apache Iggy repository root was not found');
+const read = (path) => readFile(resolve(root, path), 'utf8');
+const nodeRoot = resolve(import.meta.dirname, '..');
+const readNode = (path) => readFile(resolve(nodeRoot, path), 'utf8');
+
+const [
+ rustCodes,
+ rustDispatch,
+ rustHeader,
+ rustCommand,
+ rustOperation,
+ rustProtocolCargo,
+ nodeCodes,
+ nodeHeader,
+ nodeOperation,
+ nodeRegister,
+] = await Promise.all([
+ read('core/binary_protocol/src/codes.rs'),
+ read('core/binary_protocol/src/dispatch.rs'),
+ read('core/binary_protocol/src/consensus/header.rs'),
+ read('core/binary_protocol/src/consensus/command.rs'),
+ read('core/binary_protocol/src/consensus/operation.rs'),
+ read('core/binary_protocol/Cargo.toml'),
+ readNode('src/wire/command.code.ts'),
+ readNode('src/wire/vsr/header.ts'),
+ readNode('src/wire/vsr/operation.ts'),
+ readNode('src/wire/vsr/register.ts'),
+]);
+
+const numericValues = (source, pattern) =>
+ [...source.matchAll(pattern)].map((match) => Number(match[1]));
+
+const rustCommandCodes = numericValues(
+ rustCodes,
+ /^pub const [A-Z0-9_]+_CODE: u32 = ([0-9]+);$/gm
+).sort((left, right) => left - right);
+const nodeCommandBlock =
+ nodeCodes.match(/export const COMMAND_CODE = \{([\s\S]*?)\n\};/)?.[1] ?? '';
+const nodeCommandCodes = numericValues(
+ nodeCommandBlock,
+ /^\s*[A-Za-z0-9]+:\s*([0-9]+),/gm
+).sort((left, right) => left - right);
+assert.deepEqual(
+ nodeCommandCodes,
+ rustCommandCodes,
+ 'Node COMMAND_CODE differs from the Rust command registry'
+);
+
+const enumValues = (source, pattern) =>
+ new Map(
+ [...source.matchAll(pattern)].map((match) => [
+ match[1],
+ Number(match[2])
+ ])
+ );
+const rustOperations = enumValues(
+ rustOperation,
+ /^\s+([A-Za-z0-9]+)\s*=\s*([0-9]+),$/gm
+);
+const nodeOperations = enumValues(
+ nodeOperation,
+ /^\s+([A-Za-z0-9]+):\s*([0-9]+),?$/gm
+);
+assert.deepEqual(
+ nodeOperations,
+ rustOperations,
+ 'Node Operation differs from the Rust consensus enum'
+);
+
+const rustReplicated = new Set(
+ [...rustDispatch.matchAll(
+ /CommandMeta::replicated\([\s\S]*?Operation::([A-Za-z0-9]+)/g
+ )].map((match) => match[1])
+);
+const nodeReplicatedBlock =
+ nodeOperation.match(
+ /const REPLICATED_OPERATION[\s\S]*?new Map\(\[([\s\S]*?)\]\);/
+ )?.[1] ?? '';
+const nodeReplicated = new Set(
+ [...nodeReplicatedBlock.matchAll(/Operation\.([A-Za-z0-9]+)/g)]
+ .map((match) => match[1])
+);
+assert.deepEqual(
+ nodeReplicated,
+ rustReplicated,
+ 'Node replicated operations differ from the Rust dispatch table'
+);
+
+const rustEvictionBlock =
+ rustHeader.match(/pub enum EvictionReason \{([\s\S]*?)\n\}/)?.[1] ?? '';
+const rustEvictions = enumValues(
+ rustEvictionBlock,
+ /^\s+([A-Za-z0-9]+)\s*=\s*([0-9]+),$/gm
+);
+const nodeEvictionBlock =
+ nodeHeader.match(/export const EvictionReason = \{([\s\S]*?)\n\}/)?.[1] ??
+ '';
+const nodeEvictions = enumValues(
+ nodeEvictionBlock,
+ /^\s+([A-Za-z0-9]+):\s*([0-9]+),?$/gm
+);
+assert.deepEqual(
+ nodeEvictions,
+ rustEvictions,
+ 'Node EvictionReason differs from the Rust consensus enum'
+);
+
+const rustCommand2Block =
+ rustCommand.match(/pub enum Command2 \{([\s\S]*?)\n\}/)?.[1] ?? '';
+const rustCommand2 = enumValues(
+ rustCommand2Block,
+ /^\s+([A-Za-z0-9]+)\s*=\s*([0-9]+),$/gm
+);
+const nodeCommand2 = enumValues(
+ nodeHeader.match(/export const Command2 = \{([\s\S]*?)\n\}/)?.[1] ?? '',
+ /^\s+([A-Za-z0-9]+):\s*([0-9]+),?$/gm
+);
+assert.ok(nodeCommand2.size > 0, 'Node Command2 table was not found');
+for (const [name, value] of nodeCommand2)
+ assert.equal(
+ rustCommand2.get(name),
+ value,
+ `Node Command2.${name} differs from Rust`
+ );
+
+const rustHeaderSize = Number(
+ rustHeader.match(/pub const HEADER_SIZE: usize = ([0-9]+);/)?.[1]
+);
+const nodeHeaderSize = Number(
+ nodeHeader.match(/export const HEADER_SIZE = ([0-9]+);/)?.[1]
+);
+assert.equal(nodeHeaderSize, rustHeaderSize, 'VSR header size differs');
+
+// Header field offsets: recompute the #[repr(C)] layout from the Rust struct
+// declarations so a field inserted before the consumed offsets fails here
+// instead of desyncing the hardcoded Node tables.
+const FIELD_LAYOUT = new Map([
+ ['u8', [1, 1]],
+ ['u16', [2, 2]],
+ ['u32', [4, 4]],
+ ['u64', [8, 8]],
+ ['u128', [16, 16]],
+ ['Command2', [1, 1]],
+ ['Operation', [1, 1]],
+ ['EvictionReason', [1, 1]]
+]);
+
+const rustStructOffsets = (structName) => {
+ const body = rustHeader.match(
+ new RegExp(`pub struct ${structName} \\{([\\s\\S]*?)\\n\\}`)
+ )?.[1];
+ assert.ok(body, `Rust struct ${structName} was not found`);
+ const offsets = new Map();
+ let offset = 0;
+ for (const [, field, type] of body.matchAll(
+ /pub ([a-z_0-9]+): ([A-Za-z0-9_]+|\[u8; [0-9]+\]),/g
+ )) {
+ const arrayLength = type.match(/\[u8; ([0-9]+)\]/)?.[1];
+ const [size, align] = arrayLength
+ ? [Number(arrayLength), 1]
+ : FIELD_LAYOUT.get(type) ?? [];
+ assert.ok(
+ size !== undefined,
+ `unknown Rust field type ${type} in ${structName}`
+ );
+ offset = Math.ceil(offset / align) * align;
+ offsets.set(field, offset);
+ offset += size;
+ }
+ assert.equal(
+ offset,
+ rustHeaderSize,
+ `computed ${structName} layout does not fill HEADER_SIZE`
+ );
+ return offsets;
+};
+
+const nodeOffsetTable = (tableName) => {
+ const block = nodeHeader.match(
+ new RegExp(`export const ${tableName} = \\{([\\s\\S]*?)\\n\\} as const;`)
+ )?.[1];
+ assert.ok(block, `Node offset table ${tableName} was not found`);
+ return enumValues(block, /^\s+([A-Za-z0-9]+):\s*([0-9]+),?$/gm);
+};
+
+const toSnakeCase = (name) =>
+ name.replace(/([A-Z])/g, '_$1').toLowerCase();
+
+for (const [tableName, structName] of [
+ ['REQUEST_OFFSET', 'RequestHeader'],
+ ['REPLY_OFFSET', 'ReplyHeader'],
+ ['EVICTION_OFFSET', 'EvictionHeader']
+]) {
+ const rustOffsets = rustStructOffsets(structName);
+ for (const [field, value] of nodeOffsetTable(tableName))
+ assert.equal(
+ value,
+ rustOffsets.get(toSnakeCase(field)),
+ `Node ${tableName}.${field} differs from the Rust ${structName} layout`
+ );
+}
+
+// Operation classification: evaluate the compiled Node predicates against
+// the band constants and allowlists declared by the Rust enum.
+const operationModule = await import(
+ pathToFileURL(resolve(nodeRoot, 'dist/wire/vsr/operation.js')).href
+);
+const internalStart = rustOperations.get('CreateTopicWithAssignments');
+const metadataStart = rustOperations.get('CreateStream');
+const partitionStart = rustOperations.get('SendMessages');
+const rustMetadataNames = new Set(
+ [...(rustOperation.match(
+ /fn is_metadata[\s\S]*?matches!\(\s*self,([\s\S]*?)\)\s*\n\s*\}/
+ )?.[1] ?? '').matchAll(/Self::([A-Za-z0-9]+)/g)].map((match) => match[1])
+);
+assert.ok(rustMetadataNames.size > 0, 'Rust is_metadata allowlist not found');
+const rustResultFramedNames = new Set(
+ [...(rustOperation.match(
+ /fn is_result_framed[\s\S]*?matches!\(\s*self,([\s\S]*?)\)\s*\n\s*\}/
+ )?.[1] ?? '').matchAll(/Self::([A-Za-z0-9]+)/g)].map((match) => match[1])
+);
+assert.ok(
+ rustResultFramedNames.size > 0,
+ 'Rust is_result_framed allowlist not found'
+);
+for (const [name, value] of rustOperations) {
+ const internal = value >= internalStart && value < metadataStart;
+ const metadata = internal || rustMetadataNames.has(name);
+ assert.equal(
+ operationModule.isMetadata(value),
+ metadata,
+ `Node isMetadata(${name}) differs from Rust is_metadata`
+ );
+ assert.equal(
+ operationModule.isPartition(value),
+ value >= partitionStart,
+ `Node isPartition(${name}) differs from Rust is_partition`
+ );
+ assert.equal(
+ operationModule.isResultFramed(value),
+ metadata || rustResultFramedNames.has(name),
+ `Node isResultFramed(${name}) differs from Rust is_result_framed`
+ );
+}
+
+const protocolVersion =
+ rustProtocolCargo.match(/^version = "([0-9]+)\.([0-9]+)\.([0-9]+)/m);
+assert.ok(protocolVersion, 'binary protocol crate version is missing');
+const packedVersion =
+ Number(protocolVersion[1]) << 20 |
+ Number(protocolVersion[2]) << 10 |
+ Number(protocolVersion[3]);
+const nodePackedVersion = nodeRegister.match(
+ /export const IGGY_PROTOCOL_VERSION =\s*\(([0-9]+) << 20\) \| \(([0-9]+) << 10\) \| ([0-9]+);/
+);
+assert.ok(nodePackedVersion, 'Node packed protocol version source changed');
+assert.equal(
+ Number(nodePackedVersion[1]) << 20 |
+ Number(nodePackedVersion[2]) << 10 |
+ Number(nodePackedVersion[3]),
+ packedVersion,
+ 'Node protocol version differs from iggy_binary_protocol'
+);
+
+console.log('Node VSR protocol mirror matches Rust sources');
diff --git a/foreign/node/src/bdd/raw.ts b/foreign/node/src/bdd/raw.ts
index 0d77864d0..30e9d057d 100644
--- a/foreign/node/src/bdd/raw.ts
+++ b/foreign/node/src/bdd/raw.ts
@@ -17,13 +17,18 @@
import assert from 'node:assert/strict';
import { Then, When } from '@cucumber/cucumber';
+import { BINARY_REQUEST_KIND } from '../wire/command-set.js';
import type { TestWorld } from './world.js';
When(
'I send a raw command with code {int} and an empty payload',
async function (this: TestWorld, code: number) {
try {
- this.rawResponse = await this.client.sendBinaryRequest(code, Buffer.alloc(0));
+ this.rawResponse = await this.client.sendBinaryRequest(
+ BINARY_REQUEST_KIND.NonReplicated,
+ code,
+ Buffer.alloc(0)
+ );
this.rawError = undefined;
} catch (error) {
this.rawResponse = undefined;
diff --git a/foreign/node/src/client/client.config.test.ts b/foreign/node/src/client/client.config.test.ts
new file mode 100644
index 000000000..4ad12aedc
--- /dev/null
+++ b/foreign/node/src/client/client.config.test.ts
@@ -0,0 +1,95 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { ClientConfig } from './client.type.js';
+import {
+ DEFAULT_MAX_RESPONSE_FRAME_SIZE,
+ normalizeClientConfig
+} from './client.config.js';
+
+const config = (): ClientConfig => ({
+ transport: 'TCP',
+ options: { host: '127.0.0.1', port: 8090 },
+ credentials: { username: 'iggy', password: 'iggy' }
+});
+
+describe('normalizeClientConfig', () => {
+ it('defaults to classic without changing classic pool sizing', () => {
+ const normalized = normalizeClientConfig({
+ ...config(),
+ poolSize: { min: 2, max: 4 }
+ });
+
+ assert.equal(normalized.protocol, 'classic');
+ assert.deepEqual(normalized.poolSize, { min: 2, max: 4 });
+ assert.equal(
+ normalized.maxResponseFrameSize,
+ DEFAULT_MAX_RESPONSE_FRAME_SIZE
+ );
+ });
+
+ it('restricts VSR to one pooled connection', () => {
+ const normalized = normalizeClientConfig({
+ ...config(),
+ protocol: 'vsr'
+ });
+ assert.deepEqual(normalized.poolSize, { min: 1, max: 1 });
+
+ assert.throws(
+ () => normalizeClientConfig({
+ ...config(),
+ protocol: 'vsr',
+ poolSize: { max: 2 }
+ }),
+ /exactly one pooled connection/
+ );
+ });
+
+ it('rejects invalid protocols before opening a socket', () => {
+ assert.throws(
+ () => normalizeClientConfig({
+ ...config(),
+ protocol: 'auto' as 'vsr'
+ }),
+ /unsupported wire protocol/
+ );
+ });
+
+ it('rejects VSR over an untested TLS transport', () => {
+ assert.throws(
+ () => normalizeClientConfig({
+ ...config(),
+ protocol: 'vsr',
+ transport: 'TLS'
+ }),
+ /TCP transport only/
+ );
+ });
+
+ it('rejects unsafe response frame limits', () => {
+ for (const maxResponseFrameSize of [0, 255, 1.5, Number.MAX_VALUE])
+ assert.throws(
+ () => normalizeClientConfig({
+ ...config(),
+ maxResponseFrameSize
+ }),
+ /maxResponseFrameSize/
+ );
+ });
+});
diff --git a/foreign/node/src/client/client.config.ts b/foreign/node/src/client/client.config.ts
new file mode 100644
index 000000000..001851e81
--- /dev/null
+++ b/foreign/node/src/client/client.config.ts
@@ -0,0 +1,56 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import type { ClientConfig, Protocol } from './client.type.js';
+
+export const DEFAULT_MAX_RESPONSE_FRAME_SIZE = 64 * 1024 * 1024;
+
+const isProtocol = (value: unknown): value is Protocol =>
+ value === 'classic' || value === 'vsr';
+
+export const normalizeClientConfig = (
+ config: ClientConfig
+): ClientConfig & { protocol: Protocol } => {
+ const protocol = config.protocol ?? 'classic';
+ if (!isProtocol(protocol))
+ throw new TypeError(`unsupported wire protocol: ${String(protocol)}`);
+
+ const maxResponseFrameSize =
+ config.maxResponseFrameSize ?? DEFAULT_MAX_RESPONSE_FRAME_SIZE;
+ if (!Number.isSafeInteger(maxResponseFrameSize) ||
+ maxResponseFrameSize < 256)
+ throw new TypeError(
+ 'maxResponseFrameSize must be a safe integer of at least 256 bytes'
+ );
+
+ if (protocol === 'vsr' && config.transport === 'TLS')
+ throw new TypeError('VSR framing currently supports the TCP transport only');
+
+ if (protocol === 'vsr' &&
+ ((config.poolSize?.min ?? 1) > 1 || (config.poolSize?.max ?? 1) > 1))
+ throw new TypeError(
+ 'VSR clients currently support exactly one pooled connection'
+ );
+
+ return {
+ ...config,
+ protocol,
+ options: { ...config.options },
+ maxResponseFrameSize,
+ ...(protocol === 'vsr' ? { poolSize: { min: 1, max: 1 } } : {})
+ };
+};
diff --git a/foreign/node/src/client/client.connection.ts b/foreign/node/src/client/client.connection.ts
index 277db2c7b..8efd0d8ec 100644
--- a/foreign/node/src/client/client.connection.ts
+++ b/foreign/node/src/client/client.connection.ts
@@ -23,6 +23,8 @@ import { connect as TLSConnect } from 'node:tls';
import type { ClientConfig, TlsOption, TcpOption, ReconnectOption } from "./client.type.js"
import { serializeCommand } from './client.utils.js';
import { debug } from './client.debug.js';
+import { DEFAULT_MAX_RESPONSE_FRAME_SIZE } from './client.config.js';
+import { extractResponseFrames } from './client.frame.js';
/**
@@ -113,6 +115,8 @@ export class IggyConnection extends EventEmitter {
private reconnectOption: ReconnectOption;
/** Number of reconnection attempts made */
private reconnectCount: number;
+ /** Shared promise for concurrent callers waiting on one connection attempt */
+ private connectPromise?: Promise<this>;
/** Buffer for incomplete response data */
private readBuffers: Buffer;
@@ -125,54 +129,86 @@ export class IggyConnection extends EventEmitter {
constructor(config: ClientConfig) {
super();
this.config = config;
- this.socket = getTransport(config);
this.connected = false;
this.connecting = false;
this.ending = false;
this.waitingResponseEnd = false;
this.reconnectOption = { ...DefaultReconnectOption, ...config.reconnect };
this.reconnectCount = 0;
+ this.connectPromise = undefined;
this.readBuffers = Buffer.allocUnsafe(0);
+ this.socket = this._installSocket(getTransport(config));
}
/**
- * Establishes the connection to the server.
- * Sets up event handlers for data, errors, and disconnection.
- *
- * @returns Promise that resolves when connected
+ * Attaches the lifecycle listeners exactly once per socket instance.
+ * Attaching them in `connect()` would stack duplicate handlers whenever a
+ * failed attempt is retried on the same socket.
*/
- connect() {
- this.connecting = true;
-
- this.socket.on('data', this._onData.bind(this));
+ private _installSocket(socket: Socket): Socket {
+ socket.on('data', this._onData.bind(this));
- this.socket.on('error', async (err: SocketError) => {
+ socket.on('error', (err: SocketError) => {
debug('socket/error event', err, err.code, this.ending);
- // errors about disconnections should be ignored during disconnect
if (this.ending && (err?.code === 'ECONNRESET' || err?.code === 'EPIPE'))
return
-
- this.reconnect(err);
+ this.emit('error', err);
});
- this.socket.once('end', async (hadError?: boolean) => {
- debug('socket/close#END event', hadError);
+ socket.once('close', (hadError?: boolean) => {
+ debug('socket/close event', hadError);
this.connected = false;
+ this.connecting = false;
+ this.connectPromise = undefined;
this.emit('disconnected', hadError);
- this.reconnect();
+ if (!this.ending)
+ void this.reconnect();
});
+ return socket;
+ }
+
+ /**
+ * Establishes the connection to the server.
+ *
+ * @returns Promise that resolves when connected
+ */
+ connect(): Promise<this> {
+ if (this.connected)
+ return Promise.resolve(this);
+ if (this.connectPromise)
+ return this.connectPromise;
+ // A reconnect is waiting out its backoff; the current socket is dead and
+ // waiting on it would never settle.
+ if (this.connecting)
+ return Promise.reject(
+ new Error('connection attempt already in progress')
+ );
+ if (this.socket.destroyed)
+ this.socket = this._installSocket(getTransport(this.config));
+ this.connecting = true;
- return new Promise((resolve /**, reject*/) => {
- this.socket.once('connect', () => {
+ this.connectPromise = new Promise<this>((resolve, reject) => {
+ const rejectConnect = (error: Error) => {
+ this.socket.removeListener('connect', resolveConnect);
+ this.connecting = false;
+ this.connectPromise = undefined;
+ reject(error);
+ };
+ const resolveConnect = () => {
+ this.socket.removeListener('error', rejectConnect);
debug('socket/connect event');
this.connected = true;
this.connecting = false;
this.reconnectCount = 0;
+ this.connectPromise = undefined;
this.emit('connect');
resolve(this);
- });
+ };
+ this.socket.once('error', rejectConnect);
+ this.socket.once('connect', resolveConnect);
});
+ return this.connectPromise;
}
/**
@@ -182,6 +218,9 @@ export class IggyConnection extends EventEmitter {
* @param err - Optional error that triggered the reconnection
*/
async reconnect(err?: Error) {
+ if (this.ending || this.connected || this.connecting)
+ return;
+
const { enabled, interval, maxRetries } = this.reconnectOption
debug(
'reconnect# event/reconnect?', {
@@ -191,7 +230,7 @@ export class IggyConnection extends EventEmitter {
}
);
- if (!enabled || this.reconnectCount > maxRetries) {
+ if (!enabled || this.reconnectCount >= maxRetries) {
debug(`reconnect reached maxRetries of ${maxRetries}`, err);
return this.emit(
'error',
@@ -204,8 +243,45 @@ export class IggyConnection extends EventEmitter {
/** recreate socket */
this.connecting = true;
this.reconnectCount += 1;
- this.socket = await recreate(this.config, interval);
- this.connect();
+ this.socket = this._installSocket(await recreate(this.config, interval));
+ this.connecting = false;
+ try {
+ await this.connect();
+ } catch (error) {
+ debug('reconnect attempt failed', error);
+ }
+ }
+
+ async redirect(host: string, port: number) {
+ this.socket.removeAllListeners();
+ this.socket.destroy();
+ this.connected = false;
+ this.connecting = false;
+ this.connectPromise = undefined;
+ this._endResponseWait();
+ // The old socket's close handler was just detached, so surface the drop
+ // to any in-flight exchange and queued work ourselves.
+ this.emit('disconnected', false);
+ this.config.options = { ...this.config.options, host, port };
+ this.socket = this._installSocket(getTransport(this.config));
+ await this.connect();
+ }
+
+ abort(): void {
+ this._endResponseWait();
+ this.socket.destroy();
+ }
+
+ isConnectedTo(host: string, port: number): boolean {
+ const target = normalizeHost(host);
+ if (this.socket.remotePort === port &&
+ normalizeHost(this.socket.remoteAddress) === target)
+ return true;
+ // A roster may advertise a DNS name while the socket reports a resolved
+ // address; falling back to the configured endpoint avoids a redirect to
+ // the peer the client is already connected to.
+ return this.config.options.port === port &&
+ normalizeHost(this.config.options.host) === target;
}
/**
@@ -239,47 +315,28 @@ export class IggyConnection extends EventEmitter {
this.waitingResponseEnd
);
- // Append new data to any buffered data
- if (this.waitingResponseEnd && this.readBuffers.length > 0) {
- data = Buffer.concat([this.readBuffers, data]);
- }
-
- // Keep processing while we have enough data
- let offset = 0;
-
- while (offset < data.length) {
- const remaining = data.length - offset;
-
- // Need at least 8 bytes for the header (4 bytes status + 4 bytes length)
- if (remaining < 8) {
- // Buffer the incomplete header and wait for more data
- this.waitingResponseEnd = true;
- this.readBuffers = data.subarray(offset);
- return;
- }
-
- // Read the header
- const responseSize = data.readUInt32LE(offset + 4);
- const totalSize = 8 + responseSize;
-
- // Check if we have the complete response (header + payload)
- if (remaining < totalSize) {
- // Buffer the incomplete response and wait for more data
- this.waitingResponseEnd = true;
- this.readBuffers = data.subarray(offset);
- return;
- }
-
- // We have a complete response, extract it and emit
- const response = data.subarray(offset, offset + totalSize);
- this.emit('response', response);
-
- // Move to the next response
- offset += totalSize;
+ const buffered = this.waitingResponseEnd && this.readBuffers.length > 0
+ ? Buffer.concat([this.readBuffers, data])
+ : data;
+
+ try {
+ const extracted = extractResponseFrames(
+ this.config.protocol ?? 'classic',
+ buffered,
+ this.config.maxResponseFrameSize ?? DEFAULT_MAX_RESPONSE_FRAME_SIZE
+ );
+ this.readBuffers = extracted.remainder;
+ this.waitingResponseEnd = extracted.remainder.length > 0;
+ for (const response of extracted.frames)
+ this.emit('response', response);
+ } catch (error) {
+ this._endResponseWait();
+ this.emit(
+ 'error',
+ error instanceof Error ? error : new Error(String(error))
+ );
+ this.socket.destroy();
}
-
- // All data processed, reset buffers
- this._endResponseWait();
}
/**
@@ -289,8 +346,19 @@ export class IggyConnection extends EventEmitter {
* @param payload - Command payload
* @returns True if the write was successful
*/
- writeCommand(command: number, payload: Buffer): boolean {
+ writeCommand(command: number, payload: Buffer): void {
const cmd = serializeCommand(command, payload);
- return this.socket.write(cmd);
+ this.socket.write(cmd);
+ }
+
+ writeFrame(frame: Buffer): void {
+ this.socket.write(frame);
}
}
+
+const normalizeHost = (host?: string): string => {
+ const normalized = (host ?? '').toLowerCase().replace(/^::ffff:/, '');
+ return normalized === 'localhost' || normalized === '::1'
+ ? '127.0.0.1'
+ : normalized;
+};
diff --git a/foreign/node/src/client/client.frame.test.ts b/foreign/node/src/client/client.frame.test.ts
new file mode 100644
index 000000000..1a3b6c65a
--- /dev/null
+++ b/foreign/node/src/client/client.frame.test.ts
@@ -0,0 +1,127 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import {
+ extractResponseFrames,
+ ProtocolFrameError
+} from './client.frame.js';
+import {
+ Command2,
+ HEADER_SIZE,
+ REPLY_OFFSET
+} from '../wire/vsr/header.js';
+
+const LIMIT = 1024;
+
+const classicFrame = (body: Buffer): Buffer => {
+ const frame = Buffer.alloc(8 + body.length);
+ frame.writeUInt32LE(body.length, 4);
+ body.copy(frame, 8);
+ return frame;
+};
+
+const vsrFrame = (body: Buffer): Buffer => {
+ const frame = Buffer.alloc(HEADER_SIZE + body.length);
+ frame.writeUInt32LE(frame.length, REPLY_OFFSET.size);
+ frame.writeUInt8(Command2.Reply, REPLY_OFFSET.command);
+ body.copy(frame, HEADER_SIZE);
+ return frame;
+};
+
+describe('extractResponseFrames', () => {
+ for (const protocol of ['classic', 'vsr'] as const) {
+ const makeFrame = protocol === 'classic' ? classicFrame : vsrFrame;
+
+ it(`buffers ${protocol} headers split at every boundary`, () => {
+ const frame = makeFrame(Buffer.from('payload'));
+ const headerSize = protocol === 'classic' ? 8 : HEADER_SIZE;
+
+ for (let split = 0; split < headerSize; split += 1) {
+ const first = extractResponseFrames(
+ protocol,
+ frame.subarray(0, split),
+ LIMIT
+ );
+ assert.equal(first.frames.length, 0);
+ const second = extractResponseFrames(
+ protocol,
+ Buffer.concat([first.remainder, frame.subarray(split)]),
+ LIMIT
+ );
+ assert.deepEqual(second.frames, [frame]);
+ assert.equal(second.remainder.length, 0);
+ }
+ });
+
+ it(`buffers a fragmented ${protocol} body`, () => {
+ const frame = makeFrame(Buffer.from('payload'));
+ const split = frame.length - 2;
+ const first = extractResponseFrames(
+ protocol,
+ frame.subarray(0, split),
+ LIMIT
+ );
+ assert.equal(first.frames.length, 0);
+ const second = extractResponseFrames(
+ protocol,
+ Buffer.concat([first.remainder, frame.subarray(split)]),
+ LIMIT
+ );
+ assert.deepEqual(second.frames, [frame]);
+ });
+
+ it(`extracts coalesced ${protocol} frames and a partial tail`, () => {
+ const first = makeFrame(Buffer.from('one'));
+ const second = makeFrame(Buffer.from('two'));
+ const third = makeFrame(Buffer.from('three'));
+ const input = Buffer.concat([first, second, third.subarray(0, 3)]);
+ const extracted = extractResponseFrames(protocol, input, LIMIT);
+
+ assert.deepEqual(extracted.frames, [first, second]);
+ assert.deepEqual(extracted.remainder, third.subarray(0, 3));
+ });
+ }
+
+ it('rejects a VSR size below the header', () => {
+ const frame = vsrFrame(Buffer.alloc(0));
+ frame.writeUInt32LE(0, REPLY_OFFSET.size);
+ assert.throws(
+ () => extractResponseFrames('vsr', frame, LIMIT),
+ ProtocolFrameError
+ );
+ });
+
+ it('rejects an oversized VSR frame before buffering its body', () => {
+ const header = vsrFrame(Buffer.alloc(0));
+ header.writeUInt32LE(LIMIT + 1, REPLY_OFFSET.size);
+ assert.throws(
+ () => extractResponseFrames('vsr', header, LIMIT),
+ ProtocolFrameError
+ );
+ });
+
+ it('rejects an oversized classic frame before buffering its body', () => {
+ const header = classicFrame(Buffer.alloc(0));
+ header.writeUInt32LE(LIMIT, 4);
+ assert.throws(
+ () => extractResponseFrames('classic', header, LIMIT),
+ ProtocolFrameError
+ );
+ });
+});
diff --git a/foreign/node/src/client/client.frame.ts b/foreign/node/src/client/client.frame.ts
new file mode 100644
index 000000000..c12e82a35
--- /dev/null
+++ b/foreign/node/src/client/client.frame.ts
@@ -0,0 +1,77 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import type { Protocol } from './client.type.js';
+import {
+ HEADER_SIZE as VSR_HEADER_SIZE,
+ readSize as readVsrSize
+} from '../wire/vsr/header.js';
+
+const CLASSIC_HEADER_SIZE = 8;
+
+export class ProtocolFrameError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'ProtocolFrameError';
+ }
+}
+
+export type ExtractedFrames = {
+ frames: Buffer[],
+ remainder: Buffer
+};
+
+export const extractResponseFrames = (
+ protocol: Protocol,
+ buffer: Buffer,
+ maximumFrameSize: number
+): ExtractedFrames => {
+ const headerSize =
+ protocol === 'vsr' ? VSR_HEADER_SIZE : CLASSIC_HEADER_SIZE;
+ const frames: Buffer[] = [];
+ let offset = 0;
+
+ while (buffer.length - offset >= headerSize) {
+ const available = buffer.length - offset;
+ const declaredSize = protocol === 'vsr'
+ ? readVsrSize(buffer.subarray(offset, offset + headerSize))
+ : CLASSIC_HEADER_SIZE + buffer.readUInt32LE(offset + 4);
+
+ if (declaredSize < headerSize)
+ throw new ProtocolFrameError(
+ `declared ${protocol} frame size ${declaredSize} is below header size`
+ );
+ if (!Number.isSafeInteger(declaredSize) ||
+ declaredSize > maximumFrameSize)
+ throw new ProtocolFrameError(
+ `declared ${protocol} frame size ${declaredSize} exceeds ` +
+ `the ${maximumFrameSize} byte limit`
+ );
+ if (available < declaredSize)
+ break;
+
+ frames.push(buffer.subarray(offset, offset + declaredSize));
+ offset += declaredSize;
+ }
+
+ return {
+ frames,
+ remainder: offset === buffer.length
+ ? Buffer.alloc(0)
+ : Buffer.from(buffer.subarray(offset))
+ };
+};
diff --git a/foreign/node/src/client/client.socket.test.ts b/foreign/node/src/client/client.socket.test.ts
new file mode 100644
index 000000000..47b141049
--- /dev/null
+++ b/foreign/node/src/client/client.socket.test.ts
@@ -0,0 +1,387 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+import assert from 'node:assert/strict';
+import { once } from 'node:events';
+import type { AddressInfo, Socket } from 'node:net';
+import { createServer, type Server } from 'node:net';
+import { describe, it } from 'node:test';
+import { COMMAND_CODE } from '../wire/command.code.js';
+import { BINARY_REQUEST_KIND } from '../wire/command-set.js';
+import { ResponseError } from '../wire/error.utils.js';
+import {
+ Command2,
+ EVICTION_OFFSET,
+ EvictionReason,
+ HEADER_SIZE,
+ REPLY_OFFSET,
+ REQUEST_OFFSET
+} from '../wire/vsr/header.js';
+import { Operation } from '../wire/vsr/operation.js';
+import { CommandResponseStream } from './client.socket.js';
+import type { ClientConfig } from './client.type.js';
+
+const TEST_SESSION = 42n;
+
+type FrameHandler = (frame: Buffer, socket: Socket) => void;
+
+type VsrTestServer = {
+ port: number,
+ frames: Buffer[],
+ close: () => Promise<void>
+};
+
+/** Loopback server speaking just enough VSR framing for the client tests. */
+const startVsrServer = async (
+ handler: FrameHandler
+): Promise<VsrTestServer> => {
+ const frames: Buffer[] = [];
+ const server: Server = createServer((socket) => {
+ let pending = Buffer.alloc(0);
+ socket.on('data', (data: Buffer) => {
+ pending = Buffer.concat([pending, data]);
+ while (pending.length >= HEADER_SIZE) {
+ const size = pending.readUInt32LE(REQUEST_OFFSET.size);
+ if (pending.length < size) break;
+ const frame = pending.subarray(0, size);
+ pending = pending.subarray(size);
+ frames.push(Buffer.from(frame));
+ handler(Buffer.from(frame), socket);
+ }
+ });
+ socket.on('error', () => {});
+ });
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ return {
+ port: (server.address() as AddressInfo).port,
+ frames,
+ close: () => new Promise((resolve) => server.close(() => resolve()))
+ };
+};
+
+const replyFrame = (
+ operation: number,
+ body: Buffer = Buffer.alloc(0),
+ status = 0
+): Buffer => {
+ const frame = Buffer.alloc(HEADER_SIZE + body.length);
+ frame.writeUInt32LE(frame.length, REPLY_OFFSET.size);
+ frame.writeUInt8(Command2.Reply, REPLY_OFFSET.command);
+ frame.writeUInt8(operation, REPLY_OFFSET.operation);
+ frame.writeUInt32LE(status, REPLY_OFFSET.status);
+ body.copy(frame, HEADER_SIZE);
+ return frame;
+};
+
+const evictionFrame = (reason: number): Buffer => {
+ const frame = Buffer.alloc(HEADER_SIZE);
+ frame.writeUInt32LE(HEADER_SIZE, REPLY_OFFSET.size);
+ frame.writeUInt8(Command2.Eviction, REPLY_OFFSET.command);
+ frame.writeUInt8(reason, EVICTION_OFFSET.reason);
+ return frame;
+};
+
+const registerReplyBody = (): Buffer => {
+ const serverVersion = Buffer.from('0.0.0');
+ const body = Buffer.alloc(4 + 17 + serverVersion.length);
+ body.writeUInt32LE(0, 0);
+ body.writeUInt32LE(7, 4);
+ body.writeBigUInt64LE(TEST_SESSION, 8);
+ body.writeUInt32LE(0, 16);
+ body.writeUInt8(serverVersion.length, 20);
+ serverVersion.copy(body, 21);
+ return body;
+};
+
+const singleNodeMetadataBody = (port: number): Buffer => {
+ const name = Buffer.from('single-node');
+ const nodeName = Buffer.from('iggy-node');
+ const ip = Buffer.from('127.0.0.1');
+ const body = Buffer.alloc(
+ 4 + name.length + 4 + 4 + nodeName.length + 4 + ip.length + 8 + 2
+ );
+ let offset = 0;
+ body.writeUInt32LE(name.length, offset); offset += 4;
+ name.copy(body, offset); offset += name.length;
+ body.writeUInt32LE(1, offset); offset += 4;
+ body.writeUInt32LE(nodeName.length, offset); offset += 4;
+ nodeName.copy(body, offset); offset += nodeName.length;
+ body.writeUInt32LE(ip.length, offset); offset += 4;
+ ip.copy(body, offset); offset += ip.length;
+ body.writeUInt16LE(port, offset); offset += 8;
+ body.writeUInt8(0, offset); offset += 1;
+ body.writeUInt8(0, offset);
+ return body;
+};
+
+const twoNodeMetadataBody = (
+ followerPort: number,
+ leaderPort: number
+): Buffer => {
+ const node = (nodeName: Buffer, port: number, role: number): Buffer => {
+ const ip = Buffer.from('127.0.0.1');
+ const encoded = Buffer.alloc(4 + nodeName.length + 4 + ip.length + 8 + 2);
+ let offset = 0;
+ encoded.writeUInt32LE(nodeName.length, offset); offset += 4;
+ nodeName.copy(encoded, offset); offset += nodeName.length;
+ encoded.writeUInt32LE(ip.length, offset); offset += 4;
+ ip.copy(encoded, offset); offset += ip.length;
+ encoded.writeUInt16LE(port, offset); offset += 8;
+ encoded.writeUInt8(role, offset); offset += 1;
+ encoded.writeUInt8(0, offset);
+ return encoded;
+ };
+ const name = Buffer.from('iggy-cluster');
+ const header = Buffer.alloc(4 + name.length + 4);
+ header.writeUInt32LE(name.length, 0);
+ name.copy(header, 4);
+ header.writeUInt32LE(2, 4 + name.length);
+ return Buffer.concat([
+ header,
+ node(Buffer.from('iggy-node-1'), leaderPort, 0),
+ node(Buffer.from('iggy-node-2'), followerPort, 1)
+ ]);
+};
+
+/** Register, metadata, and echo behavior of a healthy single VSR node. */
+const singleNodeHandler = (port: number): FrameHandler =>
+ (frame, socket) => {
+ const operation = frame.readUInt8(REQUEST_OFFSET.operation);
+ if (operation === Operation.Register) {
+ socket.write(replyFrame(Operation.Register, registerReplyBody()));
+ return;
+ }
+ const code = frame.readUInt32LE(REQUEST_OFFSET.reserved);
+ if (code === COMMAND_CODE.GetClusterMetadata) {
+ socket.write(
+ replyFrame(Operation.NonReplicated, singleNodeMetadataBody(port))
+ );
+ return;
+ }
+ socket.write(replyFrame(operation));
+ };
+
+const vsrConfig = (port: number): ClientConfig => ({
+ protocol: 'vsr',
+ transport: 'TCP',
+ options: { host: '127.0.0.1', port },
+ credentials: { username: 'iggy', password: 'iggy' },
+ reconnect: { enabled: false, interval: 100, maxRetries: 1 }
+});
+
+describe('VSR client socket', () => {
+ it('registers one session before the first authenticated command', async () => {
+ const server = await startVsrServer(
+ (frame, socket) => singleNodeHandler(server.port)(frame, socket)
+ );
+ const client = new CommandResponseStream(vsrConfig(server.port));
+ try {
+ const response = await client.sendCommand(
+ 60_001,
+ Buffer.from('opaque'),
+ { rawKind: BINARY_REQUEST_KIND.NonReplicated }
+ );
+ assert.equal(response.status, 0);
+
+ const operations = server.frames.map(
+ (frame) => frame.readUInt8(REQUEST_OFFSET.operation)
+ );
+ assert.deepEqual(operations, [
+ Operation.NonReplicated,
+ Operation.Register,
+ Operation.NonReplicated
+ ]);
+ const register = server.frames[1];
+ assert.equal(register.readBigUInt64LE(REQUEST_OFFSET.request), 0n);
+ assert.equal(register.readBigUInt64LE(REQUEST_OFFSET.session), 0n);
+ const request = server.frames[2];
+ assert.equal(
+ request.readBigUInt64LE(REQUEST_OFFSET.session),
+ TEST_SESSION
+ );
+ assert.equal(request.readUInt32LE(REQUEST_OFFSET.reserved), 60_001);
+ assert.equal(client.isAuthenticated, true);
+ assert.equal(client.userId, 7);
+ } finally {
+ client.destroy();
+ await server.close();
+ }
+ });
+
+ it('replays the identical frame on a transient response', async () => {
+ let attempts = 0;
+ const server = await startVsrServer((frame, socket) => {
+ const operation = frame.readUInt8(REQUEST_OFFSET.operation);
+ if (operation !== Operation.NonReplicated ||
+ frame.readUInt32LE(REQUEST_OFFSET.reserved) !== 60_002)
+ return singleNodeHandler(server.port)(frame, socket);
+ attempts += 1;
+ socket.write(
+ attempts === 1
+ ? replyFrame(operation, Buffer.alloc(0), 57)
+ : replyFrame(operation, Buffer.from('done'))
+ );
+ });
+ const client = new CommandResponseStream(vsrConfig(server.port));
+ try {
+ const response = await client.sendCommand(
+ 60_002,
+ Buffer.from('retry-me'),
+ { rawKind: BINARY_REQUEST_KIND.NonReplicated }
+ );
+ assert.equal(attempts, 2);
+ assert.deepEqual(response.data, Buffer.from('done'));
+ const sent = server.frames.filter(
+ (frame) => frame.readUInt32LE(REQUEST_OFFSET.reserved) === 60_002
+ );
+ assert.equal(sent.length, 2);
+ assert.deepEqual(sent[0], sent[1]);
+ } finally {
+ client.destroy();
+ await server.close();
+ }
+ });
+
+ it('resets the session and surfaces a typed error on eviction', async () => {
+ const server = await startVsrServer((frame, socket) => {
+ if (frame.readUInt32LE(REQUEST_OFFSET.reserved) === 60_003) {
+ socket.write(evictionFrame(EvictionReason.NoSession));
+ return;
+ }
+ singleNodeHandler(server.port)(frame, socket);
+ });
+ const client = new CommandResponseStream(vsrConfig(server.port));
+ try {
+ let sessionResets = 0;
+ client.on('sessionReset', () => { sessionResets += 1; });
+ await assert.rejects(
+ () => client.sendCommand(
+ 60_003,
+ Buffer.alloc(0),
+ { rawKind: BINARY_REQUEST_KIND.NonReplicated }
+ ),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 40
+ );
+ assert.ok(sessionResets >= 1);
+ assert.equal(client.isAuthenticated, false);
+ } finally {
+ client.destroy();
+ await server.close();
+ }
+ });
+
+ it('fails an in-flight request when the connection drops', async () => {
+ const server = await startVsrServer((frame, socket) => {
+ if (frame.readUInt32LE(REQUEST_OFFSET.reserved) === 60_004) {
+ socket.destroy();
+ return;
+ }
+ singleNodeHandler(server.port)(frame, socket);
+ });
+ const client = new CommandResponseStream(vsrConfig(server.port));
+ try {
+ await assert.rejects(
+ () => client.sendCommand(
+ 60_004,
+ Buffer.alloc(0),
+ { rawKind: BINARY_REQUEST_KIND.NonReplicated }
+ )
+ );
+ assert.equal(client.isAuthenticated, false);
+ } finally {
+ client.destroy();
+ await server.close();
+ }
+ });
+
+ it('redirects to the advertised leader before registering', async () => {
+ const leader = await startVsrServer(
+ (frame, socket) => singleNodeHandler(leader.port)(frame, socket)
+ );
+ const follower = await startVsrServer((frame, socket) => {
+ const code = frame.readUInt32LE(REQUEST_OFFSET.reserved);
+ if (code === COMMAND_CODE.GetClusterMetadata) {
+ socket.write(replyFrame(
+ Operation.NonReplicated,
+ twoNodeMetadataBody(follower.port, leader.port)
+ ));
+ return;
+ }
+ socket.write(replyFrame(
+ frame.readUInt8(REQUEST_OFFSET.operation),
+ Buffer.alloc(0),
+ 3
+ ));
+ });
+ const client = new CommandResponseStream(vsrConfig(follower.port));
+ try {
+ const response = await client.sendCommand(
+ 60_005,
+ Buffer.alloc(0),
+ { rawKind: BINARY_REQUEST_KIND.NonReplicated }
+ );
+ assert.equal(response.status, 0);
+ const followerOperations = follower.frames.map(
+ (frame) => frame.readUInt8(REQUEST_OFFSET.operation)
+ );
+ assert.deepEqual(followerOperations, [Operation.NonReplicated]);
+ const leaderOperations = leader.frames.map(
+ (frame) => frame.readUInt8(REQUEST_OFFSET.operation)
+ );
+ assert.ok(leaderOperations.includes(Operation.Register));
+ assert.equal(
+ leader.frames.at(-1)?.readUInt32LE(REQUEST_OFFSET.reserved),
+ 60_005
+ );
+ } finally {
+ client.destroy();
+ await leader.close();
+ await follower.close();
+ }
+ });
+
+ it('rejects instead of hanging while a connection attempt is unresolved', async () => {
+ const server = await startVsrServer(() => {});
+ const port = server.port;
+ await server.close();
+ const client = new CommandResponseStream({
+ ...vsrConfig(port),
+ reconnect: { enabled: true, interval: 300, maxRetries: 1 }
+ });
+ try {
+ await assert.rejects(
+ () => client.sendCommand(
+ 60_006,
+ Buffer.alloc(0),
+ { rawKind: BINARY_REQUEST_KIND.NonReplicated }
+ )
+ );
+ await assert.rejects(
+ () => client.sendCommand(
+ 60_006,
+ Buffer.alloc(0),
+ { rawKind: BINARY_REQUEST_KIND.NonReplicated }
+ )
+ );
+ } finally {
+ client.destroy();
+ }
+ });
+});
diff --git a/foreign/node/src/client/client.socket.ts b/foreign/node/src/client/client.socket.ts
index 0fbe6f514..17842673e 100644
--- a/foreign/node/src/client/client.socket.ts
+++ b/foreign/node/src/client/client.socket.ts
@@ -20,14 +20,30 @@ import { EventEmitter } from 'node:events';
import type {
ClientConfig,
ClientCredentials, CommandResponse,
- PasswordCredentials, RawClient, TokenCredentials
+ PasswordCredentials, Protocol, RawClient, SendCommandOptions,
+ TokenCredentials
} from '../client/client.type.js';
+import type { BinaryRequestKind } from '../wire/command-set.js';
import { handleResponse } from './client.utils.js';
-import { responseError } from '../wire/error.utils.js';
+import { ResponseError, responseError } from '../wire/error.utils.js';
import { debug } from './client.debug.js';
import { IggyConnection } from './client.connection.js';
-import { LOGIN, LOGIN_WITH_TOKEN, PING } from '../wire/index.js';
+import { LOGIN, LOGIN_WITH_TOKEN, LOGOUT, PING } from '../wire/index.js';
+import { GET_CLUSTER_METADATA } from '../wire/cluster/get-cluster-metadata.command.js';
+import { COMMAND_CODE } from '../wire/command.code.js';
+import {
+ decodeVsrResponse,
+ prepareVsrCommand,
+ readRegisteredSession,
+ VsrEvictionError,
+ VsrSession,
+} from '../wire/vsr/index.js';
+import { normalizeClientConfig } from './client.config.js';
+const VSR_RESPONSE_TIMEOUT_MS = 30_000;
+const VSR_RETRY_INTERVAL_MS = 50;
+const TRANSIENT_NOT_COMMITTED = 57;
+const TRANSIENT_NOT_ACCEPTED = 58;
/**
* Command codes that can be executed without authentication.
@@ -46,6 +62,10 @@ type Job = {
command: number,
/** Command payload */
payload: Buffer,
+ /** Whether to parse the response */
+ handleResponse: boolean,
+ /** Execution model declared by a raw request */
+ kind?: BinaryRequestKind,
/** Promise resolve function */
resolve: (v: CommandResponse | PromiseLike<CommandResponse>) => void,
/** Promise reject function */
@@ -58,12 +78,20 @@ type Job = {
* Implements command queuing, authentication, and heartbeat functionality.
*/
export class CommandResponseStream extends EventEmitter {
+ /** Server wire protocol used by this connection */
+ readonly protocol: Protocol;
/** Client configuration */
private options: ClientConfig;
/** Underlying connection to the server */
private connection: IggyConnection;
/** Queue of pending command jobs */
private _execQueue: Job[];
+ /** Consensus session used by VSR framing */
+ private vsrSession: VsrSession;
+ /** Shared authentication attempt for concurrent callers */
+ private authenticationPromise?: Promise<boolean>;
+ /** Calls that have acquired this stream but have not fully settled */
+ private pendingSubmissions: number;
/** Whether the stream is currently processing a command */
public busy: boolean;
/** Whether the client has been authenticated */
@@ -80,11 +108,16 @@ export class CommandResponseStream extends EventEmitter {
*/
constructor(options: ClientConfig) {
super();
- this.options = options;
- this.connection = new IggyConnection(options);
+ const normalized = normalizeClientConfig(options);
+ this.options = normalized;
+ this.protocol = normalized.protocol;
+ this.connection = new IggyConnection(normalized);
this.busy = false;
this.isAuthenticated = false;
this._execQueue = [];
+ this.vsrSession = new VsrSession();
+ this.authenticationPromise = undefined;
+ this.pendingSubmissions = 0;
this._init();
};
@@ -93,8 +126,17 @@ export class CommandResponseStream extends EventEmitter {
*/
_init() {
this.heartbeat(this.options.heartbeatInterval);
- this.connection.on('disconnected', async () => {
+ this.connection.on('error', (error: Error) => {
+ this._failQueue(error);
+ });
+ this.connection.on('disconnected', () => {
this.isAuthenticated = false;
+ this.userId = undefined;
+ this.vsrSession.reset();
+ this.emit('sessionReset');
+ this._failQueue(
+ new Error('connection closed before queued commands were sent')
+ );
});
}
@@ -104,54 +146,88 @@ export class CommandResponseStream extends EventEmitter {
*
* @param command - Command code to send
* @param payload - Command payload buffer
- * @param handleResponse - Whether to parse the response (default: true)
- * @param last - Whether to add to end of queue (default: true)
+ * @param options - Response, queue, and raw-request options
* @returns Promise resolving to the command response
*/
async sendCommand(
command: number,
payload: Buffer,
- handleResponse = true,
- last = true
+ options: SendCommandOptions = {}
): Promise<CommandResponse> {
+ this.pendingSubmissions += 1;
+ try {
+ const {
+ handleResponse = true,
+ last = true,
+ rawKind
+ } = options;
- if (!this.connection.connected)
- await this.connection.connect()
+ if (!this.connection.connected)
+ await this.connection.connect()
- if (!this.isAuthenticated && !UNLOGGED_COMMAND_CODE.includes(command))
- await this.authenticate(this.options.credentials);
+ if (this.options.protocol === 'vsr' &&
+ isLoginCommand(command) &&
+ this.isAuthenticated)
+ await this.sendCommand(
+ LOGOUT.code,
+ LOGOUT.serialize(),
+ { last: false }
+ );
- return new Promise((resolve, reject) => {
- if (last)
- this._execQueue.push({ command, payload, resolve, reject });
- else
- this._execQueue.unshift({ command, payload, resolve, reject });
- this._processQueue(handleResponse);
- });
+ if (!this.isAuthenticated && !this.isUnloggedCommand(command))
+ await this.authenticate(this.options.credentials);
+
+ return await new Promise((resolve, reject) => {
+ const job = {
+ command,
+ payload,
+ handleResponse,
+ kind: rawKind,
+ resolve,
+ reject
+ };
+ if (last)
+ this._execQueue.push(job);
+ else
+ this._execQueue.unshift(job);
+ this._processQueue();
+ });
+ } finally {
+ this.pendingSubmissions -= 1;
+ this._emitFinishQueue();
+ }
}
/**
* Processes queued commands sequentially.
* Emits 'finishQueue' when all commands are processed.
*
- * @param handleResponse - Whether to parse responses
*/
- async _processQueue(handleResponse = true): Promise<void> {
+ async _processQueue(): Promise<void> {
if (this.busy)
return;
this.busy = true;
while (this._execQueue.length > 0 && this.connection.socket.writable) {
const next = this._execQueue.shift();
if (!next) break;
- const { command, payload, resolve, reject } = next;
+ const { command, payload, handleResponse, kind, resolve, reject } = next;
try {
- resolve(await this._processNext(command, payload, handleResponse));
+ resolve(await this._processNext(command, payload, handleResponse, kind));
} catch (err) {
reject(err);
}
}
+ if (this._execQueue.length > 0)
+ this._failQueue(new Error('connection is not writable'));
this.busy = false;
- this.emit('finishQueue');
+ this._emitFinishQueue();
+ }
+
+ private _emitFinishQueue(): void {
+ if (this.pendingSubmissions === 0 &&
+ !this.busy &&
+ this._execQueue.length === 0)
+ this.emit('finishQueue');
}
/**
@@ -165,27 +241,185 @@ export class CommandResponseStream extends EventEmitter {
_processNext(
command: number,
payload: Buffer,
- handleResp = true
+ handleResp = true,
+ kind?: BinaryRequestKind
): Promise<CommandResponse> {
- const lastWrite = this.connection.writeCommand(command, payload);
- debug('==> writeCommand', lastWrite);
- return new Promise((resolve, reject) => {
- if (!lastWrite)
- return reject(new Error('failed to write to socket'));
- const errCb = (err: unknown) => reject(err);
- this.connection.once('error', errCb);
- this.connection.once('response', (resp) => {
- this.connection.removeListener('error', errCb);
- if (!handleResp) return resolve(resp);
- const r = handleResponse(resp);
- if (r.status !== 0) {
- return reject(responseError(command, r.status));
+ if (this.options.protocol !== 'vsr')
+ return this._processClassic(command, payload, handleResp);
+ return this._processVsr(command, payload, handleResp, kind);
+ }
+
+ private async _processClassic(
+ command: number,
+ payload: Buffer,
+ handleResp: boolean
+ ): Promise<CommandResponse> {
+ const response = await this._exchange(
+ () => this.connection.writeCommand(command, payload)
+ );
+ if (!handleResp)
+ return response as unknown as CommandResponse;
+ const parsed = handleResponse(response);
+ if (parsed.status !== 0)
+ throw responseError(command, parsed.status);
+ return parsed;
+ }
+
+ private async _processVsr(
+ command: number,
+ payload: Buffer,
+ handleResp: boolean,
+ kind?: BinaryRequestKind
+ ): Promise<CommandResponse> {
+ try {
+ const prepared = prepareVsrCommand(command, payload);
+ // A transient retry must preserve all request identity fields.
+ const frame = this.vsrSession.encode(
+ prepared.command,
+ prepared.payload,
+ kind
+ );
+ const deadline = Date.now() + VSR_RESPONSE_TIMEOUT_MS;
+ let parsed: CommandResponse;
+ while (true) {
+ const remaining = deadline - Date.now();
+ if (remaining <= 0)
+ throw new Error(
+ `timed out after ${VSR_RESPONSE_TIMEOUT_MS} ms ` +
+ 'waiting for VSR response'
+ );
+ const response = await this._exchange(
+ () => this.connection.writeFrame(frame),
+ remaining
+ );
+ if (!handleResp)
+ return response as unknown as CommandResponse;
+ try {
+ parsed = decodeVsrResponse(response);
+ break;
+ } catch (error) {
+ if (!(error instanceof ResponseError) ||
+ !isTransientVsrError(error.errorCode))
+ throw error;
+ const retryDelay = Math.min(
+ VSR_RETRY_INTERVAL_MS,
+ Math.max(0, deadline - Date.now())
+ );
+ if (retryDelay === 0)
+ throw error;
+ await delay(retryDelay);
}
- return resolve(r);
- });
+ }
+
+ if (prepared.command === COMMAND_CODE.LoginRegister ||
+ prepared.command === COMMAND_CODE.LoginRegisterWithAccessToken) {
+ this.vsrSession.bind(readRegisteredSession(parsed));
+ this.isAuthenticated = true;
+ this.userId = parsed.data.readUInt32LE(0);
+ }
+ if (prepared.command === COMMAND_CODE.LogoutUser) {
+ this.isAuthenticated = false;
+ this.userId = undefined;
+ this.vsrSession.reset();
+ this.emit('sessionReset');
+ }
+ return parsed;
+ } catch (error) {
+ if (error instanceof VsrEvictionError) {
+ this.isAuthenticated = false;
+ this.userId = undefined;
+ this.vsrSession.reset();
+ this.emit('sessionReset');
+ } else if (!(error instanceof ResponseError)) {
+ // A local failure after encoding may have consumed a request ID
+ // without a server verdict; keeping the session would leave a
+ // request-ID gap the primary silently drops. Register afresh instead
+ // of replaying an ambiguous request under the old session.
+ this.isAuthenticated = false;
+ this.userId = undefined;
+ this.vsrSession.reset();
+ this.emit('sessionReset');
+ }
+ if (error instanceof ResponseError)
+ throw responseError(command, error.errorCode);
+ throw error;
+ }
+ }
+
+ private _exchange(write: () => void, timeout?: number): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ let timeoutHandler: NodeJS.Timeout | undefined;
+ const cleanup = () => {
+ if (timeoutHandler)
+ clearTimeout(timeoutHandler);
+ this.connection.removeListener('error', errorCallback);
+ this.connection.removeListener('disconnected', disconnectedCallback);
+ this.connection.removeListener('response', responseCallback);
+ };
+ const errorCallback = (error: unknown) => {
+ cleanup();
+ reject(error);
+ };
+ const disconnectedCallback = () => {
+ cleanup();
+ reject(new Error('connection closed while waiting for response'));
+ };
+ const responseCallback = (response: Buffer) => {
+ cleanup();
+ resolve(response);
+ };
+ if (timeout !== undefined) {
+ timeoutHandler = setTimeout(() => {
+ cleanup();
+ this.connection.abort();
+ reject(new Error(`timed out after ${timeout} ms waiting for VSR response`));
+ }, timeout);
+ }
+ this.connection.once('error', errorCallback);
+ this.connection.once('disconnected', disconnectedCallback);
+ this.connection.once('response', responseCallback);
+ try {
+ write();
+ } catch (error) {
+ cleanup();
+ reject(error);
+ }
});
}
+ private isUnloggedCommand(command: number): boolean {
+ return UNLOGGED_COMMAND_CODE.includes(command) ||
+ (this.options.protocol === 'vsr' &&
+ command === COMMAND_CODE.GetClusterMetadata);
+ }
+
+ private async _ensureVsrLeader(): Promise<void> {
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ // Queue the metadata fetch instead of writing directly: a bare write
+ // would race an in-flight exchange and both would wake on the same
+ // response event.
+ const response = await this.sendCommand(
+ GET_CLUSTER_METADATA.code,
+ GET_CLUSTER_METADATA.serialize(),
+ { last: false }
+ );
+ const metadata = GET_CLUSTER_METADATA.deserialize(response);
+ if (metadata.nodes.length <= 1)
+ return;
+ const leader = metadata.nodes.find(
+ (node) => node.role === 'Leader' && node.status === 'Healthy'
+ );
+ if (!leader) {
+ await delay(100);
+ continue;
+ }
+ if (!this.connection.isConnectedTo(leader.ip, leader.endpoints.tcp))
+ await this.connection.redirect(leader.ip, leader.endpoints.tcp);
+ return;
+ }
+ throw new Error('VSR cluster has no healthy leader');
+ }
+
/**
* Fails all queued commands with the given error.
*
@@ -202,7 +436,23 @@ export class CommandResponseStream extends EventEmitter {
* @param creds - Authentication credentials (token or password)
* @returns True if authentication succeeded
*/
- async authenticate(creds: ClientCredentials) {
+ async authenticate(creds: ClientCredentials): Promise<boolean> {
+ if (this.isAuthenticated)
+ return true;
+ if (this.authenticationPromise)
+ return this.authenticationPromise;
+
+ this.authenticationPromise = this._authenticate(creds);
+ try {
+ return await this.authenticationPromise;
+ } finally {
+ this.authenticationPromise = undefined;
+ }
+ }
+
+ private async _authenticate(creds: ClientCredentials): Promise<boolean> {
+ if (this.options.protocol === 'vsr')
+ await this._ensureVsrLeader();
const r = ('token' in creds) ?
await this._authWithToken(creds) :
await this._authWithPassword(creds);
@@ -219,7 +469,7 @@ export class CommandResponseStream extends EventEmitter {
*/
async _authWithPassword(creds: PasswordCredentials) {
const pl = LOGIN.serialize(creds);
- const logr = await this.sendCommand(LOGIN.code, pl, true, false);
+ const logr = await this.sendCommand(LOGIN.code, pl, { last: false });
return LOGIN.deserialize(logr);
}
@@ -231,7 +481,11 @@ export class CommandResponseStream extends EventEmitter {
*/
async _authWithToken(creds: TokenCredentials) {
const pl = LOGIN_WITH_TOKEN.serialize(creds);
- const logr = await this.sendCommand(LOGIN_WITH_TOKEN.code, pl, true, false);
+ const logr = await this.sendCommand(
+ LOGIN_WITH_TOKEN.code,
+ pl,
+ { last: false }
+ );
return LOGIN_WITH_TOKEN.deserialize(logr);
}
@@ -242,7 +496,7 @@ export class CommandResponseStream extends EventEmitter {
*/
async ping() {
const pl = PING.serialize();
- const pingR = await this.sendCommand(PING.code, pl, true);
+ const pingR = await this.sendCommand(PING.code, pl);
return PING.deserialize(pingR);
}
@@ -258,7 +512,11 @@ export class CommandResponseStream extends EventEmitter {
this.heartbeatIntervalHandler = setInterval(async () => {
if (this.connection.connected) {
debug(`sending heartbeat ping (interval: ${interval} ms)`);
- await this.ping()
+ try {
+ await this.ping()
+ } catch (error) {
+ debug('heartbeat ping failed', error);
+ }
}
}, interval);
}
@@ -293,3 +551,14 @@ export class CommandResponseStream extends EventEmitter {
export function getRawClient(options: ClientConfig): RawClient {
return new CommandResponseStream(options);
}
+
+const isLoginCommand = (command: number): boolean =>
+ command === COMMAND_CODE.LoginUser ||
+ command === COMMAND_CODE.LoginWithAccessToken;
+
+const delay = (milliseconds: number): Promise<void> =>
+ new Promise((resolve) => setTimeout(resolve, milliseconds));
+
+const isTransientVsrError = (errorCode: number): boolean =>
+ errorCode === TRANSIENT_NOT_COMMITTED ||
+ errorCode === TRANSIENT_NOT_ACCEPTED;
diff --git a/foreign/node/src/client/client.ts b/foreign/node/src/client/client.ts
index fbcbab378..b67640a45 100644
--- a/foreign/node/src/client/client.ts
+++ b/foreign/node/src/client/client.ts
@@ -21,6 +21,7 @@ import type { RawClient, ClientConfig } from "./client.type.js"
import { getRawClient } from '../client/client.socket.js';
import { CommandAPI } from '../wire/command-set.js';
import { debug } from './client.debug.js';
+import { normalizeClientConfig } from './client.config.js';
/**
@@ -79,9 +80,10 @@ export class Client extends CommandAPI {
* @param config - Client configuration
*/
constructor(config: ClientConfig) {
- const pcp = poolClientProvider(config);
+ const normalized = normalizeClientConfig(config);
+ const pcp = poolClientProvider(normalized);
super(pcp);
- this._config = config;
+ this._config = normalized;
this._pool = pcp._pool;
};
@@ -123,8 +125,9 @@ export class SingleClient extends CommandAPI {
* @param config - Client configuration
*/
constructor(config: ClientConfig) {
- super(singleClientProvider(config));
- this._config = config;
+ const normalized = normalizeClientConfig(config);
+ super(singleClientProvider(normalized));
+ this._config = normalized;
}
/**
@@ -169,6 +172,6 @@ export class SimpleClient extends CommandAPI {
* @returns SimpleClient instance
*/
export const getClient = async (config: ClientConfig) => {
- const cli = getRawClient(config);
+ const cli = getRawClient(normalizeClientConfig(config));
return new SimpleClient(cli);
};
diff --git a/foreign/node/src/client/client.type.ts b/foreign/node/src/client/client.type.ts
index 325787a79..c3da1e82e 100644
--- a/foreign/node/src/client/client.type.ts
+++ b/foreign/node/src/client/client.type.ts
@@ -19,6 +19,7 @@
import type { Readable } from 'stream';
import { type TcpSocketConnectOpts } from 'node:net';
import { type ConnectionOptions } from 'node:tls';
+import type { BinaryRequestKind } from '../wire/command-set.js';
/**
* TCP socket connection options.
@@ -44,14 +45,27 @@ export type CommandResponse = {
data: Buffer
};
+export type SendCommandOptions = {
+ /** Whether the response uses the standard command response decoder */
+ handleResponse?: boolean,
+ /** Whether to append rather than prepend the command to the queue */
+ last?: boolean,
+ /** Execution model supplied by the public raw-request API */
+ rawKind?: BinaryRequestKind
+};
+
/**
* Low-level client interface for communicating with the Iggy server.
* Provides direct access to command sending and event handling.
*/
export type RawClient = {
+ /** Server wire protocol used by this connection */
+ readonly protocol: Protocol,
/** Sends a command to the server and returns the response */
sendCommand: (
- code: number, payload: Buffer, handleResponse?: boolean
+ code: number,
+ payload: Buffer,
+ options?: SendCommandOptions
) => Promise<CommandResponse>,
/** Whether the client has been authenticated */
isAuthenticated: boolean
@@ -101,6 +115,9 @@ export type ReconnectOption = {
*/
export type TransportOption = TcpOption | TlsOption;
+/** Server wire protocol. */
+export type Protocol = 'classic' | 'vsr';
+
/**
* Token-based authentication credentials.
*/
@@ -139,6 +156,8 @@ export type PoolSizeOption = {
* Complete client configuration for connecting to the Iggy server.
*/
export type ClientConfig = {
+ /** Server wire protocol (default: classic) */
+ protocol?: Protocol,
/** Transport protocol to use (TCP or TLS) */
transport: TransportType,
/** Transport-specific connection options */
@@ -150,5 +169,7 @@ export type ClientConfig = {
/** Automatic reconnection configuration */
reconnect?: ReconnectOption,
/** Interval for sending heartbeat pings in milliseconds */
- heartbeatInterval?: number
+ heartbeatInterval?: number,
+ /** Maximum accepted response frame size in bytes */
+ maxResponseFrameSize?: number
}
diff --git a/foreign/node/src/client/index.ts b/foreign/node/src/client/index.ts
index 9bd6e2a3a..d17a9e603 100644
--- a/foreign/node/src/client/index.ts
+++ b/foreign/node/src/client/index.ts
@@ -17,6 +17,7 @@
//
export { Client, SimpleClient, SingleClient } from './client.js'
+export * from './client.config.js';
export * from './client.utils.js';
export * from './client.socket.js';
export * from './client.type.js';
diff --git a/foreign/node/src/e2e/tcp.cluster.e2e.ts b/foreign/node/src/e2e/tcp.cluster.e2e.ts
index 8fae9e93f..4416109fa 100644
--- a/foreign/node/src/e2e/tcp.cluster.e2e.ts
+++ b/foreign/node/src/e2e/tcp.cluster.e2e.ts
@@ -52,12 +52,35 @@ const expectedMeta = {
],
};
+const expectedVsrMeta = {
+ name: "single-node",
+ nodes: [
+ {
+ name: "iggy-node",
+ ip: "127.0.0.1",
+ endpoints: {
+ tcp: 8090,
+ quic: 8080,
+ http: 3000,
+ websocket: 8092,
+ },
+ role: "Leader",
+ status: "Healthy",
+ },
+ ],
+};
+
describe("e2e -> system", async () => {
const c = getTestClient();
it("e2e -> cluster::getClusterMetadata", async () => {
const meta = await c.cluster.getClusterMetadata();
- assert.deepEqual(meta, expectedMeta);
+ assert.deepEqual(
+ meta,
+ process.env.IGGY_TEST_PROTOCOL === "vsr"
+ ? expectedVsrMeta
+ : expectedMeta
+ );
});
after(() => {
diff --git a/foreign/node/src/e2e/tcp.consumer-group.e2e.ts b/foreign/node/src/e2e/tcp.consumer-group.e2e.ts
index 5638180c5..d0dd85497 100644
--- a/foreign/node/src/e2e/tcp.consumer-group.e2e.ts
+++ b/foreign/node/src/e2e/tcp.consumer-group.e2e.ts
@@ -26,8 +26,10 @@ import { getIggyAddress } from '../tcp.sm.utils.js';
describe('e2e -> consumer-group', async () => {
const [host, port] = getIggyAddress();
+ const vsr = process.env.IGGY_TEST_PROTOCOL === 'vsr';
const c = new SingleClient({
+ protocol: vsr ? 'vsr' : 'classic',
transport: 'TCP',
options: { host, port },
credentials: { username: 'iggy', password: 'iggy' }
@@ -88,12 +90,14 @@ describe('e2e -> consumer-group', async () => {
it('e2e -> consumer-stream::send-messages', async () => {
const ct = 1000;
const mn = 200;
- for (let i = 0; i <= ct; i += mn) {
+ for (let i = 0; i < ct; i += mn) {
assert.ok(await c.message.send({
streamId: streamName,
topicId: topicName,
messages: generateMessages(mn),
- partition: Partitioning.MessageKey(`key-${ i % 300 }`)
+ partition: vsr
+ ? Partitioning.PartitionId((i / mn) % 3)
+ : Partitioning.MessageKey(`key-${ i % 300 }`)
}));
}
payloadLength = ct;
diff --git a/foreign/node/src/e2e/tcp.consumer-stream.e2e.ts b/foreign/node/src/e2e/tcp.consumer-stream.e2e.ts
index 03760a15c..e954e7e6a 100644
--- a/foreign/node/src/e2e/tcp.consumer-stream.e2e.ts
+++ b/foreign/node/src/e2e/tcp.consumer-stream.e2e.ts
@@ -32,8 +32,10 @@ describe('e2e -> consumer-stream', async () => {
const [host, port] = getIggyAddress();
const credentials = { username: 'iggy', password: 'iggy' };
+ const vsr = process.env.IGGY_TEST_PROTOCOL === 'vsr';
const opt = {
+ protocol: (vsr ? 'vsr' : 'classic') as 'vsr' | 'classic',
transport: 'TCP' as const,
options: { host, port },
credentials
@@ -58,7 +60,11 @@ describe('e2e -> consumer-stream', async () => {
it('e2e -> consumer-stream::send-messages', async () => {
for (let i = 0; i < ct; i += 100) {
await sendSomeMessages(c.clientProvider)(
- streamName, topicName, Partitioning.MessageKey(`k-${i % 300}`)
+ streamName,
+ topicName,
+ vsr
+ ? Partitioning.PartitionId((i / 100) % 3)
+ : Partitioning.MessageKey(`k-${i % 300}`)
);
}
});
diff --git a/foreign/node/src/e2e/tcp.raw.e2e.ts b/foreign/node/src/e2e/tcp.raw.e2e.ts
index 9928b8263..309117eb7 100644
--- a/foreign/node/src/e2e/tcp.raw.e2e.ts
+++ b/foreign/node/src/e2e/tcp.raw.e2e.ts
@@ -19,31 +19,92 @@
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { getTestClient } from './test-client.utils.js';
+import { BINARY_REQUEST_KIND } from '../wire/command-set.js';
import { COMMAND_CODE } from '../wire/command.code.js';
describe('e2e -> raw', async () => {
const c = getTestClient();
+ const VENDOR_CODE = 60_001;
+
it('e2e -> raw::ping', async () => {
- const response = await c.sendBinaryRequest(COMMAND_CODE.Ping, Buffer.alloc(0));
+ const response = await c.sendBinaryRequest(
+ BINARY_REQUEST_KIND.NonReplicated,
+ COMMAND_CODE.Ping,
+ Buffer.alloc(0)
+ );
assert.deepEqual(response, Buffer.alloc(0));
});
it('e2e -> raw::getStats', async () => {
- const response = await c.sendBinaryRequest(COMMAND_CODE.GetStats, Buffer.alloc(0));
+ const response = await c.sendBinaryRequest(
+ BINARY_REQUEST_KIND.NonReplicated,
+ COMMAND_CODE.GetStats,
+ Buffer.alloc(0)
+ );
assert.ok(response.length > 0);
});
+ it('e2e -> raw::getStatsUsesTheProtocolKindRules', async () => {
+ const request = () => c.sendBinaryRequest(
+ BINARY_REQUEST_KIND.Replicated,
+ COMMAND_CODE.GetStats,
+ Buffer.alloc(0)
+ );
+ if (process.env.IGGY_TEST_PROTOCOL === 'vsr') {
+ await assert.rejects(request);
+ return;
+ }
+
+ // Classic framing has no operation field, so the read still succeeds.
+ assert.ok((await request()).length > 0);
+ });
+
it('e2e -> raw::sessionControlCodeRejectedClientSide', async () => {
+ for (const kind of Object.values(BINARY_REQUEST_KIND))
+ await assert.rejects(
+ () => c.sendBinaryRequest(kind, COMMAND_CODE.LoginUser, Buffer.alloc(0))
+ );
+ });
+
+ it('e2e -> raw::vendorCodeRejectedByServer', async () => {
await assert.rejects(
- () => c.sendBinaryRequest(COMMAND_CODE.LoginUser, Buffer.alloc(0))
+ () => c.sendBinaryRequest(BINARY_REQUEST_KIND.NonReplicated, VENDOR_CODE, Buffer.alloc(0))
+ );
+
+ // The rejection is request-level, so the connection stays usable.
+ const response = await c.sendBinaryRequest(
+ BINARY_REQUEST_KIND.NonReplicated,
+ COMMAND_CODE.Ping,
+ Buffer.alloc(0)
);
+ assert.deepEqual(response, Buffer.alloc(0));
+ });
+
+ it('e2e -> raw::repeatedVendorCodesDoNotGapMetadataRequestIds', async () => {
+ for (let attempt = 0; attempt < 3; attempt += 1)
+ await assert.rejects(
+ () => c.sendBinaryRequest(
+ BINARY_REQUEST_KIND.NonReplicated,
+ VENDOR_CODE + attempt,
+ Buffer.from([attempt])
+ )
+ );
+
+ const streamName = `e2e-raw-sequence-${Date.now()}`;
+ const stream = await c.stream.create({ name: streamName });
+ assert.equal(stream.name, streamName);
+ assert.equal(await c.stream.delete({ streamId: streamName }), true);
});
- it('e2e -> raw::unknownCodeRejectedByServer', async () => {
+ it('e2e -> raw::unknownReplicatedCodeRejected', async () => {
await assert.rejects(
- () => c.sendBinaryRequest(60000, Buffer.alloc(0))
+ () => c.sendBinaryRequest(
+ BINARY_REQUEST_KIND.Replicated,
+ VENDOR_CODE,
+ Buffer.alloc(0)
+ )
);
});
diff --git a/foreign/node/src/e2e/test-client.utils.ts b/foreign/node/src/e2e/test-client.utils.ts
index 22090066e..b5d2d7713 100644
--- a/foreign/node/src/e2e/test-client.utils.ts
+++ b/foreign/node/src/e2e/test-client.utils.ts
@@ -21,8 +21,10 @@ import { getIggyAddress } from '../tcp.sm.utils.js';
const credentials = { username: 'iggy', password: 'iggy' };
const [host, port] = getIggyAddress();
+const protocol = process.env.IGGY_TEST_PROTOCOL === 'vsr' ? 'vsr' : 'classic';
export const getTestClient = () => new Client({
+ protocol,
transport: 'TCP',
options: { host, port },
credentials
diff --git a/foreign/node/src/index.ts b/foreign/node/src/index.ts
index e684b401a..299425aeb 100644
--- a/foreign/node/src/index.ts
+++ b/foreign/node/src/index.ts
@@ -23,6 +23,8 @@ export {
Partitioning,
HeaderValue,
HeaderKeyFactory,
+ BINARY_REQUEST_KIND,
+ BinaryRequestKind,
} from "./wire/index.js";
export * from "./client/index.js";
diff --git a/foreign/node/src/wire/command-set.test.ts b/foreign/node/src/wire/command-set.test.ts
index 055513908..ac4fe76d4 100644
--- a/foreign/node/src/wire/command-set.test.ts
+++ b/foreign/node/src/wire/command-set.test.ts
@@ -21,8 +21,14 @@ import assert from 'node:assert/strict';
import { SimpleClient } from '../client/client.js';
import type { RawClient } from '../client/client.type.js';
import { COMMAND_CODE } from './command.code.js';
+import {
+ BINARY_REQUEST_KIND,
+ BinaryRequestKind,
+ type BinaryRequestKind as BinaryRequestKindType
+} from './command-set.js';
const mockRawClient = (): RawClient => ({
+ protocol: 'classic',
sendCommand: async () => {
throw new Error('sendCommand should not be called by the session-control guard');
},
@@ -39,35 +45,94 @@ const mockRawClient = (): RawClient => ({
});
describe('CommandAPI.sendBinaryRequest', () => {
+ it('exports exactly the two protocol request kinds', () => {
+ assert.deepEqual(BinaryRequestKind, {
+ NonReplicated: 'non_replicated',
+ Replicated: 'replicated'
+ });
+ });
+
+ it('requires the request kind in TypeScript', () => {
+ const client = new SimpleClient(mockRawClient());
+ if (false) {
+ // @ts-expect-error the breaking API requires a replication kind
+ void client.sendBinaryRequest(COMMAND_CODE.Ping, Buffer.alloc(0));
+ }
+ assert.equal('sendBinaryRequestWithKind' in client, false);
+ });
describe('session-control guard', () => {
- [
- COMMAND_CODE.LoginUser,
- COMMAND_CODE.LogoutUser,
- COMMAND_CODE.LoginRegister,
- COMMAND_CODE.LoginWithAccessToken,
- COMMAND_CODE.LoginRegisterWithAccessToken,
- ].forEach((code) => {
- it(`rejects code ${code} before reaching the client provider`, async () => {
- const client = new SimpleClient(mockRawClient());
- await assert.rejects(
- () => client.sendBinaryRequest(code, Buffer.alloc(0)),
- /code: 3, message: Invalid command/
- );
+ Object.values(BINARY_REQUEST_KIND).forEach((kind) => {
+ [
+ COMMAND_CODE.LoginUser,
+ COMMAND_CODE.LogoutUser,
+ COMMAND_CODE.LoginRegister,
+ COMMAND_CODE.LoginWithAccessToken,
+ COMMAND_CODE.LoginRegisterWithAccessToken,
+ ].forEach((code) => {
+ it(`rejects ${kind} code ${code} before reaching the client provider`, async () => {
+ const client = new SimpleClient(mockRawClient());
+ await assert.rejects(
+ () => client.sendBinaryRequest(kind, code, Buffer.alloc(0)),
+ /code: 3, message: Invalid command/
+ );
+ });
});
});
});
+ it('rejects every invalid request kind before reaching the raw client', async () => {
+ const client = new SimpleClient(mockRawClient());
+ const invalidKinds = [
+ undefined,
+ null,
+ 'auto',
+ 0,
+ {},
+ ];
+ for (const invalidKind of invalidKinds)
+ await assert.rejects(
+ () => client.sendBinaryRequest(
+ invalidKind as BinaryRequestKindType,
+ COMMAND_CODE.Ping,
+ Buffer.alloc(0)
+ ),
+ /code: 3, message: Invalid command/
+ );
+ });
+
+ it('encodes both kinds identically because classic framing has no operation field', async () => {
+ const customCode = 60_001;
+ const payload = Buffer.from([0xAA, 0xBB, 0xCC]);
+ const frames: { code: number, payload: Buffer }[] = [];
+ const raw = mockRawClient();
+ raw.sendCommand = async (code, sentPayload) => {
+ frames.push({ code, payload: Buffer.from(sentPayload) });
+ return { status: 0, length: 1, data: Buffer.alloc(0) };
+ };
+ const client = new SimpleClient(raw);
+
+ for (const kind of Object.values(BINARY_REQUEST_KIND))
+ await client.sendBinaryRequest(kind, customCode, payload);
+
+ assert.equal(frames.length, 2);
+ assert.deepEqual(frames[0], frames[1]);
+ });
+
it('forwards a custom code and opaque payload to sendCommand', async () => {
const customCode = 60_000;
const payload = Buffer.from([0xAA, 0xBB, 0xCC]);
const expectedResponse = Buffer.from('opaque response');
const raw = mockRawClient();
- raw.sendCommand = async (code, sentPayload) => {
+ raw.sendCommand = async (code, sentPayload, options) => {
assert.equal(code, customCode);
assert.deepEqual(sentPayload, payload);
+ assert.equal(
+ options?.rawKind,
+ BINARY_REQUEST_KIND.NonReplicated
+ );
return {
status: 0,
length: expectedResponse.length,
@@ -75,7 +140,11 @@ describe('CommandAPI.sendBinaryRequest', () => {
};
};
const client = new SimpleClient(raw);
- const response = await client.sendBinaryRequest(customCode, payload);
+ const response = await client.sendBinaryRequest(
+ BINARY_REQUEST_KIND.NonReplicated,
+ customCode,
+ payload
+ );
assert.deepEqual(response, expectedResponse);
});
@@ -88,7 +157,11 @@ describe('CommandAPI.sendBinaryRequest', () => {
return { status: 0, length: 1, data: Buffer.alloc(0) };
};
- const request = new SimpleClient(raw).sendBinaryRequest(60_000, payload);
+ const request = new SimpleClient(raw).sendBinaryRequest(
+ BINARY_REQUEST_KIND.NonReplicated,
+ 60_001,
+ payload
+ );
payload.fill(0);
await request;
@@ -103,6 +176,7 @@ describe('CommandAPI.sendBinaryRequest', () => {
});
const response = await new SimpleClient(raw).sendBinaryRequest(
+ BINARY_REQUEST_KIND.NonReplicated,
COMMAND_CODE.Ping,
Buffer.alloc(0)
);
diff --git a/foreign/node/src/wire/command-set.ts b/foreign/node/src/wire/command-set.ts
index 44bdf26d2..5265f1184 100644
--- a/foreign/node/src/wire/command-set.ts
+++ b/foreign/node/src/wire/command-set.ts
@@ -34,6 +34,7 @@ import { joinGroup } from './consumer-group/join-group.command.js';
import { getGroup } from './consumer-group/get-group.command.js';
import { getGroups } from './consumer-group/get-groups.command.js';
import { leaveGroup } from './consumer-group/leave-group.command.js';
+import { syncGroup } from './consumer-group/sync-group.command.js';
import { deleteGroup } from './consumer-group/delete-group.command.js';
import {
ensureConsumerGroup, ensureConsumerGroupAndJoin
@@ -165,6 +166,7 @@ const groupAPI = (c: ClientProvider) => ({
create: createGroup(c),
join: joinGroup(c),
leave: leaveGroup(c),
+ sync: syncGroup(c),
delete: deleteGroup(c),
ensure: ensureConsumerGroup(c),
ensureAndJoin: ensureConsumerGroupAndJoin(c)
@@ -211,6 +213,26 @@ const SESSION_CONTROL_CODES = new Set([
const INVALID_COMMAND_ERROR_CODE = 3;
+/**
+ * How a raw binary request executes on the server.
+ *
+ * Classic framing carries no operation field, while VSR framing uses this
+ * declaration to route unknown extension codes.
+ */
+export const BINARY_REQUEST_KIND = {
+ NonReplicated: 'non_replicated',
+ Replicated: 'replicated'
+} as const;
+
+/** PascalCase alias for enum-style call sites. */
+export const BinaryRequestKind = BINARY_REQUEST_KIND;
+
+export type BinaryRequestKind =
+ typeof BINARY_REQUEST_KIND[keyof typeof BINARY_REQUEST_KIND];
+
+const BINARY_REQUEST_KINDS: ReadonlySet<string> =
+ new Set(Object.values(BINARY_REQUEST_KIND));
+
export abstract class AbstractAPI {
clientProvider: ClientProvider;
@@ -242,16 +264,25 @@ export abstract class CommandAPI extends AbstractAPI {
* Sends a command code with a payload and returns the raw response payload.
* Session-control codes are rejected with an invalid-command error.
*
+ * @param kind - How the command executes
* @param code - Command code to send
* @param payload - Raw command payload
* @returns Raw response payload
*/
- async sendBinaryRequest(code: number, payload: Buffer): Promise<Buffer> {
- if (SESSION_CONTROL_CODES.has(code))
+ async sendBinaryRequest(
+ kind: BinaryRequestKind,
+ code: number,
+ payload: Buffer
+ ): Promise<Buffer> {
+ if (!BINARY_REQUEST_KINDS.has(kind) || SESSION_CONTROL_CODES.has(code))
throw responseError(code, INVALID_COMMAND_ERROR_CODE);
const requestPayload = Buffer.from(payload);
- const response = await (await this.clientProvider()).sendCommand(code, requestPayload);
+ const response = await (await this.clientProvider()).sendCommand(
+ code,
+ requestPayload,
+ { rawKind: kind }
+ );
return response.length <= 1 ? Buffer.alloc(0) : response.data;
}
}
diff --git a/foreign/node/src/wire/command.code.ts b/foreign/node/src/wire/command.code.ts
index bfdcafcba..adbe81912 100644
--- a/foreign/node/src/wire/command.code.ts
+++ b/foreign/node/src/wire/command.code.ts
@@ -47,6 +47,8 @@ export const COMMAND_CODE = {
GetOffset: 120,
StoreOffset: 121,
DeleteConsumerOffset: 122,
+ StoreOffset2: 123,
+ DeleteConsumerOffset2: 124,
GetStream: 200,
GetStreams: 201,
CreateStream: 202,
@@ -68,6 +70,7 @@ export const COMMAND_CODE = {
DeleteGroup: 603,
JoinGroup: 604,
LeaveGroup: 605,
+ SyncGroup: 606,
};
const reverseCommandCodeMap = reverseRecord(COMMAND_CODE);
diff --git a/foreign/node/src/wire/consumer-group/group.utils.ts b/foreign/node/src/wire/consumer-group/group.utils.ts
index 9b56db85e..a64f91a5b 100644
--- a/foreign/node/src/wire/consumer-group/group.utils.ts
+++ b/foreign/node/src/wire/consumer-group/group.utils.ts
@@ -18,6 +18,13 @@
import { serializeIdentifier, type Id } from '../identifier.utils.js';
+/** Stream, topic, and consumer-group identifiers. */
+export type TargetGroup = {
+ streamId: Id,
+ topicId: Id,
+ groupId: Id,
+};
+
/**
* Consumer group information.
*/
diff --git a/foreign/node/src/wire/consumer-group/index.ts b/foreign/node/src/wire/consumer-group/index.ts
index 7c1b67aef..89219ad06 100644
--- a/foreign/node/src/wire/consumer-group/index.ts
+++ b/foreign/node/src/wire/consumer-group/index.ts
@@ -22,4 +22,5 @@ export * from './get-group.command.js';
export * from './get-groups.command.js';
export * from './join-group.command.js';
export * from './leave-group.command.js';
+export * from './sync-group.command.js';
export * from './ensure-group.virtual.command.js';
diff --git a/foreign/node/src/wire/consumer-group/sync-group.command.test.ts b/foreign/node/src/wire/consumer-group/sync-group.command.test.ts
new file mode 100644
index 000000000..85b3ba050
--- /dev/null
+++ b/foreign/node/src/wire/consumer-group/sync-group.command.test.ts
@@ -0,0 +1,99 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+import { describe, it } from 'node:test';
+import assert from 'node:assert/strict';
+import { SYNC_GROUP } from './sync-group.command.js';
+
+describe('SyncGroup', () => {
+ it('serializes group identifiers', () => {
+ assert.equal(
+ SYNC_GROUP.serialize({ streamId: 5, topicId: 2, groupId: 1 }).length,
+ 18,
+ );
+ });
+
+ it('deserializes an assignment', () => {
+ const data = Buffer.alloc(20);
+ data.writeBigUInt64LE(7n, 0);
+ data.writeUInt32LE(2, 8);
+ data.writeUInt32LE(1, 12);
+ data.writeUInt32LE(4, 16);
+ assert.deepEqual(
+ SYNC_GROUP.deserialize({ status: 0, length: data.length, data }),
+ { generation: 7n, partitions: [1, 4] },
+ );
+ });
+
+ it('maps an empty response to no assignment', () => {
+ assert.equal(
+ SYNC_GROUP.deserialize({ status: 0, length: 0, data: Buffer.alloc(0) }),
+ null,
+ );
+ });
+
+ it('rejects a truncated fixed header', () => {
+ assert.throws(
+ () => SYNC_GROUP.deserialize({
+ status: 0,
+ length: 11,
+ data: Buffer.alloc(11),
+ }),
+ /assignment is truncated/,
+ );
+ });
+
+ it('rejects a truncated partition list', () => {
+ const data = Buffer.alloc(16);
+ data.writeUInt32LE(2, 8);
+ assert.throws(
+ () => SYNC_GROUP.deserialize({
+ status: 0,
+ length: data.length,
+ data,
+ }),
+ /partition list is truncated/,
+ );
+ });
+
+ it('rejects an impossible partition count', () => {
+ const data = Buffer.alloc(16);
+ data.writeUInt32LE(0xFFFF_FFFF, 8);
+ assert.throws(
+ () => SYNC_GROUP.deserialize({
+ status: 0,
+ length: data.length,
+ data,
+ }),
+ /partition list is truncated/,
+ );
+ });
+
+ it('rejects trailing bytes', () => {
+ const data = Buffer.alloc(17);
+ data.writeUInt32LE(1, 8);
+ assert.throws(
+ () => SYNC_GROUP.deserialize({
+ status: 0,
+ length: data.length,
+ data,
+ }),
+ /trailing bytes/,
+ );
+ });
+});
diff --git a/foreign/node/src/wire/consumer-group/sync-group.command.ts b/foreign/node/src/wire/consumer-group/sync-group.command.ts
new file mode 100644
index 000000000..3e590a545
--- /dev/null
+++ b/foreign/node/src/wire/consumer-group/sync-group.command.ts
@@ -0,0 +1,68 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+import type { CommandResponse } from '../../client/client.type.js';
+import { DeserializeError } from '../error.utils.js';
+import { wrapCommand } from '../command.utils.js';
+import { COMMAND_CODE } from '../command.code.js';
+import {
+ serializeTargetGroup,
+ type TargetGroup,
+} from './group.utils.js';
+
+/** Current assignment for a consumer-group member. */
+export type ConsumerGroupAssignment = {
+ /** Monotonic group generation */
+ generation: bigint,
+ /** Partition IDs currently owned by this member */
+ partitions: number[],
+};
+
+export const SYNC_GROUP = {
+ code: COMMAND_CODE.SyncGroup,
+
+ serialize: ({ streamId, topicId, groupId }: TargetGroup) =>
+ serializeTargetGroup(streamId, topicId, groupId),
+
+ deserialize: (response: CommandResponse): ConsumerGroupAssignment | null => {
+ if (response.data.length === 0)
+ return null;
+ if (response.data.length < 12)
+ throw new DeserializeError('consumer group assignment is truncated');
+ const generation = response.data.readBigUInt64LE(0);
+ const partitionsCount = response.data.readUInt32LE(8);
+ const partitionsLength = partitionsCount * 4;
+ if (!Number.isSafeInteger(partitionsLength) ||
+ partitionsLength > response.data.length - 12)
+ throw new DeserializeError(
+ 'consumer group assignment partition list is truncated'
+ );
+ if (response.data.length !== 12 + partitionsLength)
+ throw new DeserializeError(
+ 'consumer group assignment has trailing bytes'
+ );
+ const partitions = new Array<number>(partitionsCount);
+ for (let index = 0; index < partitionsCount; index += 1)
+ partitions[index] = response.data.readUInt32LE(12 + index * 4);
+ return { generation, partitions };
+ },
+};
+
+/** Fetches this connection's current consumer-group assignment. */
+export const syncGroup =
+ wrapCommand<TargetGroup, ConsumerGroupAssignment | null>(SYNC_GROUP);
diff --git a/foreign/node/src/wire/error.utils.ts b/foreign/node/src/wire/error.utils.ts
index 72a8cadc1..54988abd0 100644
--- a/foreign/node/src/wire/error.utils.ts
+++ b/foreign/node/src/wire/error.utils.ts
@@ -19,10 +19,24 @@
import { translateCommandCode } from './command.code.js';
import { translateErrorCode } from './error.code.js';
-export const responseError = (cmdCode: number, errCode: number) => new Error(
- `command: { code: ${cmdCode}, name: ${translateCommandCode(cmdCode)} } ` +
- `error: {code: ${errCode}, message: ${translateErrorCode(errCode)} }`
-);
+export class ResponseError extends Error {
+ readonly commandCode: number;
+ readonly errorCode: number;
+
+ constructor(commandCode: number, errorCode: number) {
+ super(
+ `command: { code: ${commandCode}, name: ${translateCommandCode(commandCode)} } ` +
+ `error: {code: ${errorCode}, message: ${translateErrorCode(errorCode)} }`
+ );
+ this.name = 'ResponseError';
+ this.commandCode = commandCode;
+ this.errorCode = errorCode;
+ Object.setPrototypeOf(this, ResponseError.prototype);
+ }
+}
+
+export const responseError = (cmdCode: number, errCode: number) =>
+ new ResponseError(cmdCode, errCode);
export class DeserializeError extends Error {
constructor(message: string, cause?: Record<string , unknown>) {
diff --git a/foreign/node/src/wire/message/poll-messages.command.ts b/foreign/node/src/wire/message/poll-messages.command.ts
index 7944ba64d..981fb8193 100644
--- a/foreign/node/src/wire/message/poll-messages.command.ts
+++ b/foreign/node/src/wire/message/poll-messages.command.ts
@@ -17,15 +17,33 @@
//
import type { Id } from '../identifier.utils.js';
-import type { CommandResponse } from '../../client/client.type.js';
-import type { Consumer } from '../offset/offset.utils.js';
-import { wrapCommand } from '../command.utils.js';
+import type {
+ CommandResponse,
+ ClientProvider,
+ RawClient,
+} from '../../client/client.type.js';
+import {
+ ConsumerKind,
+ type Consumer,
+} from '../offset/offset.utils.js';
import { COMMAND_CODE } from '../command.code.js';
+import { responseError } from '../error.utils.js';
+import { SYNC_GROUP } from '../consumer-group/sync-group.command.js';
import {
serializePollMessages, deserializePollMessages,
type PollingStrategy, type PollMessagesResponse
} from './poll.utils.js';
+const RESYNC_REQUIRED_PARTITION = 0xFFFF_FFFF;
+const GROUP_POLL_MAX_ATTEMPTS = 2;
+
+type GroupCursor = {
+ generation: bigint,
+ partitions: number[],
+ position: number,
+};
+
+const groupCursors = new WeakMap<RawClient, Map<string, GroupCursor>>();
/**
* Parameters for the poll messages command.
@@ -67,7 +85,79 @@ export const POLL_MESSAGES = {
}
};
+const groupKey = ({ streamId, topicId, consumer }: PollMessages): string =>
+ `${String(streamId)}\0${String(topicId)}\0${String(consumer.id)}`;
+
+const syncAssignment = async (
+ client: RawClient,
+ request: PollMessages,
+): Promise<GroupCursor> => {
+ const response = await client.sendCommand(
+ SYNC_GROUP.code,
+ SYNC_GROUP.serialize({
+ streamId: request.streamId,
+ topicId: request.topicId,
+ groupId: request.consumer.id,
+ }),
+ );
+ const assignment = SYNC_GROUP.deserialize(response);
+ if (assignment === null)
+ throw responseError(SYNC_GROUP.code, 5006);
+
+ let cursors = groupCursors.get(client);
+ if (!cursors) {
+ cursors = new Map();
+ groupCursors.set(client, cursors);
+ client.once('sessionReset', () => groupCursors.delete(client));
+ }
+ const key = groupKey(request);
+ const current = cursors.get(key);
+ if (current && current.generation === assignment.generation) {
+ current.partitions = assignment.partitions;
+ if (current.position >= current.partitions.length)
+ current.position = 0;
+ return current;
+ }
+ const cursor = { ...assignment, position: 0 };
+ cursors.set(key, cursor);
+ return cursor;
+};
+
+const pollConsumerGroup = async (
+ client: RawClient,
+ request: PollMessages,
+): Promise<PollMessagesResponse> => {
+ for (let attempt = 0; attempt < GROUP_POLL_MAX_ATTEMPTS; attempt += 1) {
+ const cursor = await syncAssignment(client, request);
+ if (cursor.partitions.length === 0)
+ return { partitionId: 0, currentOffset: 0n, count: 0, messages: [] };
+
+ const partitionId = cursor.partitions[cursor.position];
+ cursor.position = (cursor.position + 1) % cursor.partitions.length;
+ const response = await client.sendCommand(
+ POLL_MESSAGES.code,
+ POLL_MESSAGES.serialize({ ...request, partitionId }),
+ );
+ const polled = POLL_MESSAGES.deserialize(response);
+ if (polled.count === 0 &&
+ polled.partitionId === RESYNC_REQUIRED_PARTITION)
+ continue;
+ return polled;
+ }
+ return { partitionId: 0, currentOffset: 0n, count: 0, messages: [] };
+};
+
/**
* Executable poll messages command function.
*/
-export const pollMessages = wrapCommand<PollMessages, PollMessagesResponse>(POLL_MESSAGES);
+export const pollMessages = (getClient: ClientProvider) =>
+ async (request: PollMessages): Promise<PollMessagesResponse> => {
+ const client = await getClient();
+ if (client.protocol === 'vsr' &&
+ request.consumer.kind === ConsumerKind.Group &&
+ request.partitionId === null)
+ return pollConsumerGroup(client, request);
+ return POLL_MESSAGES.deserialize(
+ await client.sendCommand(POLL_MESSAGES.code, POLL_MESSAGES.serialize(request))
+ );
+ };
diff --git a/foreign/node/src/wire/topic/topic.utils.test.ts b/foreign/node/src/wire/topic/topic.utils.test.ts
new file mode 100644
index 000000000..41753f2db
--- /dev/null
+++ b/foreign/node/src/wire/topic/topic.utils.test.ts
@@ -0,0 +1,45 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+import { describe, it } from 'node:test';
+import assert from 'node:assert/strict';
+import { deserializeBaseTopic } from './topic.utils.js';
+
+describe('deserializeBaseTopic', () => {
+ it('uses the current message-expiry then compression wire layout', () => {
+ const data = Buffer.alloc(52);
+ data.writeUInt32LE(7, 0);
+ data.writeBigUInt64LE(1_710_000_000_000n, 4);
+ data.writeUInt32LE(3, 12);
+ data.writeBigUInt64LE(86_400_000_000n, 16);
+ data.writeUInt8(2, 24);
+ data.writeBigUInt64LE(1_000_000n, 25);
+ data.writeUInt8(3, 33);
+ data.writeBigUInt64LE(4096n, 34);
+ data.writeBigUInt64LE(12n, 42);
+ data.writeUInt8(1, 50);
+ data.write('t', 51);
+
+ const { bytesRead, data: topic } = deserializeBaseTopic(data);
+
+ assert.equal(bytesRead, data.length);
+ assert.equal(topic.messageExpiry, 86_400_000_000n);
+ assert.equal(topic.compressionAlgorithm, 2);
+ assert.equal(topic.maxTopicSize, 1_000_000n);
+ });
+});
diff --git a/foreign/node/src/wire/topic/topic.utils.ts b/foreign/node/src/wire/topic/topic.utils.ts
index 452633406..9384ff5ee 100644
--- a/foreign/node/src/wire/topic/topic.utils.ts
+++ b/foreign/node/src/wire/topic/topic.utils.ts
@@ -123,8 +123,8 @@ export const deserializeBaseTopic = (p: Buffer, pos = 0): BaseTopicSerialized =>
const id = p.readUInt32LE(pos);
const createdAt = toDate(p.readBigUint64LE(pos + 4));
const partitionsCount = p.readUInt32LE(pos + 12);
- const compressionAlgorithm = p.readUInt8(pos + 16);
- const messageExpiry = p.readBigUInt64LE(pos + 17);
+ const messageExpiry = p.readBigUInt64LE(pos + 16);
+ const compressionAlgorithm = p.readUInt8(pos + 24);
const maxTopicSize = p.readBigUInt64LE(pos + 25);
const replicationFactor = p.readUInt8(pos + 33);
const sizeBytes = p.readBigUInt64LE(pos + 34);
diff --git a/foreign/node/src/wire/vsr/header.test.ts b/foreign/node/src/wire/vsr/header.test.ts
new file mode 100644
index 000000000..91b92def0
--- /dev/null
+++ b/foreign/node/src/wire/vsr/header.test.ts
@@ -0,0 +1,99 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import {
+ Command2,
+ encodeRequestHeader,
+ HEADER_SIZE,
+ REQUEST_OFFSET
+} from './header.js';
+
+describe('VSR request header', () => {
+ it('encodes every field at its canonical offset', () => {
+ const client = 0x1122334455667788_99AABBCCDDEEFF00n;
+ const header = encodeRequestHeader({
+ size: HEADER_SIZE + 3,
+ client,
+ request: 0x0102030405060708n,
+ operation: 2,
+ namespace: 0x8877665544332211n,
+ session: 0x1020304050607080n,
+ nonReplicatedCode: 60_001
+ });
+
+ assert.equal(header.length, HEADER_SIZE);
+ assert.equal(header.readUInt32LE(REQUEST_OFFSET.size), HEADER_SIZE + 3);
+ assert.equal(header.readUInt8(REQUEST_OFFSET.command), Command2.Request);
+ assert.equal(
+ header.readBigUInt64LE(REQUEST_OFFSET.client),
+ 0x99AABBCCDDEEFF00n
+ );
+ assert.equal(
+ header.readBigUInt64LE(REQUEST_OFFSET.client + 8),
+ 0x1122334455667788n
+ );
+ assert.equal(
+ header.readBigUInt64LE(REQUEST_OFFSET.request),
+ 0x0102030405060708n
+ );
+ assert.equal(header.readUInt8(REQUEST_OFFSET.operation), 2);
+ assert.equal(
+ header.readBigUInt64LE(REQUEST_OFFSET.namespace),
+ 0x8877665544332211n
+ );
+ assert.equal(
+ header.readBigUInt64LE(REQUEST_OFFSET.session),
+ 0x1020304050607080n
+ );
+ assert.equal(header.readUInt32LE(REQUEST_OFFSET.reserved), 60_001);
+ assert.equal(header.readBigUInt64LE(REQUEST_OFFSET.timestamp), 0n);
+ });
+
+ it('leaves all unspecified and reserved bytes zero', () => {
+ const header = encodeRequestHeader({
+ size: HEADER_SIZE,
+ client: 1n,
+ request: 0n,
+ operation: 1,
+ namespace: 1n << 63n,
+ session: 0n
+ });
+ const expected = Buffer.alloc(HEADER_SIZE);
+ expected.writeUInt32LE(HEADER_SIZE, REQUEST_OFFSET.size);
+ expected.writeUInt8(Command2.Request, REQUEST_OFFSET.command);
+ expected.writeBigUInt64LE(1n, REQUEST_OFFSET.client);
+ expected.writeUInt8(1, REQUEST_OFFSET.operation);
+ expected.writeBigUInt64LE(1n << 63n, REQUEST_OFFSET.namespace);
+ assert.deepEqual(header, expected);
+ });
+
+ it('supports maximum-width unsigned request fields', () => {
+ const maximum = 0xFFFF_FFFF_FFFF_FFFFn;
+ const header = encodeRequestHeader({
+ size: HEADER_SIZE,
+ client: maximum << 64n | maximum,
+ request: maximum,
+ operation: 160,
+ namespace: maximum,
+ session: maximum
+ });
+ assert.equal(header.readBigUInt64LE(REQUEST_OFFSET.request), maximum);
+ assert.equal(header.readBigUInt64LE(REQUEST_OFFSET.session), maximum);
+ });
+});
diff --git a/foreign/node/src/wire/vsr/header.ts b/foreign/node/src/wire/vsr/header.ts
new file mode 100644
index 000000000..bdee4f270
--- /dev/null
+++ b/foreign/node/src/wire/vsr/header.ts
@@ -0,0 +1,165 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+/**
+ * VSR consensus header layout, ported from
+ * `core/binary_protocol/src/consensus/header.rs`. Every consensus frame in
+ * both directions starts with a 256-byte header. Fields are read and written
+ * by byte offset, mirroring the Rust SDK, which avoids struct casts because
+ * the headers lead with unaligned u128 fields.
+ */
+
+/** Size of every consensus header, both directions. */
+export const HEADER_SIZE = 256;
+
+/** `RequestHeader` field offsets the client writes. */
+export const REQUEST_OFFSET = {
+ size: 48,
+ command: 60,
+ client: 128,
+ timestamp: 160,
+ request: 168,
+ operation: 176,
+ namespace: 184,
+ session: 192,
+ reserved: 204
+} as const;
+
+/** `ReplyHeader` field offsets the client reads. */
+export const REPLY_OFFSET = {
+ size: 48,
+ command: 60,
+ operation: 208,
+ namespace: 216,
+ status: 224
+} as const;
+
+/** `EvictionHeader` field offsets the client reads. */
+export const EVICTION_OFFSET = {
+ command: 60,
+ client: 128,
+ serverProtocolVersion: 144,
+ serverProtocolVersionMin: 148,
+ reason: 255
+} as const;
+
+/** `Command2` frame discriminants a client encounters. */
+export const Command2 = {
+ Request: 5,
+ Reply: 8,
+ Eviction: 13
+} as const;
+
+/**
+ * `EvictionReason` values, mirroring
+ * `core/binary_protocol/src/consensus/header.rs`.
+ */
+export const EvictionReason = {
+ Reserved: 0,
+ NoSession: 1,
+ ClientReleaseTooLow: 2,
+ ClientReleaseTooHigh: 3,
+ InvalidRequestOperation: 4,
+ InvalidRequestBody: 5,
+ InvalidRequestBodySize: 6,
+ SessionTooLow: 7,
+ SessionReleaseMismatch: 8,
+ InvalidCredentials: 9,
+ InvalidToken: 10,
+ UserInactive: 11,
+ SessionError: 12,
+ StaleClient: 13,
+ IncompatibleProtocol: 14,
+ MalformedLogin: 15
+} as const;
+
+/** Fields the client writes into a request header. */
+export type RequestHeaderFields = {
+ /** Header + body total, bytes. */
+ size: number,
+ /** Ephemeral client identifier (u128). */
+ client: bigint,
+ /** Request id (u64): 0 for Register, else per session rules. */
+ request: bigint,
+ /** `Operation` discriminant. */
+ operation: number,
+ /** Routing namespace (u64). */
+ namespace: bigint,
+ /** Bound session (u64), or 0n. */
+ session: bigint,
+ /** Command code for `NonReplicated`, placed in `reserved[0..4]`. */
+ nonReplicatedCode?: number
+};
+
+const U64_MASK = 0xFFFFFFFFFFFFFFFFn;
+
+/**
+ * Encodes a 256-byte request header. Only the seven fields the server reads
+ * are written; the checksums stay zero, matching the Rust SDK's contract
+ * with the VSR server.
+ */
+export const encodeRequestHeader = (fields: RequestHeaderFields): Buffer => {
+ const header = Buffer.alloc(HEADER_SIZE);
+ header.writeUInt32LE(fields.size, REQUEST_OFFSET.size);
+ header.writeUInt8(Command2.Request, REQUEST_OFFSET.command);
+ // u128 client id: two little-endian u64 halves, low half first.
+ header.writeBigUInt64LE(fields.client & U64_MASK, REQUEST_OFFSET.client);
+ header.writeBigUInt64LE(fields.client >> 64n, REQUEST_OFFSET.client + 8);
+ header.writeBigUInt64LE(fields.request, REQUEST_OFFSET.request);
+ header.writeUInt8(fields.operation, REQUEST_OFFSET.operation);
+ header.writeBigUInt64LE(fields.namespace, REQUEST_OFFSET.namespace);
+ header.writeBigUInt64LE(fields.session, REQUEST_OFFSET.session);
+ if (fields.nonReplicatedCode !== undefined)
+ header.writeUInt32LE(fields.nonReplicatedCode, REQUEST_OFFSET.reserved);
+ return header;
+};
+
+/**
+ * Reads the frame discriminant. `command` sits at the same offset in every
+ * consensus header, so one byte discriminates the frame type.
+ */
+export const peekCommand = (header: Buffer): number =>
+ header.readUInt8(REPLY_OFFSET.command);
+
+/** Reads the total frame size from a reply or eviction header. */
+export const readSize = (header: Buffer): number =>
+ header.readUInt32LE(REPLY_OFFSET.size);
+
+/** Reads the pre-commit denial status; 0 means the reply committed. */
+export const readStatus = (header: Buffer): number =>
+ header.readUInt32LE(REPLY_OFFSET.status);
+
+/** Reads the `Operation` discriminant from a reply header. */
+export const readReplyOperation = (header: Buffer): number =>
+ header.readUInt8(REPLY_OFFSET.operation);
+
+/** Decoded eviction frame. */
+export type Eviction = {
+ reason: number,
+ serverProtocolVersion: number,
+ serverProtocolVersionMin: number
+};
+
+/** Reads the fields of an eviction header the client acts on. */
+export const readEviction = (header: Buffer): Eviction => ({
+ reason: header.readUInt8(EVICTION_OFFSET.reason),
+ serverProtocolVersion:
+ header.readUInt32LE(EVICTION_OFFSET.serverProtocolVersion),
+ serverProtocolVersionMin:
+ header.readUInt32LE(EVICTION_OFFSET.serverProtocolVersionMin)
+});
diff --git a/foreign/node/src/wire/vsr/index.ts b/foreign/node/src/wire/vsr/index.ts
new file mode 100644
index 000000000..390097855
--- /dev/null
+++ b/foreign/node/src/wire/vsr/index.ts
@@ -0,0 +1,152 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+import { createRequire } from 'node:module';
+import type { CommandResponse } from '../../client/client.type.js';
+import type { BinaryRequestKind } from '../command-set.js';
+import { COMMAND_CODE } from '../command.code.js';
+import { responseError } from '../error.utils.js';
+import { HEADER_SIZE, encodeRequestHeader } from './header.js';
+import { namespaceForRequest } from './namespace.js';
+import {
+ Operation,
+ isPartition,
+ operationForCode,
+} from './operation.js';
+import {
+ deserializeLoginRegister,
+ serializeLoginRegister,
+ serializeLoginRegisterWithPat,
+} from './register.js';
+import { decodeResponse } from './reply.js';
+import { ConsensusSession } from './session.js';
+
+const packageMetadata = createRequire(import.meta.url)(
+ '../../../package.json'
+) as { version: string };
+const SDK_VERSION = packageMetadata.version;
+const MAX_U32 = 0xFFFF_FFFF;
+/** `IggyError::Unauthenticated`, matching the Rust SDK's unbound-session error. */
+const UNAUTHENTICATED = 40;
+
+export class VsrSession {
+ private state: ConsensusSession;
+
+ constructor(clientId?: bigint) {
+ this.state = new ConsensusSession(clientId);
+ }
+
+ reset(): void {
+ this.state = new ConsensusSession();
+ }
+
+ bind(session: bigint): void {
+ this.state.bind(session);
+ }
+
+ encode(command: number, payload: Buffer, kind?: BinaryRequestKind): Buffer {
+ const operation = registerCommand(command)
+ ? Operation.Register
+ : operationForCode(command, kind);
+ const namespace = namespaceForRequest(command, payload, operation);
+ const size = HEADER_SIZE + payload.length;
+ if (!Number.isSafeInteger(size) || size > MAX_U32)
+ throw new RangeError('VSR request exceeds the u32 frame-size limit');
+
+ let request: bigint;
+ let session: bigint;
+
+ if (operation === Operation.Register) {
+ request = this.state.beginRegister();
+ session = 0n;
+ } else if (operation === Operation.NonReplicated) {
+ request = this.state.currentRequestId();
+ session = this.state.session ?? 0n;
+ } else {
+ if (this.state.session === null)
+ throw responseError(command, UNAUTHENTICATED);
+ request = isPartition(operation)
+ ? this.state.currentRequestId()
+ : this.state.nextRequestId();
+ session = this.state.session;
+ }
+
+ const header = encodeRequestHeader({
+ size: HEADER_SIZE + payload.length,
+ client: this.state.clientId,
+ request,
+ operation,
+ namespace,
+ session,
+ ...(operation === Operation.NonReplicated
+ ? { nonReplicatedCode: command }
+ : {}),
+ });
+ return payload.length === 0 ? header : Buffer.concat([header, payload]);
+ }
+}
+
+export const decodeVsrResponse = (frame: Buffer): CommandResponse => {
+ const data = decodeResponse(frame);
+ return { status: 0, length: data.length, data };
+};
+
+export const readRegisteredSession = (response: CommandResponse): bigint =>
+ deserializeLoginRegister(response.data).session;
+
+export const prepareVsrCommand = (
+ command: number,
+ payload: Buffer
+): { command: number, payload: Buffer } => {
+ if (command === COMMAND_CODE.LoginUser) {
+ const username = readWireName(payload, 0);
+ const password = readWireName(payload, username.next);
+ return {
+ command: COMMAND_CODE.LoginRegister,
+ payload: serializeLoginRegister(username.value, password.value, SDK_VERSION),
+ };
+ }
+ if (command === COMMAND_CODE.LoginWithAccessToken) {
+ const token = readWireName(payload, 0);
+ return {
+ command: COMMAND_CODE.LoginRegisterWithAccessToken,
+ payload: serializeLoginRegisterWithPat(token.value, SDK_VERSION),
+ };
+ }
+ return { command, payload };
+};
+
+const registerCommand = (command: number): boolean =>
+ command === COMMAND_CODE.LoginRegister ||
+ command === COMMAND_CODE.LoginRegisterWithAccessToken;
+
+const readWireName = (
+ payload: Buffer,
+ offset: number
+): { value: string, next: number } => {
+ if (payload.length <= offset)
+ throw new Error('wire name length is missing');
+ const length = payload.readUInt8(offset);
+ const next = offset + 1 + length;
+ if (length === 0 || payload.length < next)
+ throw new Error('wire name is incomplete');
+ return { value: payload.subarray(offset + 1, next).toString('utf8'), next };
+};
+
+export { HEADER_SIZE } from './header.js';
+export { VsrEvictionError } from './reply.js';
diff --git a/foreign/node/src/wire/vsr/namespace.test.ts b/foreign/node/src/wire/vsr/namespace.test.ts
new file mode 100644
index 000000000..f6939f670
--- /dev/null
+++ b/foreign/node/src/wire/vsr/namespace.test.ts
@@ -0,0 +1,251 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { serializeIdentifier } from '../identifier.utils.js';
+import { serializeSendMessages } from '../message/message.utils.js';
+import { Partitioning } from '../message/partitioning.utils.js';
+import { Consumer, serializeStoreOffset } from '../offset/offset.utils.js';
+import { COMMAND_CODE } from '../command.code.js';
+import { ResponseError } from '../error.utils.js';
+import {
+ METADATA_CONSENSUS_NAMESPACE,
+ namespaceForRequest,
+ packNamespace
+} from './namespace.js';
+import { Operation } from './operation.js';
+
+describe('VSR namespace routing', () => {
+ it('routes register and logout to metadata consensus', () => {
+ for (const operation of [Operation.Register, Operation.Logout])
+ assert.equal(
+ namespaceForRequest(0, Buffer.alloc(0), operation),
+ METADATA_CONSENSUS_NAMESPACE
+ );
+ });
+
+ it('routes metadata and non-replicated requests to zero', () => {
+ assert.equal(
+ namespaceForRequest(
+ COMMAND_CODE.CreateStream,
+ Buffer.alloc(0),
+ Operation.CreateStream
+ ),
+ 0n
+ );
+ assert.equal(
+ namespaceForRequest(
+ COMMAND_CODE.GetStats,
+ Buffer.alloc(0),
+ Operation.NonReplicated
+ ),
+ 0n
+ );
+ });
+
+ it('packs explicit send-message partition identifiers', () => {
+ const payload = serializeSendMessages(
+ 7,
+ 11,
+ [],
+ Partitioning.PartitionId(13)
+ );
+ assert.equal(
+ namespaceForRequest(
+ COMMAND_CODE.SendMessages,
+ payload,
+ Operation.SendMessages
+ ),
+ packNamespace(7, 11, 13)
+ );
+ });
+
+ it('defers named stream and topic routing to the server', () => {
+ const payload = serializeSendMessages(
+ 'stream',
+ 'topic',
+ [],
+ Partitioning.PartitionId(1)
+ );
+ assert.equal(
+ namespaceForRequest(
+ COMMAND_CODE.SendMessages,
+ payload,
+ Operation.SendMessages
+ ),
+ 0n
+ );
+ });
+
+ it('rejects server-selected message partitioning', () => {
+ const payload = serializeSendMessages(
+ 1,
+ 2,
+ [],
+ Partitioning.Balanced
+ );
+ assert.throws(
+ () => namespaceForRequest(
+ COMMAND_CODE.SendMessages,
+ payload,
+ Operation.SendMessages
+ ),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 5
+ );
+ });
+
+ it('routes consumer offsets from their explicit partition', () => {
+ const payload = serializeStoreOffset(
+ 1,
+ 2,
+ Consumer.Single,
+ 3,
+ 99n
+ );
+ assert.equal(
+ namespaceForRequest(
+ COMMAND_CODE.StoreOffset,
+ payload,
+ Operation.StoreConsumerOffset
+ ),
+ packNamespace(1, 2, 3)
+ );
+ });
+
+ it('routes delete-segments payloads', () => {
+ const payload = Buffer.concat([
+ serializeIdentifier(1),
+ serializeIdentifier(2),
+ Buffer.from([3, 0, 0, 0])
+ ]);
+ assert.equal(
+ namespaceForRequest(
+ COMMAND_CODE.DeleteSegments,
+ payload,
+ Operation.DeleteSegments
+ ),
+ packNamespace(1, 2, 3)
+ );
+ });
+
+ it('accepts the maximum packable identifiers', () => {
+ assert.equal(
+ packNamespace(4095, 4095, 999_999),
+ (4095n << 32n) | (4095n << 20n) | 999_999n
+ );
+ });
+
+ it('rejects peeks past the declared send-messages metadata region', () => {
+ const payload = serializeSendMessages(
+ 1,
+ 2,
+ [],
+ Partitioning.PartitionId(3)
+ );
+ const underDeclared = Buffer.from(payload);
+ // Shrink the declared metadata region so the partitioning bytes sit
+ // outside it; the peek must fail instead of reading them.
+ underDeclared.writeUInt32LE(payload.readUInt32LE(0) - 6, 0);
+ assert.throws(
+ () => namespaceForRequest(
+ COMMAND_CODE.SendMessages,
+ underDeclared,
+ Operation.SendMessages
+ ),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 3
+ );
+ });
+
+ it('rejects unknown codes in partition routing', () => {
+ assert.throws(
+ () => namespaceForRequest(
+ 60_001,
+ Buffer.alloc(0),
+ Operation.SendMessages
+ ),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 5
+ );
+ });
+
+ it('requires an explicit consumer-offset partition', () => {
+ const payload = serializeStoreOffset(
+ 1,
+ 2,
+ Consumer.Single,
+ 3,
+ 99n
+ );
+ // [kind u8][consumer 6][stream 6][topic 6] puts the partition flag at 19.
+ const withoutPartition = Buffer.from(payload);
+ withoutPartition.writeUInt8(0, 19);
+ assert.throws(
+ () => namespaceForRequest(
+ COMMAND_CODE.StoreOffset,
+ withoutPartition,
+ Operation.StoreConsumerOffset
+ ),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 6
+ );
+ });
+
+ it('rejects namespace fields before masking', () => {
+ for (const [streamId, topicId, partitionId] of [
+ [4096, 0, 0],
+ [0, 4096, 0],
+ [0, 0, 1_000_000]
+ ] as const)
+ assert.throws(
+ () => packNamespace(streamId, topicId, partitionId),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 6
+ );
+ });
+
+ it('rejects malformed identifiers at every prefix boundary', () => {
+ const payload = serializeSendMessages(
+ 1,
+ 2,
+ [],
+ Partitioning.PartitionId(3)
+ );
+ for (let length = 0; length < payload.length; length += 1)
+ assert.throws(
+ () => namespaceForRequest(
+ COMMAND_CODE.SendMessages,
+ payload.subarray(0, length),
+ Operation.SendMessages
+ ),
+ ResponseError
+ );
+
+ const invalidKind = Buffer.from(payload);
+ invalidKind.writeUInt8(99, 4);
+ assert.throws(
+ () => namespaceForRequest(
+ COMMAND_CODE.SendMessages,
+ invalidKind,
+ Operation.SendMessages
+ ),
+ ResponseError
+ );
+ });
+});
diff --git a/foreign/node/src/wire/vsr/namespace.ts b/foreign/node/src/wire/vsr/namespace.ts
new file mode 100644
index 000000000..a2947b16a
--- /dev/null
+++ b/foreign/node/src/wire/vsr/namespace.ts
@@ -0,0 +1,214 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+/**
+ * Namespace packing and the partition-plane payload peeks needed to derive
+ * it, ported from `core/binary_protocol/src/namespace.rs` and
+ * `namespace_for_request` in `core/sdk/src/vsr.rs`.
+ */
+
+import { COMMAND_CODE } from '../command.code.js';
+import { responseError } from '../error.utils.js';
+import { Operation, isMetadata } from './operation.js';
+
+/** `IggyError::InvalidCommand`. */
+const INVALID_COMMAND = 3;
+/** `IggyError::FeatureUnavailable`. */
+const FEATURE_UNAVAILABLE = 5;
+/** `IggyError::InvalidIdentifier`. */
+const INVALID_IDENTIFIER = 6;
+
+const MAX_STREAMS = 4096;
+const MAX_TOPICS = 4096;
+const MAX_PARTITIONS = 1_000_000;
+const STREAM_SHIFT = 32n;
+const TOPIC_SHIFT = 20n;
+
+/**
+ * Control-plane requests target the metadata replica (shard 0), selected by
+ * this exact sentinel. Plain 0 would fall into namespace hashing and land a
+ * Register on a peer shard.
+ */
+export const METADATA_CONSENSUS_NAMESPACE = 1n << 63n;
+
+/** Packs stream / topic / partition ids into a routing namespace. */
+export const packNamespace = (
+ streamId: number,
+ topicId: number,
+ partitionId: number
+): bigint => {
+ validateField(streamId, MAX_STREAMS);
+ validateField(topicId, MAX_TOPICS);
+ validateField(partitionId, MAX_PARTITIONS);
+ return (BigInt(streamId) << STREAM_SHIFT) |
+ (BigInt(topicId) << TOPIC_SHIFT) |
+ BigInt(partitionId);
+};
+
+/**
+ * Selects the routing namespace for a request. Partition-plane commands
+ * derive it from their own payload; a named stream or topic identifier
+ * yields 0 so the server resolves the name.
+ *
+ * @throws Error mirroring the Rust SDK: invalid-identifier for an
+ * out-of-range field, invalid-command for an undecodable payload, and
+ * feature-unavailable for a partition operation this SDK cannot derive.
+ */
+export const namespaceForRequest = (
+ code: number,
+ payload: Buffer,
+ operation: number
+): bigint => {
+ if (operation === Operation.Register || operation === Operation.Logout)
+ return METADATA_CONSENSUS_NAMESPACE;
+ if (operation === Operation.NonReplicated || isMetadata(operation))
+ return 0n;
+
+ switch (code) {
+ case COMMAND_CODE.SendMessages:
+ return namespaceFromSendMessages(payload);
+ case COMMAND_CODE.StoreOffset:
+ case COMMAND_CODE.DeleteConsumerOffset:
+ case COMMAND_CODE.StoreOffset2:
+ case COMMAND_CODE.DeleteConsumerOffset2:
+ return namespaceFromConsumerOffset(payload);
+ case COMMAND_CODE.DeleteSegments:
+ return namespaceFromDeleteSegments(payload);
+ default:
+ // The guard that keeps custom partition operations unreachable.
+ throw responseError(code, FEATURE_UNAVAILABLE);
+ }
+};
+
+/** A decoded identifier: numeric value, or null for a name (server resolves). */
+type PeekedIdentifier = {
+ numeric: number | null,
+ length: number
+};
+
+const IDENTIFIER_KIND_NUMERIC = 1;
+const IDENTIFIER_KIND_STRING = 2;
+
+const peekIdentifier = (payload: Buffer, offset: number): PeekedIdentifier => {
+ if (payload.length < offset + 2)
+ throw responseError(0, INVALID_COMMAND);
+ const kind = payload.readUInt8(offset);
+ const length = payload.readUInt8(offset + 1);
+ if (payload.length < offset + 2 + length)
+ throw responseError(0, INVALID_COMMAND);
+ if (kind === IDENTIFIER_KIND_NUMERIC) {
+ if (length !== 4)
+ throw responseError(0, INVALID_COMMAND);
+ return { numeric: payload.readUInt32LE(offset + 2), length: 2 + length };
+ }
+ if (kind === IDENTIFIER_KIND_STRING && length > 0)
+ return { numeric: null, length: 2 + length };
+ throw responseError(0, INVALID_COMMAND);
+};
+
+const validateField = (value: number, exclusiveMax: number): void => {
+ if (value >= exclusiveMax)
+ throw responseError(0, INVALID_IDENTIFIER);
+};
+
+const namespaceFromIds = (
+ stream: PeekedIdentifier,
+ topic: PeekedIdentifier,
+ partitionId: number
+): bigint => {
+ // Named identifiers defer resolution to the server.
+ if (stream.numeric === null || topic.numeric === null) return 0n;
+ return packNamespace(stream.numeric, topic.numeric, partitionId);
+};
+
+/**
+ * `SendMessages`: `[metadata_len u32][stream ident][topic ident]
+ * [partitioning kind u8, len u8, value]...`. Only explicit `PartitionId`
+ * partitioning is routable under VSR; the broker never picks a partition.
+ */
+const namespaceFromSendMessages = (payload: Buffer): bigint => {
+ if (payload.length < 4)
+ throw responseError(COMMAND_CODE.SendMessages, INVALID_COMMAND);
+ const metadataLength = payload.readUInt32LE(0);
+ if (payload.length < 4 + metadataLength)
+ throw responseError(COMMAND_CODE.SendMessages, INVALID_COMMAND);
+ // Rust peeks inside payload[4..4 + metadata_length]; a read past the
+ // declared metadata region must fail rather than spill into message bytes
+ // and derive a namespace the server would never compute.
+ const metadata = payload.subarray(4, 4 + metadataLength);
+
+ let offset = 0;
+ const stream = peekIdentifier(metadata, offset);
+ offset += stream.length;
+ const topic = peekIdentifier(metadata, offset);
+ offset += topic.length;
+
+ if (metadata.length < offset + 2)
+ throw responseError(COMMAND_CODE.SendMessages, INVALID_COMMAND);
+ const partitioningKind = metadata.readUInt8(offset);
+ const partitioningLength = metadata.readUInt8(offset + 1);
+ const PARTITIONING_PARTITION_ID = 2;
+ if (partitioningKind !== PARTITIONING_PARTITION_ID)
+ throw responseError(COMMAND_CODE.SendMessages, FEATURE_UNAVAILABLE);
+ if (partitioningLength !== 4 || metadata.length < offset + 2 + 4)
+ throw responseError(COMMAND_CODE.SendMessages, INVALID_COMMAND);
+ const partitionId = metadata.readUInt32LE(offset + 2);
+
+ return namespaceFromIds(stream, topic, partitionId);
+};
+
+/**
+ * Consumer-offset requests: `[consumer kind u8][consumer ident]
+ * [stream ident][topic ident][partition flag u8][partition u32]...`.
+ */
+const namespaceFromConsumerOffset = (payload: Buffer): bigint => {
+ if (payload.length < 1 || (payload.readUInt8(0) !== 1 &&
+ payload.readUInt8(0) !== 2))
+ throw responseError(COMMAND_CODE.StoreOffset, INVALID_COMMAND);
+ let offset = 1;
+ const consumer = peekIdentifier(payload, offset);
+ offset += consumer.length;
+ const stream = peekIdentifier(payload, offset);
+ offset += stream.length;
+ const topic = peekIdentifier(payload, offset);
+ offset += topic.length;
+
+ if (payload.length < offset + 5)
+ throw responseError(COMMAND_CODE.StoreOffset, INVALID_COMMAND);
+ const hasPartition = payload.readUInt8(offset) === 1;
+ if (!hasPartition)
+ throw responseError(COMMAND_CODE.StoreOffset, INVALID_IDENTIFIER);
+ const partitionId = payload.readUInt32LE(offset + 1);
+
+ return namespaceFromIds(stream, topic, partitionId);
+};
+
+/** `DeleteSegments`: `[stream ident][topic ident][partition u32]...`. */
+const namespaceFromDeleteSegments = (payload: Buffer): bigint => {
+ let offset = 0;
+ const stream = peekIdentifier(payload, offset);
+ offset += stream.length;
+ const topic = peekIdentifier(payload, offset);
+ offset += topic.length;
+
+ if (payload.length < offset + 4)
+ throw responseError(COMMAND_CODE.DeleteSegments, INVALID_COMMAND);
+ const partitionId = payload.readUInt32LE(offset);
+
+ return namespaceFromIds(stream, topic, partitionId);
+};
diff --git a/foreign/node/src/wire/vsr/operation.test.ts b/foreign/node/src/wire/vsr/operation.test.ts
new file mode 100644
index 000000000..2189bbe80
--- /dev/null
+++ b/foreign/node/src/wire/vsr/operation.test.ts
@@ -0,0 +1,160 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { BINARY_REQUEST_KIND } from '../command-set.js';
+import { COMMAND_CODE } from '../command.code.js';
+import { ResponseError } from '../error.utils.js';
+import {
+ isInternal,
+ isKnownOperation,
+ isMetadata,
+ isPartition,
+ isResultFramed,
+ Operation,
+ operationForCode
+} from './operation.js';
+
+const replicated = new Map<number, number>([
+ [COMMAND_CODE.CreateStream, Operation.CreateStream],
+ [COMMAND_CODE.UpdateStream, Operation.UpdateStream],
+ [COMMAND_CODE.DeleteStream, Operation.DeleteStream],
+ [COMMAND_CODE.PurgeStream, Operation.PurgeStream],
+ [COMMAND_CODE.CreateTopic, Operation.CreateTopic],
+ [COMMAND_CODE.UpdateTopic, Operation.UpdateTopic],
+ [COMMAND_CODE.DeleteTopic, Operation.DeleteTopic],
+ [COMMAND_CODE.PurgeTopic, Operation.PurgeTopic],
+ [COMMAND_CODE.CreatePartitions, Operation.CreatePartitions],
+ [COMMAND_CODE.DeletePartitions, Operation.DeletePartitions],
+ [COMMAND_CODE.DeleteSegments, Operation.DeleteSegments],
+ [COMMAND_CODE.CreateGroup, Operation.CreateConsumerGroup],
+ [COMMAND_CODE.DeleteGroup, Operation.DeleteConsumerGroup],
+ [COMMAND_CODE.CreateUser, Operation.CreateUser],
+ [COMMAND_CODE.UpdateUser, Operation.UpdateUser],
+ [COMMAND_CODE.DeleteUser, Operation.DeleteUser],
+ [COMMAND_CODE.ChangePassword, Operation.ChangePassword],
+ [COMMAND_CODE.UpdatePermissions, Operation.UpdatePermissions],
+ [COMMAND_CODE.CreateAccessToken, Operation.CreatePersonalAccessToken],
+ [COMMAND_CODE.DeleteAccessToken, Operation.DeletePersonalAccessToken],
+ [COMMAND_CODE.JoinGroup, Operation.JoinConsumerGroup],
+ [COMMAND_CODE.LeaveGroup, Operation.LeaveConsumerGroup],
+ [COMMAND_CODE.SendMessages, Operation.SendMessages],
+ [COMMAND_CODE.StoreOffset, Operation.StoreConsumerOffset],
+ [COMMAND_CODE.DeleteConsumerOffset, Operation.DeleteConsumerOffset],
+ [COMMAND_CODE.StoreOffset2, Operation.StoreConsumerOffset2],
+ [COMMAND_CODE.DeleteConsumerOffset2, Operation.DeleteConsumerOffset2]
+]);
+
+describe('VSR operation classification', () => {
+ it('matches every replicated command operation', () => {
+ for (const [code, operation] of replicated) {
+ assert.equal(operationForCode(code), operation);
+ assert.equal(
+ operationForCode(code, BINARY_REQUEST_KIND.Replicated),
+ operation
+ );
+ }
+ });
+
+ it('classifies every other known command as non-replicated', () => {
+ for (const code of Object.values(COMMAND_CODE)) {
+ if (replicated.has(code) || code === COMMAND_CODE.LogoutUser)
+ continue;
+ assert.equal(operationForCode(code), Operation.NonReplicated);
+ }
+ });
+
+ it('keeps standard command tables authoritative', () => {
+ assert.throws(
+ () => operationForCode(
+ COMMAND_CODE.GetStats,
+ BINARY_REQUEST_KIND.Replicated
+ ),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 3
+ );
+ assert.throws(
+ () => operationForCode(
+ COMMAND_CODE.CreateStream,
+ BINARY_REQUEST_KIND.NonReplicated
+ ),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 3
+ );
+ });
+
+ it('forwards only unknown non-replicated extensions', () => {
+ assert.equal(
+ operationForCode(60_001, BINARY_REQUEST_KIND.NonReplicated),
+ Operation.NonReplicated
+ );
+ assert.throws(
+ () => operationForCode(60_001, BINARY_REQUEST_KIND.Replicated),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 5
+ );
+ assert.throws(
+ () => operationForCode(60_001),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 3
+ );
+ });
+
+ it('routes logout through its consensus operation', () => {
+ assert.equal(operationForCode(COMMAND_CODE.LogoutUser), Operation.Logout);
+ assert.equal(
+ operationForCode(
+ COMMAND_CODE.LogoutUser,
+ BINARY_REQUEST_KIND.Replicated
+ ),
+ Operation.Logout
+ );
+ assert.throws(
+ () => operationForCode(
+ COMMAND_CODE.LogoutUser,
+ BINARY_REQUEST_KIND.NonReplicated
+ ),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 3
+ );
+ });
+
+ it('pins operation class predicates', () => {
+ assert.equal(isInternal(64), true);
+ assert.equal(isInternal(63), false);
+ assert.equal(isInternal(Operation.CreateStream), false);
+ assert.equal(isMetadata(Operation.CreateStream), true);
+ assert.equal(isMetadata(Operation.LeaveConsumerGroup), true);
+ assert.equal(isMetadata(Operation.DeleteSegments), false);
+ assert.equal(isMetadata(150), false);
+ assert.equal(isPartition(Operation.SendMessages), true);
+ assert.equal(isPartition(159), false);
+ assert.equal(isResultFramed(Operation.StoreConsumerOffset), true);
+ assert.equal(isResultFramed(Operation.StoreConsumerOffset2), true);
+ assert.equal(isResultFramed(Operation.DeleteConsumerOffset), true);
+ assert.equal(isResultFramed(Operation.DeleteConsumerOffset2), true);
+ assert.equal(isResultFramed(Operation.SendMessages), false);
+ });
+
+ it('recognizes only declared operation discriminants', () => {
+ assert.equal(isKnownOperation(Operation.Register), true);
+ assert.equal(isKnownOperation(Operation.SendMessages), true);
+ for (const undeclared of [69, 127, 150, 159, 163, 166, 255])
+ assert.equal(isKnownOperation(undeclared), false);
+ });
+});
diff --git a/foreign/node/src/wire/vsr/operation.ts b/foreign/node/src/wire/vsr/operation.ts
new file mode 100644
index 000000000..63f74bdd4
--- /dev/null
+++ b/foreign/node/src/wire/vsr/operation.ts
@@ -0,0 +1,206 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+/**
+ * `Operation` values and classification, ported from
+ * `core/binary_protocol/src/consensus/operation.rs` and the command table in
+ * `core/binary_protocol/src/dispatch.rs`.
+ */
+
+import { COMMAND_CODE } from '../command.code.js';
+import { BINARY_REQUEST_KIND, type BinaryRequestKind } from '../command-set.js';
+import { responseError } from '../error.utils.js';
+
+/** `Operation` discriminants a client sends or receives. */
+export const Operation = {
+ Reserved: 0,
+ Register: 1,
+ NonReplicated: 2,
+ Logout: 3,
+ CreateTopicWithAssignments: 64,
+ CreatePartitionsWithAssignments: 65,
+ RemoveConsumerGroupMember: 66,
+ CompleteConsumerGroupRevocation: 67,
+ TruncatePartition: 68,
+ CreateStream: 128,
+ UpdateStream: 129,
+ DeleteStream: 130,
+ PurgeStream: 131,
+ CreateTopic: 132,
+ UpdateTopic: 133,
+ DeleteTopic: 134,
+ PurgeTopic: 135,
+ CreatePartitions: 136,
+ DeletePartitions: 137,
+ DeleteSegments: 138,
+ CreateConsumerGroup: 139,
+ DeleteConsumerGroup: 140,
+ CreateUser: 141,
+ UpdateUser: 142,
+ DeleteUser: 143,
+ ChangePassword: 144,
+ UpdatePermissions: 145,
+ CreatePersonalAccessToken: 146,
+ DeletePersonalAccessToken: 147,
+ JoinConsumerGroup: 148,
+ LeaveConsumerGroup: 149,
+ SendMessages: 160,
+ StoreConsumerOffset: 161,
+ DeleteConsumerOffset: 162,
+ StoreConsumerOffset2: 164,
+ DeleteConsumerOffset2: 165
+} as const;
+
+const INTERNAL_START = 64;
+const METADATA_START = 128;
+const PARTITION_START = 160;
+
+/** `IggyError::InvalidCommand` numeric code. */
+export const ERROR_CODE_INVALID_COMMAND = 3;
+/** `IggyError::FeatureUnavailable` numeric code. */
+export const ERROR_CODE_FEATURE_UNAVAILABLE = 5;
+
+/**
+ * Replicated command code to `Operation` mapping, the client half of the
+ * dispatch table. Codes absent here are non-replicated when the classic
+ * command set knows them, unknown otherwise.
+ */
+const REPLICATED_OPERATION: ReadonlyMap<number, number> = new Map([
+ [COMMAND_CODE.CreateUser, Operation.CreateUser],
+ [COMMAND_CODE.DeleteUser, Operation.DeleteUser],
+ [COMMAND_CODE.UpdateUser, Operation.UpdateUser],
+ [COMMAND_CODE.UpdatePermissions, Operation.UpdatePermissions],
+ [COMMAND_CODE.ChangePassword, Operation.ChangePassword],
+ [COMMAND_CODE.CreateAccessToken, Operation.CreatePersonalAccessToken],
+ [COMMAND_CODE.DeleteAccessToken, Operation.DeletePersonalAccessToken],
+ [COMMAND_CODE.SendMessages, Operation.SendMessages],
+ [COMMAND_CODE.StoreOffset, Operation.StoreConsumerOffset],
+ [COMMAND_CODE.DeleteConsumerOffset, Operation.DeleteConsumerOffset],
+ [COMMAND_CODE.StoreOffset2, Operation.StoreConsumerOffset2],
+ [COMMAND_CODE.DeleteConsumerOffset2, Operation.DeleteConsumerOffset2],
+ [COMMAND_CODE.CreateStream, Operation.CreateStream],
+ [COMMAND_CODE.DeleteStream, Operation.DeleteStream],
+ [COMMAND_CODE.UpdateStream, Operation.UpdateStream],
+ [COMMAND_CODE.PurgeStream, Operation.PurgeStream],
+ [COMMAND_CODE.CreateTopic, Operation.CreateTopic],
+ [COMMAND_CODE.DeleteTopic, Operation.DeleteTopic],
+ [COMMAND_CODE.UpdateTopic, Operation.UpdateTopic],
+ [COMMAND_CODE.PurgeTopic, Operation.PurgeTopic],
+ [COMMAND_CODE.CreatePartitions, Operation.CreatePartitions],
+ [COMMAND_CODE.DeletePartitions, Operation.DeletePartitions],
+ [COMMAND_CODE.DeleteSegments, Operation.DeleteSegments],
+ [COMMAND_CODE.CreateGroup, Operation.CreateConsumerGroup],
+ [COMMAND_CODE.DeleteGroup, Operation.DeleteConsumerGroup],
+ [COMMAND_CODE.JoinGroup, Operation.JoinConsumerGroup],
+ [COMMAND_CODE.LeaveGroup, Operation.LeaveConsumerGroup]
+]);
+
+/** Classic command codes known to the SDK. */
+const KNOWN_COMMAND_CODES: ReadonlySet<number> =
+ new Set(Object.values(COMMAND_CODE));
+
+const KNOWN_OPERATIONS: ReadonlySet<number> =
+ new Set(Object.values(Operation));
+
+/**
+ * Whether the byte is a declared `Operation` discriminant. Replies carry a
+ * server-controlled operation byte; Rust validates it with a checked cast,
+ * so an undeclared value must be rejected, not classified by range.
+ */
+export const isKnownOperation = (operation: number): boolean =>
+ KNOWN_OPERATIONS.has(operation);
+
+/** Internal band, never client-sent. */
+export const isInternal = (operation: number): boolean =>
+ operation >= INTERNAL_START && operation < METADATA_START;
+
+/**
+ * Metadata classification is an explicit allowlist, not a range:
+ * `DeleteSegments` (138) sits inside the band but resolves to a partition
+ * truncation server-side, so it is deliberately excluded. Port of
+ * `Operation::is_metadata`.
+ */
+export const isMetadata = (operation: number): boolean => {
+ if (isInternal(operation)) return true;
+ if (operation === Operation.DeleteSegments) return false;
+ return operation >= METADATA_START &&
+ operation <= Operation.LeaveConsumerGroup;
+};
+
+/** Partition band is a bare range, mirroring `Operation::is_partition`. */
+export const isPartition = (operation: number): boolean =>
+ operation >= PARTITION_START;
+
+/** Whether a reply body leads with a committed result section. */
+export const isResultFramed = (operation: number): boolean =>
+ isMetadata(operation) ||
+ operation === Operation.StoreConsumerOffset ||
+ operation === Operation.StoreConsumerOffset2 ||
+ operation === Operation.DeleteConsumerOffset ||
+ operation === Operation.DeleteConsumerOffset2;
+
+/**
+ * Picks the header operation for a command code, honoring the caller's
+ * declaration only where the protocol tables have nothing to say. Standard
+ * codes resolve first so a caller cannot redirect a shipped command into the
+ * other execution model. Port of `operation_for_code` in
+ * `core/sdk/src/vsr.rs`, extended with the raw declaration rules for
+ * unknown extension codes.
+ *
+ * @throws Error with the invalid-command code for a conflicting declaration
+ * or an undeclared unknown code, and feature-unavailable for an unknown
+ * code declared replicated.
+ */
+export const operationForCode = (
+ code: number,
+ kind?: BinaryRequestKind
+): number => {
+ // The dispatch table files logout as non-replicated, but VSR routes it
+ // through its own consensus operation; the raw API blocks code 39 before
+ // classification, so only the typed logout path reaches this branch.
+ if (code === COMMAND_CODE.LogoutUser)
+ return acceptDeclaration(code, Operation.Logout, kind);
+
+ const replicated = REPLICATED_OPERATION.get(code);
+ if (replicated !== undefined)
+ return acceptDeclaration(code, replicated, kind);
+
+ if (KNOWN_COMMAND_CODES.has(code))
+ return acceptDeclaration(code, Operation.NonReplicated, kind);
+
+ if (kind === BINARY_REQUEST_KIND.NonReplicated)
+ return Operation.NonReplicated;
+ if (kind === BINARY_REQUEST_KIND.Replicated)
+ // A replicated extension needs a server-side handler registry that does
+ // not exist yet; failing closed beats a half-supported frame.
+ throw responseError(code, ERROR_CODE_FEATURE_UNAVAILABLE);
+ throw responseError(code, ERROR_CODE_INVALID_COMMAND);
+};
+
+const acceptDeclaration = (
+ code: number,
+ operation: number,
+ kind?: BinaryRequestKind
+): number => {
+ if (kind === undefined) return operation;
+ const standard = operation === Operation.NonReplicated ?
+ BINARY_REQUEST_KIND.NonReplicated :
+ BINARY_REQUEST_KIND.Replicated;
+ if (kind === standard) return operation;
+ throw responseError(code, ERROR_CODE_INVALID_COMMAND);
+};
diff --git a/foreign/node/src/wire/vsr/register.test.ts b/foreign/node/src/wire/vsr/register.test.ts
new file mode 100644
index 000000000..bb6fdba3f
--- /dev/null
+++ b/foreign/node/src/wire/vsr/register.test.ts
@@ -0,0 +1,93 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import {
+ deserializeLoginRegister,
+ IGGY_PROTOCOL_VERSION,
+ serializeLoginRegister,
+ serializeLoginRegisterWithPat
+} from './register.js';
+
+describe('VSR register payloads', () => {
+ it('encodes protocol, SDK, credentials, and empty context', () => {
+ const body = serializeLoginRegister('iggy', 'secret', '0.8.1-edge.3');
+ assert.equal(body.readUInt32LE(0), IGGY_PROTOCOL_VERSION);
+ assert.match(body.toString('utf8'), /node-sdk/);
+ assert.match(body.toString('utf8'), /0\.8\.1-edge\.3/);
+ assert.match(body.toString('utf8'), /iggy/);
+ assert.match(body.toString('utf8'), /secret/);
+ assert.equal(body.readUInt32LE(body.length - 4), 0);
+ });
+
+ it('uses UTF-8 byte lengths and enforces one-byte bounds', () => {
+ const body = serializeLoginRegister('żółw', 'hasło', '版本');
+ assert.equal(body.readUInt8(4), Buffer.byteLength('node-sdk'));
+ assert.match(body.toString('utf8'), /żółw/);
+ assert.throws(
+ () => serializeLoginRegister('', 'secret', '1.0.0'),
+ /1\.\.255 bytes/
+ );
+ assert.throws(
+ () => serializeLoginRegister('x'.repeat(256), 'secret', '1.0.0'),
+ /1\.\.255 bytes/
+ );
+ const maximum = serializeLoginRegister(
+ 'x'.repeat(255),
+ 'secret',
+ '1.0.0'
+ );
+ assert.match(maximum.toString('utf8'), /x{255}/);
+ });
+
+ it('encodes PAT registration and rejects oversized tokens', () => {
+ const body = serializeLoginRegisterWithPat('token', '0.8.1-edge.3');
+ assert.match(body.toString('utf8'), /token/);
+ assert.throws(
+ () => serializeLoginRegisterWithPat('x'.repeat(256), '0.8.1-edge.3'),
+ /token exceeds/
+ );
+ });
+
+ it('decodes a complete login response', () => {
+ const version = Buffer.from('0.10.3');
+ const body = Buffer.alloc(17 + version.length);
+ body.writeUInt32LE(7, 0);
+ body.writeBigUInt64LE(42n, 4);
+ body.writeUInt32LE(IGGY_PROTOCOL_VERSION, 12);
+ body.writeUInt8(version.length, 16);
+ version.copy(body, 17);
+ assert.deepEqual(deserializeLoginRegister(body), {
+ userId: 7,
+ session: 42n,
+ serverProtocolVersion: IGGY_PROTOCOL_VERSION,
+ serverVersion: '0.10.3'
+ });
+ });
+
+ it('rejects every truncated fixed response and variable tail', () => {
+ for (let length = 0; length < 17; length += 1)
+ assert.throws(
+ () => deserializeLoginRegister(Buffer.alloc(length)),
+ /too short/
+ );
+ const body = Buffer.alloc(17);
+ body.writeUInt8(1, 16);
+ assert.throws(() => deserializeLoginRegister(body), /truncated/);
+ });
+});
diff --git a/foreign/node/src/wire/vsr/register.ts b/foreign/node/src/wire/vsr/register.ts
new file mode 100644
index 000000000..ba8a198ec
--- /dev/null
+++ b/foreign/node/src/wire/vsr/register.ts
@@ -0,0 +1,116 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+/**
+ * The Register (login) handshake bodies and reply, ported from
+ * `core/binary_protocol/src/requests/users/login_register.rs` and
+ * `responses/users/login_register.rs`. The VSR server rejects the legacy login
+ * codes with a `MalformedLogin` eviction, so a VSR client must emit
+ * `LoginRegister` / `LoginRegisterWithPat` and nothing else.
+ */
+
+import { DeserializeError } from '../error.utils.js';
+
+/**
+ * Packed protocol semver of the wire contract this port implements,
+ * `pack(0, 10, 3)` per `core/binary_protocol/src/version.rs`. Bump together
+ * with the Rust `IGGY_PROTOCOL_VERSION` on any wire-incompatible change.
+ */
+export const IGGY_PROTOCOL_VERSION = (0 << 20) | (10 << 10) | 3;
+
+const SDK_NAME = 'node-sdk';
+
+const wireName = (value: string): Buffer => {
+ const bytes = Buffer.from(value, 'utf8');
+ if (bytes.length < 1 || bytes.length > 255)
+ throw new Error(`wire name must be 1..255 bytes, got ${bytes.length}`);
+ return Buffer.concat([Buffer.from([bytes.length]), bytes]);
+};
+
+const versionInfo = (sdkVersion: string): Buffer => {
+ const version = Buffer.alloc(4);
+ version.writeUInt32LE(IGGY_PROTOCOL_VERSION);
+ return Buffer.concat([version, wireName(SDK_NAME), wireName(sdkVersion)]);
+};
+
+/**
+ * `LoginRegisterRequest` body:
+ * `[ClientVersionInfo][username len u8 + bytes][password len u8 + bytes]
+ * [context len u32][context]`.
+ */
+export const serializeLoginRegister = (
+ username: string,
+ password: string,
+ sdkVersion: string
+): Buffer => {
+ const passwordBytes = Buffer.from(password, 'utf8');
+ if (passwordBytes.length > 255)
+ throw new Error('password exceeds the u8 length prefix');
+ return Buffer.concat([
+ versionInfo(sdkVersion),
+ wireName(username),
+ Buffer.from([passwordBytes.length]),
+ passwordBytes,
+ Buffer.alloc(4)
+ ]);
+};
+
+/** `LoginRegisterWithPatRequest` body: the PAT takes the credential slot. */
+export const serializeLoginRegisterWithPat = (
+ token: string,
+ sdkVersion: string
+): Buffer => {
+ const tokenBytes = Buffer.from(token, 'utf8');
+ if (tokenBytes.length > 255)
+ throw new Error('token exceeds the u8 length prefix');
+ return Buffer.concat([
+ versionInfo(sdkVersion),
+ Buffer.from([tokenBytes.length]),
+ tokenBytes,
+ Buffer.alloc(4)
+ ]);
+};
+
+/** Decoded `LoginRegisterResponse`. */
+export type LoginRegisterResponse = {
+ userId: number,
+ session: bigint,
+ serverProtocolVersion: number,
+ serverVersion: string
+};
+
+/**
+ * `[user_id u32][session u64][server_protocol_version u32]
+ * [server_version len u8 + bytes]`.
+ */
+export const deserializeLoginRegister = (
+ body: Buffer
+): LoginRegisterResponse => {
+ if (body.length < 17)
+ throw new DeserializeError(
+ `login register response too short: ${body.length} bytes`);
+ const versionLength = body.readUInt8(16);
+ if (body.length < 17 + versionLength)
+ throw new DeserializeError('login register response truncated');
+ return {
+ userId: body.readUInt32LE(0),
+ session: body.readBigUInt64LE(4),
+ serverProtocolVersion: body.readUInt32LE(12),
+ serverVersion: body.subarray(17, 17 + versionLength).toString('utf8')
+ };
+};
diff --git a/foreign/node/src/wire/vsr/reply.test.ts b/foreign/node/src/wire/vsr/reply.test.ts
new file mode 100644
index 000000000..3fee8f07f
--- /dev/null
+++ b/foreign/node/src/wire/vsr/reply.test.ts
@@ -0,0 +1,177 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { ResponseError } from '../error.utils.js';
+import {
+ Command2,
+ EVICTION_OFFSET,
+ EvictionReason,
+ HEADER_SIZE,
+ REPLY_OFFSET
+} from './header.js';
+import { Operation } from './operation.js';
+import {
+ decodeResponse,
+ splitMetadataResult,
+ VsrEvictionError
+} from './reply.js';
+
+const reply = (
+ operation: number,
+ body = Buffer.alloc(0),
+ status = 0
+): Buffer => {
+ const frame = Buffer.alloc(HEADER_SIZE + body.length);
+ frame.writeUInt32LE(frame.length, REPLY_OFFSET.size);
+ frame.writeUInt8(Command2.Reply, REPLY_OFFSET.command);
+ frame.writeUInt8(operation, REPLY_OFFSET.operation);
+ frame.writeUInt32LE(status, REPLY_OFFSET.status);
+ body.copy(frame, HEADER_SIZE);
+ return frame;
+};
+
+const eviction = (reason: number): Buffer => {
+ const frame = Buffer.alloc(HEADER_SIZE);
+ frame.writeUInt32LE(HEADER_SIZE, REPLY_OFFSET.size);
+ frame.writeUInt8(Command2.Eviction, REPLY_OFFSET.command);
+ frame.writeUInt8(reason, EVICTION_OFFSET.reason);
+ return frame;
+};
+
+describe('VSR reply decoding', () => {
+ it('rejects truncated, undersized, and unsupported frames', () => {
+ assert.throws(() => decodeResponse(Buffer.alloc(255)), ResponseError);
+
+ const undersized = reply(Operation.NonReplicated);
+ undersized.writeUInt32LE(1, REPLY_OFFSET.size);
+ assert.throws(() => decodeResponse(undersized), ResponseError);
+
+ const unsupported = reply(Operation.NonReplicated);
+ unsupported.writeUInt8(Command2.Request, REPLY_OFFSET.command);
+ assert.throws(() => decodeResponse(unsupported), ResponseError);
+ });
+
+ it('rejects a declared size beyond the received bytes', () => {
+ const frame = reply(Operation.NonReplicated);
+ frame.writeUInt32LE(HEADER_SIZE + 1, REPLY_OFFSET.size);
+ assert.throws(() => decodeResponse(frame), ResponseError);
+ });
+
+ it('rejects an undeclared reply operation discriminant', () => {
+ for (const operation of [69, 150, 163, 255])
+ assert.throws(
+ () => decodeResponse(reply(operation)),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 3
+ );
+ });
+
+ it('passes an empty register body through as a terminal failure', () => {
+ assert.deepEqual(
+ decodeResponse(reply(Operation.Register)),
+ Buffer.alloc(0)
+ );
+ const committed = Buffer.concat([Buffer.alloc(4), Buffer.from('ok')]);
+ assert.deepEqual(
+ decodeResponse(reply(Operation.Register, committed)),
+ Buffer.from('ok')
+ );
+ });
+
+ it('returns only the declared body and ignores a following frame', () => {
+ const first = reply(Operation.NonReplicated, Buffer.from('one'));
+ const second = reply(Operation.NonReplicated, Buffer.from('two'));
+ assert.deepEqual(
+ decodeResponse(Buffer.concat([first, second])),
+ Buffer.from('one')
+ );
+ });
+
+ it('surfaces pre-commit status before decoding the body', () => {
+ assert.throws(
+ () => decodeResponse(reply(Operation.CreateStream, Buffer.alloc(0), 57)),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 57
+ );
+ });
+
+ it('strips a successful result section', () => {
+ const body = Buffer.concat([Buffer.alloc(4), Buffer.from('stream')]);
+ assert.deepEqual(
+ decodeResponse(reply(Operation.CreateStream, body)),
+ Buffer.from('stream')
+ );
+ });
+
+ it('surfaces the first committed result error', () => {
+ const body = Buffer.alloc(20);
+ body.writeUInt32LE(2, 0);
+ body.writeUInt32LE(7, 4);
+ body.writeUInt32LE(1009, 8);
+ body.writeUInt32LE(8, 12);
+ body.writeUInt32LE(1010, 16);
+ assert.throws(
+ () => splitMetadataResult(Operation.CreateStream, body),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 1009
+ );
+ });
+
+ it('rejects truncated result sections', () => {
+ assert.throws(
+ () => splitMetadataResult(Operation.CreateStream, Buffer.alloc(3)),
+ ResponseError
+ );
+ const body = Buffer.alloc(4);
+ body.writeUInt32LE(1, 0);
+ assert.throws(
+ () => splitMetadataResult(Operation.CreateStream, body),
+ ResponseError
+ );
+ });
+
+ it('maps every eviction reason to a terminal eviction error', () => {
+ for (const reason of Object.values(EvictionReason)) {
+ const frame = eviction(reason);
+ if (reason === EvictionReason.IncompatibleProtocol) {
+ frame.writeUInt32LE((0 << 20) | (10 << 10) | 3, 144);
+ frame.writeUInt32LE(10 << 10, 148);
+ }
+ assert.throws(
+ () => decodeResponse(frame),
+ VsrEvictionError
+ );
+ }
+ assert.throws(
+ () => decodeResponse(eviction(255)),
+ VsrEvictionError
+ );
+ });
+
+ it('rejects malformed incompatible-protocol windows safely', () => {
+ const frame = eviction(EvictionReason.IncompatibleProtocol);
+ frame.writeUInt32LE(1, 144);
+ frame.writeUInt32LE(2, 148);
+ assert.throws(
+ () => decodeResponse(frame),
+ (error: unknown) =>
+ error instanceof VsrEvictionError && error.errorCode === 40
+ );
+ });
+});
diff --git a/foreign/node/src/wire/vsr/reply.ts b/foreign/node/src/wire/vsr/reply.ts
new file mode 100644
index 000000000..59e242b1e
--- /dev/null
+++ b/foreign/node/src/wire/vsr/reply.ts
@@ -0,0 +1,165 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+/**
+ * Reply decode funnel, ported from `decode_response` in
+ * `core/sdk/src/vsr.rs`. Strict order: frame length, frame discriminant
+ * (evictions surface as typed errors, never a read timeout), declared size,
+ * pre-commit denial status before any body decode, then the committed
+ * result section for result-framed operations.
+ */
+
+import { ResponseError, responseError } from '../error.utils.js';
+import {
+ Command2, EvictionReason, HEADER_SIZE,
+ peekCommand, readEviction, readReplyOperation, readSize, readStatus
+} from './header.js';
+import { Operation, isKnownOperation, isResultFramed } from './operation.js';
+
+/** `IggyError` codes this funnel raises client-side. */
+const INVALID_COMMAND = 3;
+const UNAUTHENTICATED = 40;
+const INVALID_CREDENTIALS = 42;
+const INVALID_PERSONAL_ACCESS_TOKEN = 53;
+const STALE_CLIENT = 30;
+const INVALID_FORMAT = 4;
+const EMPTY_RESPONSE = 304;
+const INCOMPATIBLE_PROTOCOL_VERSION = 14003;
+
+const RESULT_COUNT_LEN = 4;
+const RESULT_ENTRY_LEN = 8;
+
+export class VsrEvictionError extends ResponseError {
+ constructor(errorCode: number) {
+ super(0, errorCode);
+ this.name = 'VsrEvictionError';
+ Object.setPrototypeOf(this, VsrEvictionError.prototype);
+ }
+}
+
+/**
+ * Decodes one complete consensus frame into the reply body, stripping the
+ * committed result section for result-framed operations and mapping every
+ * denial channel to a thrown error.
+ */
+export const decodeResponse = (frame: Buffer): Buffer => {
+ if (frame.length < HEADER_SIZE)
+ throw responseError(0, EMPTY_RESPONSE);
+
+ switch (peekCommand(frame)) {
+ case Command2.Eviction:
+ throw evictionError(frame);
+ case Command2.Reply:
+ break;
+ default:
+ throw responseError(0, INVALID_COMMAND);
+ }
+
+ const size = readSize(frame);
+ if (size < HEADER_SIZE || frame.length < size)
+ throw responseError(0, INVALID_COMMAND);
+
+ const status = readStatus(frame);
+ // A pre-commit denial always ships an empty body; the status channel and
+ // the committed result section are mutually exclusive.
+ if (status !== 0)
+ throw responseError(0, status);
+
+ const operation = readReplyOperation(frame);
+ if (!isKnownOperation(operation))
+ throw responseError(0, INVALID_COMMAND);
+ const body = frame.subarray(HEADER_SIZE, size);
+ return splitMetadataResult(operation, body);
+};
+
+/**
+ * Strips the committed result section leading a result-framed reply body.
+ * A Register reply is result-framed too, except a terminal register failure
+ * ships an empty body, passed through so the typed decode fails. A metadata
+ * body too short for the entries its count claims is corruption, never a
+ * silent success.
+ */
+export const splitMetadataResult = (
+ operation: number,
+ body: Buffer
+): Buffer => {
+ const resultFramed = isResultFramed(operation) ||
+ (operation === Operation.Register && body.length > 0);
+ if (!resultFramed) return body;
+
+ if (body.length < RESULT_COUNT_LEN)
+ throw responseError(0, INVALID_COMMAND);
+ const count = body.readUInt32LE(0);
+ const sectionLength = RESULT_COUNT_LEN + count * RESULT_ENTRY_LEN;
+ if (body.length < sectionLength)
+ throw responseError(0, INVALID_COMMAND);
+ if (count === 0)
+ return body.subarray(RESULT_COUNT_LEN);
+ // First entry: {index u32, result u32}; result shares the IggyError space.
+ const code = body.readUInt32LE(RESULT_COUNT_LEN + 4);
+ throw responseError(0, code);
+};
+
+/**
+ * Maps a session-terminal eviction frame to a typed error, the same mapping
+ * as `eviction_reason_to_error` in `core/common`. An invalid protocol window
+ * degrades to an authentication error rather than trusting the remote frame.
+ */
+export const evictionError = (frame: Buffer): Error => {
+ const eviction = readEviction(frame);
+ let errorCode: number;
+ switch (eviction.reason) {
+ case EvictionReason.InvalidCredentials:
+ errorCode = INVALID_CREDENTIALS;
+ break;
+ case EvictionReason.InvalidToken:
+ errorCode = INVALID_PERSONAL_ACCESS_TOKEN;
+ break;
+ case EvictionReason.UserInactive:
+ case EvictionReason.SessionError:
+ case EvictionReason.NoSession:
+ case EvictionReason.SessionTooLow:
+ case EvictionReason.SessionReleaseMismatch:
+ errorCode = UNAUTHENTICATED;
+ break;
+ case EvictionReason.StaleClient:
+ errorCode = STALE_CLIENT;
+ break;
+ case EvictionReason.IncompatibleProtocol:
+ if (eviction.serverProtocolVersionMin === 0 ||
+ eviction.serverProtocolVersion < eviction.serverProtocolVersionMin)
+ errorCode = UNAUTHENTICATED;
+ else
+ errorCode = INCOMPATIBLE_PROTOCOL_VERSION;
+ break;
+ case EvictionReason.MalformedLogin:
+ errorCode = INVALID_FORMAT;
+ break;
+ case EvictionReason.Reserved:
+ case EvictionReason.ClientReleaseTooLow:
+ case EvictionReason.ClientReleaseTooHigh:
+ case EvictionReason.InvalidRequestOperation:
+ case EvictionReason.InvalidRequestBody:
+ case EvictionReason.InvalidRequestBodySize:
+ errorCode = INVALID_COMMAND;
+ break;
+ default:
+ errorCode = UNAUTHENTICATED;
+ }
+ return new VsrEvictionError(errorCode);
+};
diff --git a/foreign/node/src/wire/vsr/session.test.ts b/foreign/node/src/wire/vsr/session.test.ts
new file mode 100644
index 000000000..62a82a216
--- /dev/null
+++ b/foreign/node/src/wire/vsr/session.test.ts
@@ -0,0 +1,57 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { ConsensusSession } from './session.js';
+
+describe('ConsensusSession', () => {
+ it('starts unbound with a nonzero client ID', () => {
+ const session = new ConsensusSession();
+ assert.notEqual(session.clientId, 0n);
+ assert.equal(session.session, null);
+ assert.equal(session.currentRequestId(), 1n);
+ });
+
+ it('binds once to a positive server session', () => {
+ const session = new ConsensusSession(7n);
+ session.beginRegister();
+ assert.throws(() => session.bind(0n), /must be > 0/);
+ session.bind(42n);
+ assert.equal(session.session, 42n);
+ assert.throws(() => session.bind(43n), /already bound/);
+ });
+
+ it('advances metadata IDs monotonically', () => {
+ const session = new ConsensusSession(7n);
+ session.beginRegister();
+ session.bind(42n);
+ assert.equal(session.nextRequestId(), 1n);
+ assert.equal(session.nextRequestId(), 2n);
+ assert.equal(session.currentRequestId(), 3n);
+ });
+
+ it('rearms registration with a fresh client ID', () => {
+ const session = new ConsensusSession(7n);
+ session.beginRegister();
+ session.bind(42n);
+ session.beginRegister();
+ assert.equal(session.session, null);
+ assert.equal(session.currentRequestId(), 1n);
+ assert.notEqual(session.clientId, 7n);
+ });
+});
diff --git a/foreign/node/src/wire/vsr/session.ts b/foreign/node/src/wire/vsr/session.ts
new file mode 100644
index 000000000..cb2339b41
--- /dev/null
+++ b/foreign/node/src/wire/vsr/session.ts
@@ -0,0 +1,113 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+import { randomBytes } from 'node:crypto';
+
+const MAX_U64 = 0xFFFF_FFFF_FFFF_FFFFn;
+
+/**
+ * Consensus-level session state, ported from `core/sdk/src/session.rs`.
+ *
+ * Each client instance generates an ephemeral random `clientId` (u128).
+ * After a Register commits, the server assigns a `session` number (commit op
+ * number). Replicated metadata requests advance a monotonic request id;
+ * non-replicated and partition-plane requests read the current id without
+ * advancing it, because the server's `ClientTable` only tracks ids for
+ * replicated metadata ops and a consumed id would gap the next one, which the
+ * primary silently drops (`RequestGap`).
+ */
+export class ConsensusSession {
+ private _clientId: bigint;
+ private _session: bigint | null;
+ private requestCounter: bigint;
+ private registerConsumed: boolean;
+
+ constructor(clientId?: bigint) {
+ this._clientId = clientId ?? generateClientId();
+ this._session = null;
+ this.requestCounter = 1n;
+ this.registerConsumed = false;
+ }
+
+ get clientId(): bigint {
+ return this._clientId;
+ }
+
+ /** The bound session number, or null before Register commits. */
+ get session(): bigint | null {
+ return this._session;
+ }
+
+ get isBound(): boolean {
+ return this._session !== null;
+ }
+
+ /** Binds the session after Register commits through consensus. */
+ bind(session: bigint): void {
+ if (this._session !== null)
+ throw new Error(`session already bound (session=${this._session})`);
+ if (session <= 0n)
+ throw new Error('session must be > 0');
+ this._session = session;
+ }
+
+ /**
+ * Begins a registration, re-arming the session for a re-login. A prior
+ * consumed or bound session is replaced wholesale (fresh client id,
+ * unbound), so a repeat login encodes a clean Register instead of tripping
+ * the one-shot guard. Returns the register request id, always 0.
+ */
+ beginRegister(): bigint {
+ if (this.registerConsumed || this.isBound) {
+ this._clientId = generateClientId();
+ this._session = null;
+ this.requestCounter = 1n;
+ this.registerConsumed = false;
+ }
+ this.registerConsumed = true;
+ return 0n;
+ }
+
+ /**
+ * Next application request id, advancing the counter: 1, 2, 3, ...
+ * Request 0 is reserved for Register.
+ */
+ nextRequestId(): bigint {
+ if (!this.isBound)
+ throw new Error('nextRequestId called before bind');
+ if (this.requestCounter === MAX_U64)
+ throw new RangeError('VSR request counter exhausted');
+ const id = this.requestCounter;
+ this.requestCounter += 1n;
+ return id;
+ }
+
+ /** Current counter value without advancing it. */
+ currentRequestId(): bigint {
+ return this.requestCounter;
+ }
+}
+
+/** Ephemeral random u128, non-zero (retry on the astronomically unlikely 0). */
+const generateClientId = (): bigint => {
+ for (;;) {
+ const id = randomBytes(16).reduce(
+ (acc, byte) => (acc << 8n) | BigInt(byte), 0n);
+ if (id !== 0n) return id;
+ }
+};
diff --git a/foreign/node/src/wire/vsr/vsr.test.ts b/foreign/node/src/wire/vsr/vsr.test.ts
new file mode 100644
index 000000000..2df7b6326
--- /dev/null
+++ b/foreign/node/src/wire/vsr/vsr.test.ts
@@ -0,0 +1,110 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+import { describe, it } from 'node:test';
+import assert from 'node:assert/strict';
+import { BINARY_REQUEST_KIND } from '../command-set.js';
+import { ResponseError } from '../error.utils.js';
+import { HEADER_SIZE, REQUEST_OFFSET } from './header.js';
+import { prepareVsrCommand, VsrSession } from './index.js';
+import { Operation } from './operation.js';
+import { COMMAND_CODE } from '../command.code.js';
+
+describe('VSR custom request framing', () => {
+ it('encodes a custom non-replicated code and opaque payload', () => {
+ const session = new VsrSession();
+ const payload = Buffer.from([0xAA, 0xBB, 0xCC]);
+ const frame = session.encode(
+ 60_000,
+ payload,
+ BINARY_REQUEST_KIND.NonReplicated
+ );
+
+ assert.equal(frame.readUInt8(REQUEST_OFFSET.operation), Operation.NonReplicated);
+ assert.equal(frame.readUInt32LE(REQUEST_OFFSET.reserved), 60_000);
+ assert.deepEqual(frame.subarray(256), payload);
+ });
+
+ it('rejects a custom replicated code without a server registry', () => {
+ const session = new VsrSession();
+ assert.throws(
+ () => session.encode(
+ 60_000,
+ Buffer.alloc(0),
+ BINARY_REQUEST_KIND.Replicated
+ ),
+ /Feature is unavailable/
+ );
+ });
+
+ it('does not consume a request ID when local routing fails', () => {
+ const session = new VsrSession(7n);
+ session.bind(42n);
+ assert.throws(
+ () => session.encode(
+ COMMAND_CODE.SendMessages,
+ Buffer.alloc(0)
+ )
+ );
+
+ const frame = session.encode(
+ COMMAND_CODE.CreateStream,
+ Buffer.alloc(0)
+ );
+ assert.equal(frame.readBigUInt64LE(REQUEST_OFFSET.request), 1n);
+ });
+
+ it('rejects an unbound replicated request with a typed error', () => {
+ const session = new VsrSession();
+ assert.throws(
+ () => session.encode(COMMAND_CODE.CreateStream, Buffer.alloc(0)),
+ (error: unknown) =>
+ error instanceof ResponseError && error.errorCode === 40
+ );
+ });
+
+ it('rejects a truncated legacy login payload locally', () => {
+ assert.throws(
+ () => prepareVsrCommand(COMMAND_CODE.LoginUser, Buffer.alloc(0))
+ );
+ assert.throws(
+ () => prepareVsrCommand(
+ COMMAND_CODE.LoginUser,
+ Buffer.from([4, 0x69, 0x67])
+ )
+ );
+ });
+
+ it('does not advance for non-replicated or partition operations', () => {
+ const session = new VsrSession(7n);
+ session.bind(42n);
+ const custom = session.encode(
+ 60_001,
+ Buffer.alloc(0),
+ BINARY_REQUEST_KIND.NonReplicated
+ );
+ assert.equal(custom.readBigUInt64LE(REQUEST_OFFSET.request), 1n);
+
+ const metadata = session.encode(
+ COMMAND_CODE.CreateStream,
+ Buffer.alloc(0)
+ );
+ assert.equal(metadata.readBigUInt64LE(REQUEST_OFFSET.request), 1n);
+ assert.equal(metadata.length, HEADER_SIZE);
+ });
+});