power-queues 1.0.8 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,2 +1,146 @@
1
1
  # power-queues
2
- ## Base classes for implementing custom queues in redis under high load conditions.
2
+ A production-ready, **Redis-backed queue runner** with visibility timeouts, delayed scheduling, chainable queues, retries with exponential backoff + jitter, and heartbeat renewals — built on top of a thin ```PowerRedis``` abstraction.
3
+
4
+ This module exposes a base abstract class PowerQueue which you extend and implement. It supports:
5
+
6
+ - FIFO reservation (`LMOVE LEFT->RIGHT` preferred, `RPOPLPUSH` fallback) via Lua scripts or client loop.
7
+ - **Visibility timeout (VT)** with periodic heartbeat (ZSET scores store deadlines).
8
+ - **Delayed tasks** (ZSET with future timestamps) and promotion to ready list.
9
+ - **Retry policy** with exponential backoff + jitter and a **fail** queue after max attempts.
10
+ - **Chain mode**: automatically forward a task through a list of queues and call lifecycle hooks.
11
+ - Iteration loop with promote/requeue passes, concurrency slicing, and status counters with TTL.
12
+
13
+ It provides the core logic for **visibility timeouts**, **task retries**, **delayed scheduling**, **chain forwarding**, and **concurrent workers** — without any external dependencies.
14
+
15
+ > Built on top of [**PowerRedis**](https://github.com/ihor-bielchenko/power-redis)
16
+ > Uses utilities from [**full-utils**](https://github.com/ihor-bielchenko/full-utils)
17
+
18
+ ## API (with examples)
19
+ Below are brief excerpts. Full JSDoc: power-queues.docs.ihor.bielchenko.com.
20
+
21
+ ## Overview
22
+
23
+ PowerQueue is not a “ready-made” message broker like BullMQ — it’s a **foundation** for building your own
24
+ custom Redis-based queues with full control over task lifecycle and execution flow.
25
+
26
+ It manages:
27
+
28
+ - `LIST` for **ready tasks** (RPUSH producers, LMOVE/RPOPLPUSH consumers)
29
+ - `LIST` for **processing tasks** (temporary visibility list)
30
+ - `ZSET` for **visibility timeouts** (invisible tasks until acknowledged or expired)
31
+ - `ZSET` for **delayed scheduling** (future tasks activation)
32
+
33
+ Ideal for:
34
+ - high-performance Redis-based backends,
35
+ - telemetry and distributed job systems,
36
+ - retryable or delayed workloads,
37
+ - cron-like task promotion and requeueing.
38
+
39
+
40
+ ---
41
+
42
+ ## Key Features
43
+
44
+ - **Visibility timeout** — automatic requeue if worker crashes or fails to ack in time
45
+ - **Delayed tasks** — schedule jobs for future execution (e.g., 5 minutes later)
46
+ - **Concurrent processing** — process multiple jobs in parallel
47
+ - **Retry logic** — exponential backoff with configurable limits
48
+ - **Lifecycle hooks** — extend and customize every phase
49
+ - **Task chaining** — forward results between queues
50
+ - **Lua-optimized reservation** — atomic batch pulls via LMOVE or RPOPLPUSH fallback
51
+ - **Zero dependencies** — built purely on Node.js + PowerRedis + full-utils
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ npm install power-queue
57
+ # or
58
+ yarn add power-queue
59
+ ```
60
+ PowerQueue works with any Redis client compatible with IORedis interface.
61
+
62
+ ## Example Usage
63
+ ### 1. Create your custom queue
64
+ ```javascript
65
+ import { PowerQueue } from 'power-queue';
66
+
67
+ class EmailQueue extends PowerQueue {
68
+ /**
69
+ * Process a single task payload.
70
+ */
71
+ async execute(task) {
72
+ console.log('📨 Sending email:', task.payload);
73
+
74
+ // Simulate async work
75
+ await this.wait(200);
76
+
77
+ // Optionally return result
78
+ return { status: 'sent', timestamp: Date.now() };
79
+ }
80
+ }
81
+
82
+ export const emailQueue = new EmailQueue({
83
+ redis: { host: '127.0.0.1', port: 6379 },
84
+ });
85
+
86
+ ```
87
+ ### 2. Enqueue a new task
88
+ ```javascript
89
+ await emailQueue.enqueue('emails', {
90
+ to: 'user@example.com',
91
+ subject: 'Welcome!',
92
+ body: 'Hello and thanks for joining!',
93
+ });
94
+
95
+ ```
96
+ ### 3. Start processing
97
+ ```javascript
98
+ emailQueue.start('emails');
99
+
100
+ ```
101
+ That’s it — PowerQueue will:
102
+ - Pull tasks from Redis LIST atomically
103
+ - Move them into processing + visibility sets
104
+ - Retry or requeue on error or timeout
105
+ - Handle parallel processing with full isolation
106
+
107
+ ## Configuration Options
108
+ Each property is strongly typed and fully documented in TypeDoc.
109
+ | Property | Type | Default | Description |
110
+ | ---------------------- | ----------------------------------- | ------- | ---------------------------------------------- |
111
+ | `iterationTimeout` | `number` | `1000` | Delay (ms) between polling loops |
112
+ | `portionLength` | `number` | `1000` | Max number of tasks per batch pull |
113
+ | `expireStatusSec` | `number` | `300` | TTL for progress tracking |
114
+ | `maxAttempts` | `number` | `1` | Max retry attempts before marking as failed |
115
+ | `concurrency` | `number` | `32` | Parallel runners per queue |
116
+ | `visibilityTimeoutSec` | `number` | `60` | How long a task stays invisible before requeue |
117
+ | `retryBaseSec` | `number` | `1` | Base delay for exponential backoff |
118
+ | `retryMaxSec` | `number` | `3600` | Max retry delay |
119
+ | `runners` | `Map<string, { running: boolean }>` | — | Active queue execution flags |
120
+ | `processingRaw` | `Map<string, string>` | — | Tracks raw Redis entries for acknowledgment |
121
+ | `heartbeatTimers` | `Map<string, NodeJS.Timeout>` | — | Maintains active visibility extensions |
122
+
123
+
124
+ ## Design Principles
125
+ ### Minimalism
126
+ Only core Redis primitives are used — no unnecessary abstractions or event emitters.
127
+
128
+ ### Predictability
129
+ All queue state is transparent and Redis-inspectable:
130
+ - ```LIST``` for ready and processing states
131
+ - ```ZSET``` for timeouts and scheduling
132
+
133
+ ### Resilience
134
+ Every step (reserve, ack, retry, promote) can recover after process restart.
135
+
136
+ ### Extensibility
137
+ Implement custom behaviors by overriding:
138
+ ```javascript
139
+ async beforeExecute(task) {}
140
+ async afterExecute(task, result) {}
141
+ async onError(task, error) {}
142
+ async onRetry(task, delaySec) {}
143
+ ```
144
+
145
+ ## License
146
+ Use freely in your own projects. Add proper notices if you publish a package (MIT/Apache-2.0, etc.).