@push.rocks/taskbuffer 3.1.7 โ†’ 3.1.8

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,61 +1,494 @@
1
- # @push.rocks/taskbuffer
2
- flexible task management. TypeScript ready!
3
-
4
- ## Availabililty and Links
5
- * [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/taskbuffer)
6
- * [gitlab.com (source)](https://gitlab.com/push.rocks/taskbuffer)
7
- * [github.com (source mirror)](https://github.com/push.rocks/taskbuffer)
8
- * [docs (typedoc)](https://push.rocks.gitlab.io/taskbuffer/)
9
-
10
- ## Status for master
11
-
12
- Status Category | Status Badge
13
- -- | --
14
- GitLab Pipelines | [![pipeline status](https://gitlab.com/push.rocks/taskbuffer/badges/master/pipeline.svg)](https://lossless.cloud)
15
- GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/push.rocks/taskbuffer/badges/master/coverage.svg)](https://lossless.cloud)
16
- npm | [![npm downloads per month](https://badgen.net/npm/dy/@push.rocks/taskbuffer)](https://lossless.cloud)
17
- Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/push.rocks/taskbuffer)](https://lossless.cloud)
18
- TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
19
- node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
20
- Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
21
- PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@push.rocks/taskbuffer)](https://lossless.cloud)
22
- PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@push.rocks/taskbuffer)](https://lossless.cloud)
23
- BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@push.rocks/taskbuffer)](https://lossless.cloud)
24
-
25
- ## Usage
26
-
27
- We highly recommend TypeScript as this module supports **TypeScript intellisense**.
28
-
29
- ```javascript
30
- import * as taskbuffer from "taskbuffer";
31
-
32
- myTask = new taskbuffer.Task({
33
- preTask: someOtherTask // optional, don't worry loops are prevented
34
- afterTask: someOtherTask // optional, don't worry loops are prevented
35
- name:"myTask1",
36
- buffered: true, // optional
37
- bufferMax: 3, // optional, call qeues greater than this are truncated
38
- execDelay: 1000, // optional, time in ms to wait before executing task call
39
- taskFunction:() => {
40
- // do some stuff and return promise
41
- // pass on any data through promise resolution
42
- // Use TypeScript for better understanding and code completion
1
+ # @push.rocks/taskbuffer ๐Ÿš€
2
+
3
+ A **powerful**, **flexible**, and **TypeScript-first** task management library for orchestrating asynchronous operations with style. From simple task execution to complex distributed workflows, taskbuffer has got you covered.
4
+
5
+ ## Install ๐Ÿ“ฆ
6
+
7
+ ```bash
8
+ npm install @push.rocks/taskbuffer --save
9
+ ```
10
+
11
+ Or with **pnpm** (recommended):
12
+
13
+ ```bash
14
+ pnpm add @push.rocks/taskbuffer
15
+ ```
16
+
17
+ ## Why taskbuffer? ๐Ÿค”
18
+
19
+ In the modern JavaScript ecosystem, managing asynchronous tasks efficiently is crucial. Whether you're building a data pipeline, managing API rate limits, or orchestrating complex workflows, **@push.rocks/taskbuffer** provides the tools you need:
20
+
21
+ - **๐ŸŽฏ TypeScript-first**: Built with TypeScript for TypeScript - enjoy complete type safety and excellent IDE support
22
+ - **โšก Flexible execution**: From simple tasks to complex parallel workflows with dependencies
23
+ - **๐Ÿ”„ Smart buffering**: Control concurrent executions with intelligent buffer management
24
+ - **โฐ Built-in scheduling**: Cron-based task scheduling without additional dependencies
25
+ - **๐ŸŽญ Multiple paradigms**: Support for debounced, throttled, and one-time execution patterns
26
+ - **๐Ÿ”Œ Extensible**: Clean architecture that's easy to extend and customize
27
+ - **๐Ÿƒ Zero dependencies on external schedulers**: Everything you need is included
28
+
29
+ ## Core Concepts ๐ŸŽ“
30
+
31
+ ### Task
32
+ The fundamental unit of work. A task wraps an asynchronous function and provides powerful execution control.
33
+
34
+ ### Taskchain
35
+ Sequential task execution - tasks run one after another, with results passed along the chain.
36
+
37
+ ### Taskparallel
38
+ Parallel task execution - multiple tasks run simultaneously for maximum performance.
39
+
40
+ ### TaskManager
41
+ Centralized task scheduling and management using cron expressions.
42
+
43
+ ### TaskDebounced
44
+ Debounced task execution - prevents rapid repeated executions, only running after a quiet period.
45
+
46
+ ### TaskOnce
47
+ Singleton task execution - ensures a task runs exactly once, perfect for initialization routines.
48
+
49
+ ## Quick Start ๐Ÿ
50
+
51
+ ### Basic Task Execution
52
+
53
+ ```typescript
54
+ import { Task } from '@push.rocks/taskbuffer';
55
+
56
+ // Create a simple task
57
+ const myTask = new Task({
58
+ name: 'DataProcessor',
59
+ taskFunction: async () => {
60
+ const data = await fetchData();
61
+ return processData(data);
62
+ }
63
+ });
64
+
65
+ // Execute the task
66
+ const result = await myTask.trigger();
67
+ ```
68
+
69
+ ### Buffered Execution (Rate Limiting)
70
+
71
+ Perfect for API calls or database operations that need throttling:
72
+
73
+ ```typescript
74
+ const apiTask = new Task({
75
+ name: 'APICall',
76
+ taskFunction: async (endpoint: string) => {
77
+ return await fetch(endpoint);
78
+ },
79
+ buffered: true,
80
+ bufferMax: 3, // Maximum 3 concurrent executions
81
+ execDelay: 1000 // Wait 1 second between executions
82
+ });
83
+
84
+ // These will be automatically throttled
85
+ for (let i = 0; i < 10; i++) {
86
+ apiTask.trigger(`/api/data/${i}`);
87
+ }
88
+ ```
89
+
90
+ ### Task Chains - Sequential Workflows
91
+
92
+ Build complex workflows where each step depends on the previous:
93
+
94
+ ```typescript
95
+ import { Task, Taskchain } from '@push.rocks/taskbuffer';
96
+
97
+ const fetchTask = new Task({
98
+ name: 'FetchData',
99
+ taskFunction: async () => {
100
+ const response = await fetch('/api/data');
101
+ return response.json();
102
+ }
103
+ });
104
+
105
+ const transformTask = new Task({
106
+ name: 'TransformData',
107
+ taskFunction: async (data) => {
108
+ return data.map(item => ({
109
+ ...item,
110
+ processed: true,
111
+ timestamp: Date.now()
112
+ }));
113
+ }
114
+ });
115
+
116
+ const saveTask = new Task({
117
+ name: 'SaveData',
118
+ taskFunction: async (transformedData) => {
119
+ await database.bulkInsert(transformedData);
120
+ return { saved: transformedData.length };
121
+ }
122
+ });
123
+
124
+ const workflow = new Taskchain({
125
+ name: 'DataPipeline',
126
+ taskArray: [fetchTask, transformTask, saveTask]
127
+ });
128
+
129
+ // Execute the entire chain
130
+ const result = await workflow.trigger();
131
+ console.log(`Processed ${result.saved} items`);
132
+ ```
133
+
134
+ ### Parallel Execution - Maximum Performance
135
+
136
+ Execute multiple independent tasks simultaneously:
137
+
138
+ ```typescript
139
+ import { Task, Taskparallel } from '@push.rocks/taskbuffer';
140
+
141
+ const tasks = ['user', 'posts', 'comments'].map(resource =>
142
+ new Task({
143
+ name: `Fetch${resource}`,
144
+ taskFunction: async () => {
145
+ const data = await fetch(`/api/${resource}`);
146
+ return data.json();
147
+ }
148
+ })
149
+ );
150
+
151
+ const parallelFetch = new Taskparallel({
152
+ taskArray: tasks
153
+ });
154
+
155
+ // All tasks execute simultaneously
156
+ const [users, posts, comments] = await parallelFetch.trigger();
157
+ ```
158
+
159
+ ### Scheduled Tasks with TaskManager
160
+
161
+ Run tasks on a schedule using cron expressions:
162
+
163
+ ```typescript
164
+ import { Task, TaskManager } from '@push.rocks/taskbuffer';
165
+
166
+ const backupTask = new Task({
167
+ name: 'DatabaseBackup',
168
+ taskFunction: async () => {
169
+ await performBackup();
170
+ console.log(`Backup completed at ${new Date().toISOString()}`);
171
+ }
172
+ });
173
+
174
+ const manager = new TaskManager();
175
+
176
+ // Add and schedule tasks
177
+ manager.addAndScheduleTask(backupTask, '0 0 * * *'); // Daily at midnight
178
+ manager.addAndScheduleTask(healthCheck, '*/5 * * * *'); // Every 5 minutes
179
+
180
+ // Start the scheduler
181
+ manager.start();
182
+
183
+ // Later... stop if needed
184
+ manager.stop();
185
+ ```
186
+
187
+ ### Debounced Tasks - Smart Throttling
188
+
189
+ Prevent task spam with intelligent debouncing:
190
+
191
+ ```typescript
192
+ import { TaskDebounced } from '@push.rocks/taskbuffer';
193
+
194
+ const saveTask = new TaskDebounced({
195
+ name: 'AutoSave',
196
+ taskFunction: async (content: string) => {
197
+ await saveToDatabase(content);
198
+ console.log('Content saved');
199
+ },
200
+ debounceTimeInMillis: 2000 // Wait 2 seconds of inactivity
201
+ });
202
+
203
+ // Rapid calls will be debounced
204
+ input.addEventListener('input', (e) => {
205
+ saveTask.trigger(e.target.value);
206
+ });
207
+ ```
208
+
209
+ ### One-Time Tasks - Initialize Once
210
+
211
+ Ensure initialization code runs exactly once:
212
+
213
+ ```typescript
214
+ import { TaskOnce } from '@push.rocks/taskbuffer';
215
+
216
+ const initTask = new TaskOnce({
217
+ name: 'SystemInitialization',
218
+ taskFunction: async () => {
219
+ await database.connect();
220
+ await cache.initialize();
221
+ await loadConfiguration();
222
+ console.log('System initialized');
43
223
  }
44
- })
224
+ });
225
+
226
+ // Safe to call multiple times - only runs once
227
+ await initTask.trigger();
228
+ await initTask.trigger(); // This won't run again
45
229
  ```
46
230
 
47
- For further information read the linked docs at the top of this README.
231
+ ## Advanced Features ๐Ÿ”ฅ
232
+
233
+ ### Task Dependencies with Pre/Post Hooks
234
+
235
+ Create sophisticated task relationships:
236
+
237
+ ```typescript
238
+ const validationTask = new Task({
239
+ name: 'ValidateInput',
240
+ taskFunction: async (data) => {
241
+ if (!isValid(data)) {
242
+ throw new Error('Validation failed');
243
+ }
244
+ return data;
245
+ }
246
+ });
247
+
248
+ const mainTask = new Task({
249
+ name: 'ProcessData',
250
+ taskFunction: async (data) => {
251
+ return await complexProcessing(data);
252
+ },
253
+ preTask: validationTask, // Runs before main task
254
+ afterTask: cleanupTask // Runs after main task
255
+ });
256
+ ```
257
+
258
+ ### Task Runners - Distributed Execution
259
+
260
+ The TaskRunner system enables distributed task execution across multiple workers:
261
+
262
+ ```typescript
263
+ import { TaskRunner } from '@push.rocks/taskbuffer';
264
+
265
+ const runner = new TaskRunner({
266
+ name: 'WorkerNode1',
267
+ maxConcurrentTasks: 5
268
+ });
269
+
270
+ // Register tasks this runner can handle
271
+ runner.registerTask(dataProcessingTask);
272
+ runner.registerTask(imageResizeTask);
273
+
274
+ // Start processing
275
+ runner.start();
276
+ ```
277
+
278
+ ### Buffer Management Strategies
279
+
280
+ Fine-tune concurrent execution behavior:
281
+
282
+ ```typescript
283
+ const task = new Task({
284
+ name: 'ResourceIntensive',
285
+ taskFunction: async () => { /* ... */ },
286
+ buffered: true,
287
+ bufferMax: 5, // Max 5 concurrent
288
+ execDelay: 100, // 100ms between starts
289
+ timeout: 30000 // 30 second timeout
290
+ });
291
+ ```
292
+
293
+ ### Cycle Detection and Prevention
294
+
295
+ TaskBuffer automatically detects and prevents circular dependencies:
296
+
297
+ ```typescript
298
+ const taskA = new Task({
299
+ name: 'TaskA',
300
+ taskFunction: async () => { /* ... */ },
301
+ preTask: taskB // This would create a cycle
302
+ });
303
+
304
+ const taskB = new Task({
305
+ name: 'TaskB',
306
+ taskFunction: async () => { /* ... */ },
307
+ preTask: taskA // Circular dependency detected!
308
+ });
309
+ ```
310
+
311
+ ### Dynamic Task Creation
312
+
313
+ Create tasks on-the-fly based on runtime conditions:
314
+
315
+ ```typescript
316
+ const dynamicWorkflow = async (config: Config) => {
317
+ const tasks = config.steps.map(step =>
318
+ new Task({
319
+ name: step.name,
320
+ taskFunction: async (input) => {
321
+ return await processStep(step, input);
322
+ }
323
+ })
324
+ );
325
+
326
+ const chain = new Taskchain({
327
+ name: 'DynamicWorkflow',
328
+ taskArray: tasks
329
+ });
330
+
331
+ return await chain.trigger();
332
+ };
333
+ ```
334
+
335
+ ## API Reference ๐Ÿ“š
336
+
337
+ ### Task Options
338
+
339
+ | Option | Type | Description |
340
+ |--------|------|-------------|
341
+ | `name` | `string` | Unique identifier for the task |
342
+ | `taskFunction` | `Function` | Async function to execute |
343
+ | `buffered` | `boolean` | Enable buffer management |
344
+ | `bufferMax` | `number` | Maximum concurrent executions |
345
+ | `execDelay` | `number` | Delay between executions (ms) |
346
+ | `timeout` | `number` | Task timeout (ms) |
347
+ | `preTask` | `Task` | Task to run before |
348
+ | `afterTask` | `Task` | Task to run after |
349
+
350
+ ### TaskManager Methods
351
+
352
+ | Method | Description |
353
+ |--------|-------------|
354
+ | `addTask(task, cronExpression)` | Add and schedule a task |
355
+ | `removeTask(taskName)` | Remove a scheduled task |
356
+ | `start()` | Start the scheduler |
357
+ | `stop()` | Stop the scheduler |
358
+ | `getStats()` | Get execution statistics |
359
+
360
+ ### Taskchain Methods
361
+
362
+ | Method | Description |
363
+ |--------|-------------|
364
+ | `addTask(task)` | Add task to chain |
365
+ | `removeTask(taskName)` | Remove task from chain |
366
+ | `trigger(initialValue)` | Execute the chain |
367
+ | `reset()` | Reset chain state |
368
+
369
+ ## Performance Tips ๐ŸŽ๏ธ
370
+
371
+ 1. **Use buffering for I/O operations**: Prevents overwhelming external services
372
+ 2. **Leverage parallel execution**: When tasks are independent, run them simultaneously
373
+ 3. **Implement proper error handling**: Use try-catch in task functions
374
+ 4. **Monitor task execution**: Use the built-in stats and logging
375
+ 5. **Set appropriate timeouts**: Prevent hanging tasks from blocking your system
376
+
377
+ ## Error Handling ๐Ÿ›ก๏ธ
378
+
379
+ ```typescript
380
+ const robustTask = new Task({
381
+ name: 'RobustOperation',
382
+ taskFunction: async (input) => {
383
+ try {
384
+ return await riskyOperation(input);
385
+ } catch (error) {
386
+ // Log error
387
+ console.error(`Task failed: ${error.message}`);
388
+
389
+ // Optionally retry
390
+ if (error.retryable) {
391
+ return await riskyOperation(input);
392
+ }
393
+
394
+ // Or return default value
395
+ return defaultValue;
396
+ }
397
+ },
398
+ timeout: 5000 // Fail if takes longer than 5 seconds
399
+ });
400
+ ```
401
+
402
+ ## Real-World Examples ๐ŸŒ
403
+
404
+ ### API Rate Limiting
405
+
406
+ ```typescript
407
+ const apiClient = new Task({
408
+ name: 'RateLimitedAPI',
409
+ taskFunction: async (endpoint: string) => {
410
+ return await fetch(`https://api.example.com${endpoint}`);
411
+ },
412
+ buffered: true,
413
+ bufferMax: 10, // 10 requests
414
+ execDelay: 100 // Per 100ms = 100 req/s max
415
+ });
416
+ ```
417
+
418
+ ### Database Migration Pipeline
419
+
420
+ ```typescript
421
+ const migrationChain = new Taskchain({
422
+ name: 'DatabaseMigration',
423
+ taskArray: [
424
+ backupTask,
425
+ schemaUpdateTask,
426
+ dataTransformTask,
427
+ validationTask,
428
+ cleanupTask
429
+ ]
430
+ });
431
+ ```
432
+
433
+ ### Microservice Health Monitoring
434
+
435
+ ```typescript
436
+ const healthMonitor = new TaskManager();
437
+
438
+ services.forEach(service => {
439
+ const healthCheck = new Task({
440
+ name: `HealthCheck:${service.name}`,
441
+ taskFunction: async () => {
442
+ const healthy = await checkHealth(service.url);
443
+ if (!healthy) {
444
+ await alertOps(service);
445
+ }
446
+ }
447
+ });
448
+
449
+ healthMonitor.addAndScheduleTask(healthCheck, '*/1 * * * *'); // Every minute
450
+ });
451
+ ```
452
+
453
+ ## Testing ๐Ÿงช
454
+
455
+ ```typescript
456
+ import { expect, tap } from '@git.zone/tstest';
457
+ import { Task } from '@push.rocks/taskbuffer';
458
+
459
+ tap.test('should execute task successfully', async () => {
460
+ const result = await myTask.trigger();
461
+ expect(result).toEqual(expectedValue);
462
+ });
463
+
464
+ tap.start();
465
+ ```
466
+
467
+ ## Contributing ๐Ÿค
468
+
469
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
470
+
471
+ ## Support ๐Ÿ’ฌ
472
+
473
+ - ๐Ÿ“ง Email: [hello@task.vc](mailto:hello@task.vc)
474
+ - ๐Ÿ› Issues: [GitHub Issues](https://github.com/push-rocks/taskbuffer/issues)
475
+ - ๐Ÿ“– Docs: [Documentation](https://code.foss.global/push.rocks/taskbuffer)
476
+
477
+ ## License and Legal Information
478
+
479
+ This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
480
+
481
+ **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
48
482
 
49
- > MIT licensed | **&copy;** [Lossless GmbH](https://lossless.gmbh)
483
+ ### Trademarks
50
484
 
51
- [![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://push.rocks)
485
+ This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
52
486
 
53
- ## Contribution
487
+ ### Company Information
54
488
 
55
- We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
489
+ Task Venture Capital GmbH
490
+ Registered at District court Bremen HRB 35230 HB, Germany
56
491
 
57
- For further information read the linked docs at the top of this readme.
492
+ For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
58
493
 
59
- ## Legal
60
- > MIT licensed | **&copy;** [Task Venture Capital GmbH](https://task.vc)
61
- | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
494
+ By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
@@ -1,8 +1,8 @@
1
1
  /**
2
- * autocreated commitinfo by @pushrocks/commitinfo
2
+ * autocreated commitinfo by @push.rocks/commitinfo
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/taskbuffer',
6
- version: '3.1.7',
7
- description: 'flexible task management. TypeScript ready!'
6
+ version: '3.1.8',
7
+ description: 'A flexible task management library supporting TypeScript, allowing for task buffering, scheduling, and execution with dependency management.'
8
8
  }