HPKV SDK Guides

SDK Reference Documentation

REST & Nexus SDK

REST API SDK simplifies using HPKV's REST API. It provides methods for all core CRUD operations, as well as Nexus Search capabilities.

Supported Operations

  • CRUD Operations - Full support for creating, reading, updating, and deleting records
  • Range Queries - Range queries to retrieve multiple records within a key range
  • JSON Atomic Patching & Partial Updates - JSON patching when values are JSON objects and appending when values are arbitrary strings
  • Atomic Increments/Decrements - atomic increments and decrements for counters without race conditions
  • Nexus Semantic Search - Retrieving records that have semantic similarity to a given query
  • Nexus Query - Generating AI-Powered answers to natural language queries about your data

Open Source Client

The REST API client SDKs are available as open source software on GitHub. You can find the source code, contribute, or create custom implementations.

Currently, only the NodeJS SDK is available, with more language implementations coming soon.

Installation

npm install @hpkv/rest-client

Basic Usage Examples

import HPKVRestClient from '@hpkv/rest-client';

const client = new HPKVRestClient('your-hpkv-api-base-url', 'your-hpkv-nexus-api-base-url', 'your-api-key');

// Set a value
await client.set('my-key', 'my-value');

// Get a value
const result = await client.get('my-key');

// Store JSON
await client.set('user:1', {
  name: 'John Doe',
  email: '[email protected]',
});

// Partial update - updates the value of email and adds a new address property
await client.set(
  'user:1',
  {
    email: '[email protected]',
    address: 'John Doe address'
  },
  true
);

// Atomic Increment counter
const counter = await client.atomicIncrement('visits', 1);

// Range query 
const records = await client.range('start', 'end', 100);

// Semantic search
const searchResults = await client.nexusSearch('find John Doe''s information');

// AI-powered query
const answer = await client.nexusQuery('What is John Doe''s email address?');

SDK Reference

Node.js REST SDK Reference

HPKVRestClient

The main client class for performing CRUD operations over HTTP.

Methods
class HPKVRestClient {
constructor(apiKey: string, baseUrl: string);

set(key: string, value: unknown, partialUpdate?: boolean): Promise<RecordResponse>
//Set a value for a key. If partialUpdate is true, the value will be appended to the existing. If the existing and new values are valid JSON, it performs an atomic JSON patching.

get(key: string): Promise<RecordResponse>
//Get a value by key.

delete(key: string): Promise<RecordResponse>
//Delete a key-value pair.

atomicIncrement(key: string, increment: number): Promise<RecordResponse>
//Increment or decrement a numeric value atomically.

range(startKey: string, endKey: string, limit=100): Promise<RangeResponse>
//Query records within a key range.

nexusSearch(query: string, options?: SearchOptions): Promise<SearchResponse>
//Perform semantic search using Nexus Search.

nexusQuery(query: string, options?: QueryOptions): Promise<QueryResponse>
//Get AI-generated answers using Nexus Query.


}

WebSocket SDK

HPKV's WebSocket SDK makes it easy to use HPKV's WebSocket API. It provides methods for all core CRUD operations, as well as real-time key monitoring (Pub-Sub).

Supported Operations

  • CRUD Operations - Full support for creating, reading, updating, and deleting records
  • Range Queries - Range queries to retrieve multiple records within a key range
  • JSON Atomic Patching & Partial Updates - JSON patching when values are JSON objects and appending when values are arbitrary strings
  • Atomic Increments/Decrements - atomic increments and decrements for counters without race conditions
  • Access Controlled Operations - Limiting client access to specific keys
  • Real-time key monitoring (Pub-Sub) - Subscribing to real-time changes in key values

Open Source Client

The WebSocket client SDKs are available as open source software on GitHub. You can find the source code, contribute, or create custom implementations.

Currently, only the NodeJS SDK is available, with more language implementations coming soon.

Installation

npm install @hpkv/websocket-client

Client Types

The WebSocket SDK provides two types of clients:

  • HPKVApiClient

    Handles CRUD operations over WebSocket connections to HPKV. It requires an API key and has full access to all keys. This is meant to be usedfor server-side operations.

  • HPKVSubscriptionClient

    Enables real-time key monitoring (Pub-Sub) and access-controlled CRUD operations. Authenticates using a subscription token that must be generated on your server.

    Key features:

    • Connects using a subscription token generated by the WebsocketTokenManager
    • Token generation requires specifying subscribeKeys (for monitoring) and optional accessPattern (for controlling CRUD access)
    • Access is restricted to keys matching the patterns defined during token generation

Creating Clients

Use HPKVClientFactory to create clients. It provides static methods to create both HPKVApiClient and HPKVSubscriptionClient instances.

import { HPKVClientFactory } from '@hpkv/websocket-client';
// Create a client for CRUD operations without limits
const apiClient = HPKVClientFactory.createApiClient('YOUR_API_KEY', 'YOUR_API_BASE_URL');

// Create a client for real-time key monitoring (Pub-Sub) and access-controlled CRUD operations
const subscriptionClient = HPKVClientFactory.createSubscriptionClient('YOUR_SUBSCRIPTION_TOKEN', 'YOUR_API_BASE_URL');
Using API Client

The WebSocket SDK provides a complete set of operations for interacting with your HPKV database. Both HPKVApiClient and HPKVSubscriptionClient share the same method signatures for CRUD operations, However, HPKVApiClient connects to the databse using API key and has full access to all keys, while HPKVSubscriptionClient connects using a subscription token and has limited access to only the keys specified during token generation.

The example below demonstrates:

  • Connecting to HPKV via WebSocket
  • Storing structured JSON data
  • Retrieving stored values
  • Performing JSON patching
  • Executing range queries to fetch multiple records
  • Using atomic operations for counters
const apiClient = HPKVClientFactory.createApiClient('YOUR_API_KEY', 'YOUR_API_BASE_URL');

    await apiClient.connect();

    const userData = {
      name: 'John Doe',
      email: '[email protected]',
      preferences: {
        theme: 'dark',
        notifications: true,
      },
    };

    // Store user data
    const setResponse = await apiClient.set('user:123', userData);
    console.log(setResponse.success);

    // Retrieve user data
    const getResponse = await apiClient.get('user:123');
    console.log('Retrieved user data:', getResponse.value;

    // Example of partial update - Atomic JSON Patching
    const patchResponse = await apiClient.set('user:123', {
      preferences: {
        theme: 'light',
        notifications: false,
      },
    }, true);
    console.log(patchResponse.success);
    const changedValue = await apiClient.get('user:123');
    console.log(changedValue.value); // {name: 'John Doe', email: '[email protected]', preferences: {theme: 'light', notifications: false}}

    // Example of appending a value
    const setResponse = await apiClient.set('key-with-non-json-value', 'Hello');
    console.log(setResponse.success);
    const appendResponse = await apiClient.set('key-with-non-json-value', ' world!', true);
    const getResponse = await apiClient.get('key-with-non-json-value');
    console.log(getResponse.value); // Hello world!

    // Example of range query. Returns first 10 records in the key range 'user:100' to 'user:200'
    const rangeResult = await apiClient.range('user:100', 'user:200', {
      limit: 10,
    });
    console.log('Total count:', rangeResult.count);
    console.log('Truncated:', rangeResult.truncated); // Specifies if there are more records beyond the limit
    console.log('Records:', rangeResult.records);

    // Example of atomic increment
    await apiClient.set('user:123:visits', '0');
    const incrementResponse = await apiClient.atomicIncrement('user:123:visits', 1);
    console.log(incrementResponse.success, incrementResponse.newValue); // true 1
    
    await apiClient.disconnect();
    

Token Generation for Subscription Client

The HPKVSubscriptionClient requires a subscription token to connect. This token must be generated on your server using the WebsocketTokenManager class. You can specify the keys to subscribe to and the pattern of keys that the client can access and modify and when the client connects using the token, it will receive notifications for any changes in the subscribed keys and can perform CRUD operations on the keys that match the access pattern.

The WebsocketTokenManager class enables secure token generation for subscription clients. When calling the generateToken() method, you can configure:

  • subscribeKeys - An array of keys to monitor for real-time changes
  • accessPattern - (Optional) A regex pattern that controls which keys the client can access and modify
import { WebsocketTokenManager } from '@hpkv/websocket-client';

const tokenManager = new WebsocketTokenManager('YOUR_API_KEY', 'YOUR_API_BASE_URL');

// Generates a token with subscription to the key 'document:123' and access pattern to match keys that start with 'document:'
const token = await tokenManager.generateToken({
  subscribeKeys: ['document:123'], // keys to subscribe to
  accessPattern: '^document:.*$' // regex pattern to match keys that the client can perform CRUD operations on
});

// Use the token to create a subscription client. The client will be notified when the value of 'document:123' changes.
const subscriptionClient = HPKVClientFactory.createSubscriptionClient(token, 'YOUR_API_BASE_URL');

// Add a handler to the subscription client to handle changes in the subscribed keys
subscriptionClient.subscribe((data) => {
  console.log(`${data.key} updated: ${data.value}`);
  // Update UI...
});

// Connect the subscription client to the server
await subscriptionClient.connect();
// Client can succesfully perform CRUD operations on the allowed keys
const setResponse = await subscriptionClient.set('document:123', 'new value');
const getResponse = await subscriptionClient.get('document:234');
const deleteResponse = await subscriptionClient.delete('document:345');

// Client will not be able to perform any operations on keys that do not match the access pattern
const setResponse = await subscriptionClient.set('user:123', 'new value'); // will fail
const getResponse = await subscriptionClient.get('user:123'); // will fail
const deleteResponse = await subscriptionClient.delete('user:123'); // will fail

Notes

  • These tokens should always be generated server-side since WebsocketTokenManager requires API key for token generation and the tokens control access patterns.
  • The tokens are valid for 2 hours, so consider some token regeneration logic in your application
  • Subscribing to a key does not give access to the key, it only gives the ability to monitor changes on the key.
  • When no access pattern is provided, the client using the token will have access to all keys.
  • To deny access to all keys, provide $^ as the access pattern. Client will still be subscribed to the given keys but will not have access for any operations.
  • If you need to change the subscribed keys or access pattern, you can generate a new token with the new configuration.

Using Subscription Client

Subscription clients require tokens to connect and as mentioned above. Subscription clients can be used at both client and server sides, but if used at client side, these tokens must be generated on your server. The standard implementation flow for using subscription clients at the client side is:

  1. Create a secure API endpoint on your server that generates tokens using WebsocketTokenManager
  2. Client applications request a token from your endpoint (with proper authentication)
  3. Your server generates and returns the token with appropriate access limitations
  4. Client applications calls the endpoint to get the token and use the token to create and connect a HPKVSubscriptionClient

The example below demonstrates this implementing real-time features in browser applications:

// First, call your token generation API endpoint to get a token. You need to add an endpoint to your backend server to generate the token.
const response = await fetch('https://you-token-generation-endpoint', {
  method: 'POST',
});
const { token } = await response.json();

// Create subscription client
const subscriptionClient = HPKVClientFactory.createSubscriptionClient(
  token,
  'your_api_base_url'
);

await subscriptionClient.connect();

// Add a handler to the subscription client to handle changes in the subscribed keys
subscriptionClient.subscribe((data) => {
  console.log(`${data.key} updated: ${data.value}`);
  // Update UI...
});

//Perform CRUD oeprations. The operations will fail if the key does not match the access pattern.
// set a value
const setResponse = await subscriptionClient.set('document:123', '{name: 'Initial Name'}');
console.log(setResponse.success);

// get a value
const getResponse = await subscriptionClient.get('document:123');
console.log(getResponse.value);
// The value is : {name: 'Initial Name'}

// partially update a value by setting the partialUpdate flag to true. If value is a valid JSON, it will do an atomic patch operation, otherwise it will append the new value to the existing value.
const patchResponse = await subscriptionClient.set('document:123', {
  name: 'New Name',
  author: 'John Doe'
}, true);
console.log(patchResponse.success);
const changedValue = await subscriptionClient.get('document:123');
console.log(changedValue.value);
// The value of the key is now: {name: 'New Name', author: 'John Doe'}


// delete a value
const deleteResponse = await subscriptionClient.delete('document:123');
console.log(deleteResponse.success);

//atmoic increment. it will increase the value of the key by 1.
const incrementResponse = await subscriptionClient.atomicIncrement('counter', 1);
console.log(incrementResponse.success, incrementResponse.newValue);

//range query. it will return the first 10 keys in the range 'document:100' to 'document:200'
const rangeResponse = await subscriptionClient.range('document:100', 'document:200', {limit: 10});
console.log(rangeResponse.records);

await subscriptionClient.disconnect();

Here's an example implementation of a server-side API endpoint that generates tokens:

import { WebsocketTokenManager } from '@hpkv/websocket-client';
import express from 'express';

const app = express();
const tokenManager = new WebsocketTokenManager('your-api-key', 'your api base url');

app.post('/api/token/websocket', async (req, res) => {
  try {
    // Generate a token with specific access patterns and keys to monitor
    const token = await tokenManager.generateToken({
      subscribeKeys: ['user:123', 'product:456'], // Keys to monitor
      accessPattern: '^(user|product):[0-9]+'     // Regex pattern for allowed operations
    });
    
    res.json({ token });
  } catch (error) {
    res.status(500).json({ error: 'Failed to generate token' });
  }
});

Connection Management

The WebSocket client automatically manages the connection lifecycle, including reconnections. If the connection is lost unexpectedly, the client will attempt to reconnect using an exponential backoff strategy:

  • It waits for an initial delay (configurable, default 1s) before the first retry.
  • The delay doubles for each subsequent failed attempt, up to a maximum delay (configurable, default 30s).
  • A small random jitter is added to the delay to prevent simultaneous reconnections from multiple clients.
  • Reconnection stops after 3 attempts. If it fails to reconnect after these attempts, a reconnectFailed event is emitted.

To monitor the connection state, you can subscribe to events using the on method:

client.on('connected', () => {
  console.log('WebSocket connected!');
});

client.on('disconnected', ({ code, reason }) => {
  console.log(`WebSocket disconnected. Code: ${code}, Reason: ${reason}`);
});

client.on('reconnecting', ({ attempt, maxAttempts, delay }) => {
  console.log(`Attempting to reconnect (${attempt}/${maxAttempts})... Waiting ${delay}ms`);
});

client.on('reconnectFailed', (error) => {
  console.error('Failed to reconnect after multiple attempts:', error);
});

The available events are:

  • connected: Emitted when the connection is successfully established (initially or after a reconnect).
  • disconnected: Emitted when the connection is closed. It may receive an object with code and reason if provided by the server.
  • reconnecting: Emitted before each reconnection attempt. It receives an object with attempt, maxAttempts, and the calculated delay in milliseconds.
  • reconnectFailed: Emitted when all reconnection attempts have failed. It receives the final ConnectionError object.
Use the off method with the same arguments to remove listeners when they are no longer needed.

SDK Reference

Node.js WebSocket SDK Reference

HPKVClientFactory

The main factory class for creating API and Subscription clients.

Methods
class HPKVClientFactory {
  /**
   * Creates an API client for CRUD operations using API key
   */
  static createApiClient(apiKey: string, baseUrl: string): HPKVApiClient;
  
  /**
   * Creates a subscription client for real-time monitoring and access-controlled CRUD operations
   */
  static createSubscriptionClient(token: string, baseUrl: string): HPKVSubscriptionClient;
}

BaseWebSocketClient

Base client class that handles WebSocket connections, reconnection logic, and common CRUD operations.

Constructor
constructor(baseUrl: string, config?: ConnectionConfig);
Methods
interface BaseWebSocketClient {
  /**
   * Connects to the WebSocket server
   * Must be called before any other method
   */
  connect(): Promise<void>;
  
  /**
   * Disconnects from the WebSocket server
   * @param cancelPendingRequests - Whether to cancel all pending requests (default: true)
   */
  disconnect(cancelPendingRequests?: boolean): Promise<void>;
  
  /**
   * Gets the value associated with the specified key
   * @param key - The key to get the value of
   * @param timeoutMs - Optional custom timeout for this operation
   */
  get(key: string, timeoutMs?: number): Promise<HPKVResponse>;
  
  /**
   * Sets a key-value pair
   * @param key - The key to set the value of
   * @param value - The value to set
   * @param partialUpdate - If true, performs a merge/patch instead of replacing the value
   * @param timeoutMs - Optional custom timeout for this operation
   */
  set(key: string, value: unknown, partialUpdate?: boolean, timeoutMs?: number): Promise<HPKVResponse>;
  
  /**
   * Deletes the specified key
   * @param key - The key to delete
   * @param timeoutMs - Optional custom timeout for this operation
   */
  delete(key: string, timeoutMs?: number): Promise<HPKVResponse>;
  
  /**
   * Performs a range query to retrieve multiple records
   * @param key - The key to start the range query from
   * @param endKey - The key to end the range query at
   * @param options - Optional range query options
   * @param timeoutMs - Optional custom timeout for this operation
   */
  range(key: string, endKey: string, options?: RangeQueryOptions, timeoutMs?: number): Promise<HPKVResponse>;
  
  /**
   * Atomically increments or decrements a numeric value
   * @param key - The key to increment or decrement
   * @param value - The amount to increment or decrement by
   * @param timeoutMs - Optional custom timeout for this operation
   */
  atomicIncrement(key: string, value: number, timeoutMs?: number): Promise<HPKVResponse>;
  
  /**
   * Register event listeners for connection events
   * @param event - The event to listen for
   * @param listener - The listener to call when the event occurs
   */
  on(event: 'connected' | 'disconnected' | 'reconnecting' | 'reconnectFailed', listener: (...args: any[]) => void): void;
  
  /**
   * Remove event listeners
   * @param event - The event to remove the listener from
   * @param listener - The listener to remove
   */
  off(event: 'connected' | 'disconnected' | 'reconnecting' | 'reconnectFailed', listener: (...args: any[]) => void): void;
  
  /**
   * Get the current connection state
   */
  getConnectionState(): ConnectionState;
  
  /**
   * Get current connection statistics
   */
  getConnectionStats(): ConnectionStats;

  /**
   * Clean up resources when instance is no longer needed
   */
  destroy(): void;
}

HPKVApiClient

Client for CRUD operations using API key authentication.

Constructor
constructor(apiKey: string, baseUrl: string, config?: ConnectionConfig);
Methods

Inherits all methods from BaseWebSocketClient.

HPKVSubscriptionClient

Client for real-time key monitoring (Pub-Sub) and access-controlled CRUD operations. Access is controlled by the subscription token.

Constructor
constructor(token: string, baseUrl: string, config?: ConnectionConfig);
Methods

Inherits all methods from BaseWebSocketClient.

interface HPKVSubscriptionClient extends BaseWebSocketClient {
  /**
   * Subscribes to changes for keys covered by the subscription token
   * @param callback Function to call when key values change
   * @returns callback id
   */
  subscribe(callback: HPKVEventHandler): string;
  
  /**
   * Unsubscribes the callback from the subscription
   */
  unsubscribe(callbackId: string): void;
}

WebsocketTokenManager

Manages token generation for subscription clients. Should only be used on the server side.

Constructor
constructor(apiKey: string, baseUrl: string);
Methods
class WebsocketTokenManager {
  /**
   * Generates a token for subscription client
   * @returns A subscription token
   */
  generateToken(config: HPKVTokenConfig): Promise<string>;
}

Type Definitions

ConnectionConfig
interface ConnectionConfig {
  maxReconnectAttempts?: number;
  initialDelayBetweenReconnects?: number;
  maxDelayBetweenReconnects?: number;
}
ConnectionStats
interface ConnectionStats {
  isConnected: boolean;
  reconnectAttempts: number;
  messagesPending: number;
  connectionState: string;
  queueSize: number;
}
ConnectionState
enum ConnectionState {
  CONNECTED = 1,
  DISCONNECTED = 2,
  RECONNECTING = 3,
  RECONNECT_FAILED = 4
}
HPKVTokenConfig
interface HPKVTokenConfig {
  /**
   * Keys to subscribe to for real-time monitoring
   */
  subscribeKeys: string[];
  
  /**
   * Regex pattern for keys that the client can perform CRUD operations on
   */
  accessPattern?: string;
}
RangeQueryOptions
interface RangeQueryOptions {
  limit?: number;
}
HPKVResponse
interface HPKVResponse {
  type?: string;
  code: number;
  message?: string;
  messageId?: number;
  key?: string;
  value?: string | number;
  newValue?: number;
  error?: string;
  success?: boolean;
  records?: Array<{
    key: string;
    value: string;
  }>;
  count?: number;
  truncated?: boolean;
  timestamp?: number;
}
HPKVEventHandler
type HPKVEventHandler = (data: HPKVResponse) => void;

RIOC SDK

Business+ Feature

This feature is available exclusively to Business and Enterprise plan subscribers. Please visit our pricing page for more information.

HPKV provides official SDKs for Node.js, Python, and .NET to simplify integration with your applications. These SDKs offer a native interface to RIOC (Remote IO Control), our high-performance protocol for ultra-low latency operations.

Security Note

All SDKs use TLS 1.3 by default for secure communication. Your certificates will be automatically generated and available in your Dashboard. Enterprise users can optionally disable TLS for private setups where security is managed through other means.

Open Source Client

The RIOC client SDKs are available as open source software on GitHub. You can find the source code, contribute, or create custom implementations.

The repository includes client SDKs for Node.js, Python, and .NET, core API documentation, implementation examples, and client protocol specifications. All client code is licensed under the Apache License 2.0.

Installation

npm install @hpkv/rioc

Coming Soon

Usage Examples

Here's how to perform common operations with our SDKs:

const { RiocClient, RiocConfig } = require('@hpkv/rioc');

// Create a client
const config = new RiocConfig({
  host: 'your-hpkv-host.com',
  port: 8080,
  apiKey: 'YOUR_API_KEY'
});
const client = new RiocClient(config);

try {
  // Basic operations
  const key = Buffer.from('user:123');
  const value = Buffer.from('John Doe');
  
  // Insert a record
  client.insert(key, value, RiocClient.getTimestamp());
  
  // Get a record
  const retrievedValue = client.get(key);
  console.log(retrievedValue.toString()); // "John Doe"
  
  // Atomic increment/decrement
  const counterKey = Buffer.from('counter:visits');
  // First create the counter if it doesn't exist
  client.insert(counterKey, Buffer.from('0'), RiocClient.getTimestamp());
  // Increment the counter
  const newCount = client.atomicIncDec(counterKey, 1, RiocClient.getTimestamp());
  console.log('Visit count:', newCount); // 1
  
  // Range query - get all users from 100 to 200
  const startKey = Buffer.from('user:100');
  const endKey = Buffer.from('user:200');
  const results = client.rangeQuery(startKey, endKey, 50); // limit to 50 records
  
  for (const { key, value } of results) {
    console.log(`${key.toString()}: ${value.toString()}`);
  }
  
  // Batch operations
  const batch = client.createBatch();
  batch.addGet(Buffer.from('user:123'));
  batch.addRangeQuery(startKey, endKey, 10);
  
  const tracker = batch.executeAsync();
  tracker.wait();
  
  // Get results from the batch
  const batchGetResult = tracker.getResponse(0);
  const batchRangeResult = tracker.getRangeQueryResponse(1);
  
  console.log(batchGetResult.toString());
  console.log(`Found ${batchRangeResult.length} records in range`);
  
  // Clean up
  batch.dispose();
  tracker.dispose();
} finally {
  // Always dispose the client when done
  client.dispose();
}

SDK Reference

Node.js SDK Reference

RiocClient

The main client class for interacting with HPKV through RIOC.

Constructor
class RiocClient {
  constructor(config: RiocConfig);
}

Creates a new RIOC client with the specified configuration.

Properties
class RiocClient {
  readonly isDisposed: boolean;  // Whether the client has been disposed
}
Methods
class RiocClient {
  /**
   * Gets a timestamp for write operations.
   * This method provides accurate timing for operations, though using local system time is also acceptable.
   */
  static getTimestamp(): bigint;
  
  /**
   * Retrieves the value associated with the specified key
   */
  get(key: Buffer): Buffer;
  
  /**
   * Retrieves multiple records within a key range
   */
  rangeQuery(startKey: Buffer, endKey: Buffer, limit?: number): { key: Buffer, value: Buffer }[];
  
  /**
   * Inserts or updates a key-value pair
   */
  insert(key: Buffer, value: Buffer, timestamp: bigint): void;
  
  /**
   * Deletes the specified key
   */
  delete(key: Buffer, timestamp: bigint): void;
  
  /**
   * Atomically increments or decrements a numeric value
   * @param key The key of the value to increment/decrement
   * @param increment The amount to increment (positive) or decrement (negative)
   * @param timestamp The operation timestamp
   * @returns The new value after the operation
   */
  atomicIncDec(key: Buffer, increment: number, timestamp: bigint): number;
  
  /**
   * Creates a new batch for executing multiple operations
   */
  createBatch(): RiocBatch;
  
  /**
   * Disposes of the client and releases all resources
   */
  dispose(): void;
}
String Helper Methods
class RiocClient {
  /**
   * Gets a value as a string
   */
  getString(key: string): string;
  
  /**
   * Inserts a string value
   */
  insertString(key: string, value: string, timestamp: bigint): void;
  
  /**
   * Deletes a key (string version)
   */
  deleteString(key: string, timestamp: bigint): void;
  
  /**
   * Performs a range query with string keys and values
   */
  rangeQueryString(startKey: string, endKey: string, limit?: number): { key: string, value: string }[];
  
  /**
   * Atomically increments or decrements a numeric value (string version)
   * @returns The new value after the operation
   */
  atomicIncDecString(key: string, increment: number, timestamp: bigint): number;
}

RiocBatch

Represents a batch of operations to be executed together.

Methods
class RiocBatch {
  /**
   * Adds a get operation to the batch
   */
  addGet(key: Buffer): void;
  
  /**
   * Adds a range query operation to the batch
   */
  addRangeQuery(startKey: Buffer, endKey: Buffer, limit?: number): void;
  
  /**
   * Adds an insert operation
   */
  addInsert(key: Buffer, value: Buffer, timestamp: bigint): void;
  
  /**
   * Adds a delete operation
   */
  addDelete(key: Buffer, timestamp: bigint): void;
  
  /**
   * Executes the batch asynchronously
   */
  executeAsync(): RiocBatchTracker;
  
  /**
   * Disposes of the batch and releases all resources
   */
  dispose(): void;
}

RiocBatchTracker

Tracks the execution of a batch operation.

Methods
class RiocBatchTracker {
  /**
   * Waits for the batch operation to complete
   */
  wait(timeoutMs: number): void;
  
  /**
   * Gets the response for a GET operation
   */
  getResponse(index: number): Buffer;
  
  /**
   * Gets the response for a RANGE QUERY operation
   */
  getRangeQueryResponse(index: number): { key: Buffer, value: Buffer }[];
  
  /**
   * Disposes of the tracker and releases all resources
   */
  dispose(): void;
}

Configuration Types

RiocConfig
interface RiocConfig {
  host: string;          // The host to connect to
  port: number;          // The port to connect to
  timeoutMs?: number;    // Operation timeout in milliseconds (default: 5000)
  tls?: RiocTlsConfig;  // TLS configuration
}
RiocTlsConfig
interface RiocTlsConfig {
  caPath: string;           // CA certificate path
  certificatePath: string;  // Client certificate path
  keyPath: string;         // Client private key path
  verifyHostname: string;  // Server hostname to verify
  verifyPeer: boolean;     // Enable certificate verification
}

Error Types

  • RiocError

    Base error class for all RIOC errors.

  • RiocTimeoutError

    Thrown when an operation times out.

  • RiocConnectionError

    Thrown when there are connection issues.

Best Practices

  • Use timestamps from the SDK's timestamp generation methods for write operations for accurate operation timing
  • Implement proper error handling with specific error types
  • Use batch operations when performing multiple related operations
  • Use range queries for efficiently retrieving multiple related records
  • Keep your SDK version up to date for the latest features and security updates
  • Store TLS certificates securely and implement proper certificate rotation
  • Use string methods (e.g., insert_string) for text data to handle encoding automatically
  • Implement reconnection logic with exponential backoff for production applications
  • Monitor operation latencies and implement appropriate timeout values