@argos-js/queue
v0.1.2
Published
Event-driven asynchronous job queue with transactional adapters and concurrency controls for Argos-JS
Readme
@argos-js/queue
Event-driven asynchronous job queue with transactional adapters, concurrency controls, backoff retries, and graceful shutdown for the Argos-JS framework.
Features
- Strict Conceptual Separation: Dedicated purely to event-driven, on-demand jobs (emails, webhooks, heavy background processing).
- Zero External Required Dependencies: Out-of-the-box support for
MemoryAdapter(in-memory, testing, development) andDatabaseAdapter(@argos-js/datatransactional withSELECT ... FOR UPDATE SKIP LOCKEDon PostgreSQL/MySQL, or atomic transactions on SQLite). - Pluggable Architecture: Ready for future native Rust engines, ArgosDB, or optional Redis drivers without forcing BullMQ or Redis.
- Type-Safe Job Definitions:
defineJob<TPayload>()with inferred payload typing and cooperativeJobContext(jobId,attempt,signal,progress). - Cooperative Graceful Shutdown: Listens to
SIGTERM/SIGINT, propagatesAbortSignalto active jobs, and drains running tasks before terminating. - Configurable Backoff Retries: Supports exponential and fixed backoff strategies.
Installation
pnpm add @argos-js/queueQuick Start
1. Defining a Job
import { defineJob } from '@argos-js/queue';
export interface SendWelcomeEmailPayload {
to: string;
name: string;
}
export const sendWelcomeEmailJob = defineJob<SendWelcomeEmailPayload>({
name: 'send-welcome-email',
attempts: 3,
backoff: {
type: 'exponential',
delayMs: 1000, // 1s, 2s, 4s...
},
handler: async (payload, context) => {
console.log(`[Job ${context.jobId}] Attempt ${context.attempt} sending email to ${payload.to}`);
// Cooperative cancellation check
if (context.signal.aborted) {
throw new Error('Worker is shutting down');
}
await context.progress(25);
// Send email logic...
await context.progress(100);
},
});2. Dispatching a Job
// Dispatch immediately
const jobId = await sendWelcomeEmailJob.dispatch({
to: '[email protected]',
name: 'Alice',
});
// Dispatch with delay or specific queue
const delayedJobId = await sendWelcomeEmailJob.dispatch(
{ to: '[email protected]', name: 'Bob' },
{ delayMs: 60000, queue: 'high-priority' }
);3. Running a Queue Worker
import { QueueWorker, DatabaseAdapter, setDefaultQueueAdapter } from '@argos-js/queue';
import { createDatabase } from '@argos-js/data';
// Optional: Use persistent database adapter
const db = createDatabase({
driver: 'postgres',
connectionString: process.env.DATABASE_URL,
});
const adapter = new DatabaseAdapter(db);
setDefaultQueueAdapter(adapter);
const worker = new QueueWorker({
concurrency: 4,
queues: ['high-priority', 'default'],
adapter,
});
// Setup SIGTERM / SIGINT graceful handling
worker.setupSignalHandlers();
await worker.start();CLI Management
The official Argos CLI provides semantic commands to control queue workers:
# Start queue workers
argos queue start --workers=4 --queues=high,default
# Check queue status (pending, processing, completed, failed)
argos queue status
# Clear jobs from a specific queue
argos queue clear defaultProduction Deployment
Systemd Service (/etc/systemd/system/argos-queue.service)
[Unit]
Description=Argos-JS Background Queue Worker
After=network.target
[Service]
Type=simple
User=argos
WorkingDirectory=/var/www/my-argos-app
Environment=NODE_ENV=production
ExecStart=/usr/bin/node ./dist/app/index.js --worker
Restart=always
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=30
[Install]
WantedBy=multi-user.targetDocker Container
FROM node:20-alpine AS runner
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm install -g pnpm && pnpm install --prod
COPY dist ./dist
ENV NODE_ENV=production
STOPSIGNAL SIGTERM
CMD ["node", "./node_modules/@argos-js/cli/bin/argos.js", "queue", "start", "--workers=4"]