Skip to content

skyaktech/tlq-client-node

Repository files navigation

TLQ Client

A TypeScript/Node.js client library for TLQ (Tiny Little Queue) message queue system. TLQ is a simple, fast, in-memory message queue that runs on port 1337.

Features

  • 🚀 Modern TypeScript - Built with TypeScript 5+ and Node.js 22+
  • 🌐 Native Fetch - Uses Node.js native fetch, no external HTTP dependencies
  • 🔁 Automatic Retries - Built-in retry logic with exponential backoff
  • 🎯 Type Safety - Full TypeScript types for all operations
  • 🪶 Lightweight - Minimal dependencies (only debug for logging)
  • 📦 64KB Message Limit - Enforced message size validation
  • 🆔 UUID v7 - Time-ordered message IDs

Installation

npm install tlq-client

Quick Start

import { TLQClient, AddMessageCommand, GetMessagesCommand } from 'tlq-client';

// Initialize the client (defaults to localhost:1337)
const client = new TLQClient({
  host: 'localhost',
  port: 1337,
  maxRetries: 3,
  timeoutMs: 30000
});

// Send a message
const message = await client.send(new AddMessageCommand({
  body: JSON.stringify({ hello: 'world' })
}));
console.log('Message sent:', message.id);

// Get messages
const result = await client.send(new GetMessagesCommand({
  count: 5
}));
console.log('Received messages:', result.messages);

Configuration

Client Options

const client = new TLQClient({
  host: 'localhost',     // TLQ server host
  port: 1337,           // TLQ server port (default: 1337)
  // OR
  endpoint: 'http://localhost:1337',  // Full endpoint URL
  
  maxRetries: 3,        // Maximum retry attempts
  retryDelayMs: 100,    // Base retry delay in milliseconds
  timeoutMs: 30000      // Request timeout in milliseconds
});

Environment Variables

TLQ_HOST=localhost     # Server host
TLQ_PORT=1337         # Server port
TLQ_TIMEOUT=30000     # Request timeout
TLQ_MAX_RETRIES=3     # Max retries
TLQ_DEBUG=true        # Enable debug logging

Available Commands

HealthCheckCommand

Check if the TLQ server is running.

const health = await client.send(new HealthCheckCommand());
console.log('Server status:', health.status);

AddMessageCommand

Add a message to the queue.

const message = await client.send(new AddMessageCommand({
  body: 'Hello World'  // String content (max 64KB)
}));
console.log('Message ID:', message.id);
console.log('State:', message.state);  // 'Ready'
console.log('Retry count:', message.retry_count);  // 0

GetMessagesCommand

Retrieve messages from the queue.

const result = await client.send(new GetMessagesCommand({
  count: 10  // Number of messages to retrieve
}));

for (const msg of result.messages) {
  console.log('ID:', msg.id);
  console.log('Body:', msg.body);
  console.log('State:', msg.state);
  console.log('Retry count:', msg.retry_count);
}

DeleteMessagesCommand

Delete one or more processed messages.

// Delete single message
await client.send(new DeleteMessagesCommand({
  ids: [messageId]  // Array of message UUIDs
}));

// Delete multiple messages
await client.send(new DeleteMessagesCommand({
  ids: ['msg-1', 'msg-2', 'msg-3']
}));

RetryMessagesCommand

Return one or more messages to the queue for retry.

// Retry single message
await client.send(new RetryMessagesCommand({
  ids: [messageId]  // Array of message UUIDs
}));

// Retry multiple messages
await client.send(new RetryMessagesCommand({
  ids: ['msg-1', 'msg-2', 'msg-3']
}));

PurgeQueueCommand

Clear all messages from the queue.

await client.send(new PurgeQueueCommand());
console.log('Queue purged');

Message Structure

TLQ messages have the following structure:

interface TLQMessage {
  id: string;           // UUID v7 (time-ordered)
  body: string;         // Message content (max 64KB)
  state: MessageState;  // 'Ready' | 'Processing' | 'Failed'
  retry_count: number;  // Number of retry attempts
}

Error Handling

The library provides typed error classes for different scenarios:

import { TLQError, ValidationError, NetworkError, TimeoutError } from 'tlq-client';

try {
  await client.send(command);
} catch (error) {
  if (error instanceof ValidationError) {
    // Handle validation errors (e.g., message too large)
    console.error('Invalid input:', error.message);
  } else if (error instanceof NetworkError) {
    // Handle network errors
    console.error('Network issue:', error.message);
  } else if (error instanceof TimeoutError) {
    // Handle timeout errors
    console.error('Request timed out:', error.message);
  } else if (error instanceof TLQError) {
    // Handle general TLQ errors
    console.error('TLQ error:', error.code, error.message);
    
    if (error.retryable) {
      // Error is retryable
    }
  }
}

Examples

See the examples/ directory for complete examples:

  • basic-usage.ts - Complete workflow example
  • error-handling.ts - Error handling patterns

Basic Example

import { 
  TLQClient, 
  AddMessageCommand, 
  GetMessagesCommand,
  DeleteMessagesCommand,
  RetryMessagesCommand 
} from 'tlq-client';

const client = new TLQClient();

// Add messages
await client.send(new AddMessageCommand({
  body: JSON.stringify({ type: 'order', id: '123' })
}));

// Get and process messages
const { messages } = await client.send(new GetMessagesCommand({ count: 5 }));

const processedIds: string[] = [];
const failedIds: string[] = [];

for (const message of messages) {
  try {
    // Process message
    const data = JSON.parse(message.body);
    console.log('Processing:', data);
    
    // Mark as processed
    processedIds.push(message.id);
  } catch (error) {
    // Mark as failed for retry
    failedIds.push(message.id);
  }
}

// Batch delete successful messages
if (processedIds.length > 0) {
  await client.send(new DeleteMessagesCommand({ ids: processedIds }));
}

// Batch retry failed messages
if (failedIds.length > 0) {
  await client.send(new RetryMessagesCommand({ ids: failedIds }));
}

Development

# Install dependencies
npm install

# Run in development mode
npm run dev

# Build the library
npm run build

# Run tests
npm test

# Run linting
npm run lint

# Type checking
npm run typecheck

Requirements

  • Node.js >= 22.0.0
  • TypeScript >= 5.0.0
  • TLQ server running (default: localhost:1337)

TLQ Server

To run TLQ server using Docker:

docker run -p 1337:1337 nebojsa/tlq

Or install from crates.io:

cargo install tlq
tlq

License

MIT

About

A TypeScript/Node.js client library for TLQ (Tiny Little Queue) message queue system

Resources

License

Stars

Watchers

Forks

Packages

No packages published