Skip to main content

Built and signed on GitHub Actions

Works with
This package works with DenoIt is unknown whether this package works with Cloudflare Workers, Node.js, Bun, Browsers
It is unknown whether this package works with Cloudflare Workers
It is unknown whether this package works with Node.js
This package works with Deno
It is unknown whether this package works with Bun
It is unknown whether this package works with Browsers
•JSR Score100%•
License
Apache-2.0
•
Downloads296/wk
•
Publisheda day ago (0.0.10)

A provider-agnostic message queue for NetScript: enqueue and drain background jobs through one MessageQueue contract, auto-discovering a RabbitMQ, Redis, or Deno KV backend from the Aspire environment.

Examples

Example 1

import { createQueue, createTypedQueue } from '@netscript/queue';
import { z } from 'zod';

interface MyMessage { type: 'email' | 'sms'; to: string }
declare function processMessage(message: MyMessage): Promise<void>;

// Simple queue (auto-discovers backend)
const queue = createQueue<MyMessage>('notifications');
await queue.enqueue({ type: 'email', to: 'user@example.com' });

// Type-safe queue with validation
const MessageSchema = z.object({
  type: z.enum(['email', 'sms']),
  to: z.string(),
  body: z.string(),
});

const typedQueue = createTypedQueue('notifications', MessageSchema);
await typedQueue.enqueue({
  type: 'email',
  to: 'user@example.com',
  body: 'Hello!',
});

// Listen for messages
await queue.listen(async (message) => {
  await processMessage(message);
});

Classes

c
QueueConfigurationError(
message: string,
context?: Record<string, unknown>
)

Error thrown when queue configuration is invalid.

c
QueueConnectionError(
message: string,
cause?: Error
)

Error thrown when queue connection fails.

c
QueueError(
message: string,
code: QueueErrorCode,
options?: { cause?: Error; context?: Record<string, unknown>; }
)

Base error class for all queue operations.

  • cause: Error

    Original error that caused this error (if any).

  • code: QueueErrorCode

    Error code for programmatic error handling.

  • context: Record<string, unknown>

    Additional context about the error.

  • toJSON(): Record<string, unknown>

    Convert error to JSON for logging/serialization.

c
QueueHandlerError(
message: string,
cause?: Error,
context?: Record<string, unknown>
)

Error thrown when message handler fails.

c
QueueReceiptRetainedError(
message: string,
cause?: unknown,
context?: Record<string, unknown>
)

Error thrown by a handler when delivery settlement cannot be persisted and the queue adapter must retain the native receipt without acknowledging the message or issuing a counted requeue.

  • retainReceipt: boolean

    Marker inspected by queue adapters to retain the receipt without counted requeue.

c
QueueValidationError(
message: string,
context?: Record<string, unknown>
)

Error thrown when message validation fails.

Enums

E

Error codes for queue operations.

E

Supported queue providers.

Functions

f
createParallelQueue<T = unknown>(
name: string,
options?: ParallelQueueOptions
): MessageQueue<T>

Create a message queue with parallel processing capability.

f
createQueue<T = unknown>(
name: string,
options?: QueueOptions
): MessageQueue<T>

Create a message queue instance with auto-discovery.

f
createTypedQueue<T>(
name: string,
schema: ValidationSchema<T>,
options?: TypedQueueOptions
): TypedMessageQueue<T>

Create a type-safe message queue with Zod validation.

f
isQueueReceiptRetainedError(error: unknown): error is QueueReceiptRetainedError

Return whether an error instructs queue adapters to retain the native receipt without acknowledging the delivery or issuing a counted requeue.

f
safeValidate<T>(
schema: ValidationSchema<T>,
message: unknown
): ValidationResult<T>

Safely validate a message against a Zod schema. Returns a result object instead of throwing.

f
validateOrThrow<T>(
schema: ValidationSchema<T>,
message: unknown,
context?: Record<string, unknown>
): T

Validate a message and throw QueueValidationError if invalid.

f
withValidation<T>(
schema: ValidationSchema<T>,
handler: (message: T) => Promise<void>
): (message: unknown) => Promise<void>

Create a validation middleware for queue handlers. Validates messages before passing to the handler.

Interfaces

I

Structured dead-letter record written by queue adapters before discarding poison messages.

  • Number of delivery attempts observed before terminal failure.

  • enqueuedAt: string

    ISO timestamp when the message was originally enqueued.

  • errorCode: string

    Optional structured error code, such as QueueErrorCode or adapter-specific code.

  • errorMessage: string

    Optional human-readable failure summary.

  • failedAt: string

    ISO timestamp when the terminal failure was recorded.

  • headers: Record<string, string>

    Message headers such as trace context.

  • messageId: string

    Provider or envelope message identifier.

  • Original message payload.

  • queueName: string

    Queue namespace where the message was consumed.

  • reason: DeadLetterReason

    Stable failure reason.

I

Minimal durable store port for dead-letter queue records.

  • append(record: DeadLetterRecord<T>): Promise<void>

    Append a terminal failure record idempotently.

  • depth(): Promise<number>

    Count stored dead-letter records.

  • list(options?: { limit?: number; }): Promise<DeadLetterRecord<T>[]>

    List records in store order.

  • reprocess(
    reenqueue: (record: DeadLetterRecord<T>) => Promise<void>,
    options?: { limit?: number; }
    ): Promise<number>

    Re-enqueue records and remove successfully re-enqueued entries from the store.

I

Options for enqueueing messages.

  • Deduplication ID to prevent duplicate messages. Messages with the same ID within a time window are deduplicated. Provider-specific behavior.

  • delay: number

    Delay in milliseconds before the message becomes available for processing. Useful for scheduling and implementing cron-like patterns.

  • headers: Record<string, string>

    Custom headers/metadata attached to the message. Useful for tracing, routing, or application-specific metadata.

  • priority: number

    Message priority (provider-specific). Higher values typically mean higher priority. Not all providers support priority queues.

  • retentionId: string

    Originating durable identity for adapters supporting pending-message cancellation.

I

Options for listening to messages.

  • concurrency: number

    Number of messages to process concurrently. Default: 1 (sequential processing)

  • Redis delayed-promotion poll in integer milliseconds, 10–60000 (default 1000). Overrides NETSCRIPT_REDIS_DELAYED_POLL_INTERVAL_MS; other providers ignore it.

  • Redis/KV-polling wait for admitted callbacks after intake cancellation. Defaults to the backend visibility timeout; positive Infinity delegates the wait to an outer owner. This is separate from WorkerOptions.drainTimeoutMs, which bounds the whole worker stop; workers retain that total deadline.

  • Redis delivery limit, including the first delivery; defaults to 5.

  • Redis idle pickup poll in integer milliseconds, 10–60000 (default 50). Overrides NETSCRIPT_REDIS_QUEUE_POLL_INTERVAL_MS; other providers ignore it.

  • Maximum number of messages to prefetch. Provider-specific optimization for throughput.

  • Redis grace after lease expiry before recovery, in milliseconds; defaults to 1000.

  • signal: AbortSignal

    Abort signal to stop listening. Allows graceful shutdown of message processing.

  • Visibility timeout in milliseconds. How long a message is hidden from other consumers while processing. Provider-specific behavior.

I

Message context provided to handlers during message processing. Contains metadata and control methods for message acknowledgment.

  • ack(): Promise<void>

    Acknowledge successful message processing. Called automatically on handler success in most cases.

  • Number of times this message has been delivered. Useful for implementing retry limits and dead-letter queue logic.

  • Timestamp when the message was originally enqueued.

  • extendVisibility(milliseconds?: number): Promise<boolean>

    Extend a live claim from now; false means ownership expired or was replaced.

  • headers: Record<string, string>

    Custom headers/metadata attached to the message.

  • messageId: string

    Unique message identifier assigned by the provider.

  • nack(options?: NackOptions): Promise<void>

    Negative acknowledge - signal message processing failure. Called automatically on handler error if native retry is supported.

I

Core message queue interface that all adapters must implement. Provides a unified API for enqueuing and consuming messages.

  • cancelPending(
    resolve: (ids: readonly string[]) => Promise<readonly string[]>,
    onCancelled?: (retentionId: string) => void
    ): Promise<boolean>

    Cancel a bounded page of pending messages by their originating retention identity. The resolver receives at most 100 unique identities; true means another page remains. The optional observer runs once per successful CAS deletion, never on a lost race. Providers without durable cancellable keys omit this capability.

  • enqueue(
    message: T,
    options?: EnqueueOptions
    ): Promise<void>

    Enqueue a single message for processing.

  • enqueueMany(
    messages: T[],
    options?: EnqueueOptions
    ): Promise<void>

    Enqueue multiple messages in a batch. Not all backends support this natively - falls back to sequential enqueue.

  • listen(
    handler: (
    message: T,
    context: MessageContext
    ) => Promise<void>
    ,
    options?: ListenOptions
    ): Promise<void>

    Start listening for messages and process them with the handler. This is typically a long-running operation that continues until stopped.

  • nativeRetrial: boolean

    Indicates whether the backend supports native retry mechanisms. When true, failed messages are automatically retried by the backend. When false, the application must handle retries.

  • stop(): Promise<void>

    Stop listening for messages gracefully. Allows in-flight messages to complete before shutting down.

I

Options for negative acknowledgement and terminal dead-letter metadata.

  • errorCode: string

    Optional structured failure code for the dead-letter record.

  • errorMessage: string

    Optional human-readable failure summary for the dead-letter record.

  • Return a controlled-shutdown delivery without charging this attempt. Effective only when requeue is true; defaults to false. Refunds this live claim once, preserving identity and metadata. Ordinary failures and expired claims count.

  • reason: DeadLetterReason

    Terminal failure reason to store when requeue is false.

  • requeue: boolean

    Whether the message should be returned to the queue for another delivery attempt.

I

Options for creating a parallel queue.

  • concurrency: number

    Number of concurrent message processors (workers). Must be >= 1. Values > 1 enable parallel processing.

I

Provider-specific connection options.

  • denoKv: { path?: string; verbose?: boolean; pollInterval?: number; visibilityTimeout?: number; maxRetries?: number; retryBaseDelay?: number; retryMaxDelay?: number; deduplicationWindow?: number; }

    Deno KV connection options. Also includes options for the KV-polling adapter used with KV Connect.

  • postgres: { url?: string; tableName?: string; }

    PostgreSQL connection options.

  • rabbitmq: { url?: string; queueName?: string; }

    RabbitMQ (AMQP) connection options.

  • redis: { url?: string; options?: Record<string, unknown>; }

    Redis connection options.

I

Base options for creating a queue.

  • autoDiscover: boolean

    Enable auto-discovery of queue services from Aspire environment. Priority: RabbitMQ > Redis > Deno KV (default)

  • connection: QueueConnectionOptions

    Provider-specific connection options.

  • deadLetterStore: DeadLetterStorePort

    Optional dead-letter store used for terminal message failures. When omitted, adapters use their provider-specific durable default.

  • Disable automatic tracing wrapper. When true, the queue will not be automatically wrapped with TracedQueue. Useful when manual tracing is preferred (e.g., in scheduler with traceJobDispatch).

  • provider: QueueProvider

    Queue provider to use. If not specified, auto-discovery will be used.

  • Maximum retry attempts for failed messages. Only applies when backend doesn't have native retry.

  • retryDelay: number

    Delay between retry attempts in milliseconds. Only applies when backend doesn't have native retry.

I

Typed message queue with runtime schema validation. Extends MessageQueue with runtime type safety.

  • schema: ValidationSchema<T>

    The schema used for validation.

I

Options for creating a typed queue with Zod validation.

I

Validation result for safe parsing.

  • data: T

    Parsed data when validation succeeds.

  • error: string

    Validation error message when validation fails.

  • success: boolean

    Whether validation succeeded.

I

Minimal schema contract supported by queue validation helpers.

  • parse(input: unknown): T

    Parse and return the validated value or throw on failure.

  • safeParse(input: unknown):
    { success: true; data: T; }
    | { success: false; error: { message: string; }; }

    Parse and return a structured success/failure result without throwing.

Type Aliases

T
DeadLetterReason =
"max_attempts_exceeded"
| "nack_without_requeue"
| "validation_failed"
| "unroutable"

Stable reason that explains why a message entered the dead-letter queue.