@netscript/queue@0.0.10Built and signed on GitHub ActionsBuilt and signed on GitHub Actions
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
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
Error thrown when queue configuration is invalid.
Error thrown when queue connection fails.
Base error class for all queue operations.
Error thrown when message handler fails.
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.
Error thrown when message validation fails.
Enums
Error codes for queue operations.
Supported queue providers.
Functions
Create a message queue with parallel processing capability.
Create a message queue instance with auto-discovery.
Create a type-safe message queue with Zod validation.
Return whether an error instructs queue adapters to retain the native receipt without acknowledging the delivery or issuing a counted requeue.
Safely validate a message against a Zod schema. Returns a result object instead of throwing.
Validate a message and throw QueueValidationError if invalid.
Create a validation middleware for queue handlers. Validates messages before passing to the handler.
Interfaces
Structured dead-letter record written by queue adapters before discarding poison messages.
- deliveryCount: number
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.
- payload: T
Original message payload.
- queueName: string
Queue namespace where the message was consumed.
- reason: DeadLetterReason
Stable failure reason.
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(): Promise<number>reenqueue: (record: DeadLetterRecord<T>) => Promise<void>,options?: { limit?: number; }
Re-enqueue records and remove successfully re-enqueued entries from the store.
Options for enqueueing messages.
- deduplicationId: string
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.
Options for listening to messages.
- concurrency: number
Number of messages to process concurrently. Default: 1 (sequential processing)
- delayedPollIntervalMs: number
Redis delayed-promotion poll in integer milliseconds, 10–60000 (default 1000). Overrides NETSCRIPT_REDIS_DELAYED_POLL_INTERVAL_MS; other providers ignore it.
- drainTimeoutMs: number
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.
- maxDeliveries: number
Redis delivery limit, including the first delivery; defaults to 5.
- pollIntervalMs: number
Redis idle pickup poll in integer milliseconds, 10–60000 (default 50). Overrides NETSCRIPT_REDIS_QUEUE_POLL_INTERVAL_MS; other providers ignore it.
- prefetchCount: number
Maximum number of messages to prefetch. Provider-specific optimization for throughput.
- recoveryGrace: number
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.
- visibilityTimeout: number
Visibility timeout in milliseconds. How long a message is hidden from other consumers while processing. Provider-specific behavior.
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.
- deliveryCount: number
Number of times this message has been delivered. Useful for implementing retry limits and dead-letter queue logic.
- enqueuedAt: Date
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.
Core message queue interface that all adapters must implement. Provides a unified API for enqueuing and consuming messages.
- cancelPending(): Promise<boolean>resolve: (ids: readonly string[]) => Promise<readonly string[]>,onCancelled?: (retentionId: string) => void
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(): Promise<void>message: T,options?: EnqueueOptions
Enqueue a single message for processing.
- enqueueMany(): Promise<void>messages: T[],options?: EnqueueOptions
Enqueue multiple messages in a batch. Not all backends support this natively - falls back to sequential enqueue.
- listen(): Promise<void>handler: () => Promise<void>,message: T,context: MessageContextoptions?: ListenOptions
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.
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.
- preserveDeliveryCount: boolean
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
requeueis false. - requeue: boolean
Whether the message should be returned to the queue for another delivery attempt.
Options for creating a parallel queue.
- concurrency: number
Number of concurrent message processors (workers). Must be >= 1. Values > 1 enable parallel processing.
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.
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.
- disableAutoTracing: boolean
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.
- retryAttempts: number
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.
Typed message queue with runtime schema validation. Extends MessageQueue with runtime type safety.
- schema: ValidationSchema<T>
The schema used for validation.
Options for creating a typed queue with Zod validation.
- onValidationError: "discard" | "dlq" | "throw"
Action to take when validation fails on dequeue.
- validateOnDequeue: boolean
Validate messages when dequeuing.
- validateOnEnqueue: boolean
Validate messages before enqueuing.
Validation result for safe parsing.
Minimal schema contract supported by queue validation helpers.
Type Aliases
| "nack_without_requeue"
| "validation_failed"
| "unroutable"
Stable reason that explains why a message entered the dead-letter queue.