@mrjacket/ahko 0.6.0 → 1.1.0
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/CHANGELOG.md +59 -0
- package/README.md +142 -15
- package/dist/ahko.d.ts +80 -11
- package/dist/config/config-loader.d.ts +31 -0
- package/dist/config/index.d.ts +1 -0
- package/dist/errors/circuit-breaker.error.d.ts +24 -0
- package/dist/errors/index.d.ts +1 -0
- package/dist/index.cjs +651 -85
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.js +637 -84
- package/dist/index.js.map +1 -1
- package/dist/models/circuit-breaker.model.d.ts +39 -0
- package/dist/models/config.model.d.ts +23 -0
- package/dist/models/index.d.ts +3 -0
- package/dist/models/options.model.d.ts +23 -0
- package/dist/models/priority.model.d.ts +18 -0
- package/dist/models/stats.model.d.ts +5 -0
- package/dist/scheduler/circuit-breaker.d.ts +56 -0
- package/dist/scheduler/debounce-coordinator.d.ts +2 -0
- package/dist/scheduler/task-queue.d.ts +29 -4
- package/dist/scheduler/task-runner.d.ts +9 -0
- package/dist/scheduler/throttle-coordinator.d.ts +2 -0
- package/dist/version.d.ts +1 -1
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,65 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.1.0] - 2026-09-23 — Declarative Config, Circuit Breaker & Priority Queue
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- Declarative configuration file support via `config.ahko.json` with multi-profile support (e.g. `default`, `crawler`, `critical-gateway`).
|
|
12
|
+
- Static configuration loaders: `Ahko.loadConfig(config)` for universal programmatic profile loading (Node.js & browser), `Ahko.loadConfigFile(path?)` for asynchronous filesystem loading, and `Ahko.fromProfile(name, overrides?)`.
|
|
13
|
+
- Martin Fowler Circuit Breaker pattern with `ECircuitState` (`CLOSED`, `OPEN`, `HALF_OPEN`), `CircuitBreakerCoordinator`, and `AhkoCircuitBreakerOpenError`:
|
|
14
|
+
- Protects downstream services by tracking consecutive failures against a `failureThreshold`.
|
|
15
|
+
- Fast-fails pending and incoming tasks without execution when OPEN.
|
|
16
|
+
- Automatically transitions to HALF_OPEN after `resetTimeoutMs` cooldown to allow a recovery trial.
|
|
17
|
+
- Heals to CLOSED on trial success or immediately re-trips to OPEN on trial failure.
|
|
18
|
+
- Priority queue scheduling with stable FIFO ordering:
|
|
19
|
+
- Supports named priorities (`"high"`, `"normal"`, `"low"`) and arbitrary numerical weights (e.g. `100`, `-5`).
|
|
20
|
+
- Tasks with higher priority preempt lower priority tasks in the queue; tasks with identical priority preserve strict FIFO ordering.
|
|
21
|
+
- Queue flow control via `ahko.pause()`, `ahko.resume()`, and `ahko.isPaused()`:
|
|
22
|
+
- Halts dispatching pending tasks without interrupting currently executing tasks.
|
|
23
|
+
- Immediately dispatches accumulated tasks upon resume up to concurrency limits.
|
|
24
|
+
- Total Timeout Budget (`totalTimeoutMs`):
|
|
25
|
+
- Sets an overarching execution deadline spanning queue wait time, execution, and retry delays.
|
|
26
|
+
- Cancels task runners cleanly with `AhkoTimeoutError` when the budget expires.
|
|
27
|
+
- Ergonomic function wrapping via `ahko.wrap(fn, options)`:
|
|
28
|
+
- Wraps any sync or async function returning a decorated function routed through the scheduler with pre-configured priorities and options.
|
|
29
|
+
- New runnable examples:
|
|
30
|
+
- `examples/07-circuit-breaker.mjs`: circuit breaker tripping, fast-failing, and cooldown recovery.
|
|
31
|
+
- `examples/08-priority-queue.mjs`: priority queue ordering and pause/resume flow control.
|
|
32
|
+
- `config.ahko.example.json`: reference declarative schema configuration file.
|
|
33
|
+
- Extended telemetry in `ahko.stats()`: `isPaused` boolean and `circuitState` indicator.
|
|
34
|
+
|
|
35
|
+
### Fixed
|
|
36
|
+
- Remediated 2 CodeQL static analysis security alerts:
|
|
37
|
+
- Alert #4: Removed unused `externalController` declaration in `src/__tests__/e2e.test.ts`.
|
|
38
|
+
- Alert #3: Removed unused `sleep` helper declaration in `examples/04-retry-backoff-jitter.mjs`.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## [1.0.0] - 2026-09-23 — Stable Scheduler Release
|
|
43
|
+
|
|
44
|
+
### Added
|
|
45
|
+
- Comprehensive End-to-End stress and integration test suite (`src/__tests__/e2e.test.ts`) verifying:
|
|
46
|
+
- High-concurrency bursts under rate-limited temporal pacing (`minIntervalMs`) and jittered backoff retries.
|
|
47
|
+
- Interleaved interactive debounce and throttle streams under queue contention.
|
|
48
|
+
- Cooperative cancellation waves simulating document switches or build cancellations (VS Code / CLI scenarios).
|
|
49
|
+
- Graceful shutdown workflows clearing pending queues while allowing in-flight tasks to settle cleanly (`ahko.chill()`).
|
|
50
|
+
- Full lifecycle telemetry stream validation and microservice uncooperative timeout handling.
|
|
51
|
+
- Standalone runnable examples suite (`examples/`) with dedicated `examples/README.md`:
|
|
52
|
+
- `01-concurrency-and-pacing.mjs`: concurrency limits and temporal pacing.
|
|
53
|
+
- `02-debounce-search.mjs`: debounced interactive search with Promise coalescing.
|
|
54
|
+
- `03-throttle-events.mjs`: high-frequency event stream throttling.
|
|
55
|
+
- `04-retry-backoff-jitter.mjs`: resilient retries with exponential backoff and full jitter.
|
|
56
|
+
- `05-idle-telemetry.mjs`: non-blocking background tasks and lifecycle event logging.
|
|
57
|
+
- `06-graceful-shutdown.mjs`: safe process termination sequence.
|
|
58
|
+
- Dedicated npm script `"test:e2e"` for focused integration testing.
|
|
59
|
+
- Documentation restructuring into domain guides (`docs/guides/`) and specifications (`docs/architecture/`), including production architectural recipes (`recipes.md`).
|
|
60
|
+
|
|
61
|
+
### Changed
|
|
62
|
+
- Connected `DebounceCoordinator` and `ThrottleCoordinator` settlement lifecycles directly to `TaskQueue.checkIdle()`, ensuring that window expirations and coordinator deletions deterministically resolve idle promises and emit `"idle"` events.
|
|
63
|
+
- Transitioned version to stable 1.0.0 baseline with frozen zero-dependency architecture.
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
8
67
|
## [0.6.0] - 2026-09-23 — Telemetry & DX
|
|
9
68
|
|
|
10
69
|
### Added
|
package/README.md
CHANGED
|
@@ -13,10 +13,10 @@
|
|
|
13
13
|
<img src="https://img.shields.io/npm/v/@mrjacket/ahko.svg?color=success" alt="npm version">
|
|
14
14
|
</a>
|
|
15
15
|
<a href="https://www.npmjs.com/package/@mrjacket/ahko">
|
|
16
|
-
<img src="https://img.shields.io/
|
|
16
|
+
<img src="https://img.shields.io/node/v/@mrjacket/ahko.svg" alt="node">
|
|
17
17
|
</a>
|
|
18
18
|
<a href="https://www.npmjs.com/package/@mrjacket/ahko">
|
|
19
|
-
<img src="https://img.shields.io/
|
|
19
|
+
<img src="https://img.shields.io/npm/dm/@mrjacket/ahko.svg" alt="npm downloads">
|
|
20
20
|
</a>
|
|
21
21
|
<a href="https://github.com/x-name15/ahko/actions/workflows/ci.yml">
|
|
22
22
|
<img src="https://github.com/x-name15/ahko/actions/workflows/ci.yml/badge.svg" alt="ci">
|
|
@@ -30,12 +30,6 @@
|
|
|
30
30
|
<a href="https://www.npmjs.com/package/@mrjacket/ahko">
|
|
31
31
|
<img src="https://img.shields.io/badge/dependencies-0-success" alt="zero dependencies">
|
|
32
32
|
</a>
|
|
33
|
-
<a href="https://bundlephobia.com/package/@mrjacket/ahko">
|
|
34
|
-
<img src="https://img.shields.io/bundlephobia/minzip/@mrjacket/ahko?color=purple" alt="bundle size">
|
|
35
|
-
</a>
|
|
36
|
-
<a href="https://github.com/x-name15/ahko">
|
|
37
|
-
<img src="https://img.shields.io/badge/TypeScript-Ready-3178C6?logo=typescript&logoColor=white" alt="TypeScript">
|
|
38
|
-
</a>
|
|
39
33
|
<a href="https://github.com/x-name15/ahko/issues">
|
|
40
34
|
<img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome">
|
|
41
35
|
</a>
|
|
@@ -290,6 +284,119 @@ console.log(ahko.battery());
|
|
|
290
284
|
// { level: 3, chill: true, status: "low-energy", quote: "Mwee... my battery is low, but all your tasks are handled completely chill." }
|
|
291
285
|
```
|
|
292
286
|
|
|
287
|
+
### 12. Priority-Aware Scheduling
|
|
288
|
+
|
|
289
|
+
Ensure critical tasks jump ahead of normal or background work while preserving strict FIFO ordering among peers:
|
|
290
|
+
|
|
291
|
+
```typescript
|
|
292
|
+
// Named priorities: "high" (10), "normal" (0), "low" (-10), or custom numeric weights
|
|
293
|
+
await ahko.schedule(criticalTask, { priority: "high" });
|
|
294
|
+
await ahko.schedule(backgroundSync, { priority: "low" });
|
|
295
|
+
await ahko.schedule(superUrgent, { priority: 100 });
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
### 13. Circuit Breaker Protection
|
|
299
|
+
|
|
300
|
+
Protect fragile downstream services and databases from cascading failures. When consecutive failures meet `failureThreshold`, the circuit trips to `OPEN` and fast-fails tasks immediately without execution:
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
const ahko = new Ahko({
|
|
304
|
+
concurrency: 2,
|
|
305
|
+
circuitBreaker: {
|
|
306
|
+
failureThreshold: 3, // trip after 3 consecutive failures
|
|
307
|
+
resetTimeoutMs: 15000, // wait 15s before attempting recovery probe
|
|
308
|
+
},
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
try {
|
|
312
|
+
await ahko.schedule(callFlakyService);
|
|
313
|
+
} catch (err) {
|
|
314
|
+
if (err instanceof AhkoCircuitBreakerOpenError) {
|
|
315
|
+
console.warn("Fast-failed: Circuit breaker is OPEN!");
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
### 14. Pause & Resume Flow Control
|
|
321
|
+
|
|
322
|
+
Temporarily halt queue dispatching without aborting in-flight tasks. Resuming immediately pumps accumulated tasks up to capacity:
|
|
323
|
+
|
|
324
|
+
```typescript
|
|
325
|
+
// Stop dispatching new tasks
|
|
326
|
+
ahko.pause();
|
|
327
|
+
console.log(ahko.isPaused()); // true
|
|
328
|
+
|
|
329
|
+
// In-flight tasks finish peacefully...
|
|
330
|
+
|
|
331
|
+
// Resume dispatching
|
|
332
|
+
ahko.resume();
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
### 15. Total Timeout Budget
|
|
336
|
+
|
|
337
|
+
Enforce an overarching deadline spanning queue wait time, execution, and retries:
|
|
338
|
+
|
|
339
|
+
```typescript
|
|
340
|
+
// Task will abort with AhkoTimeoutError if total elapsed time exceeds 5000ms
|
|
341
|
+
await ahko.schedule(fetchWithRetries, {
|
|
342
|
+
totalTimeoutMs: 5000,
|
|
343
|
+
retry: { attempts: 3, baseDelay: 1000 },
|
|
344
|
+
});
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
### 16. Function Wrapping (`ahko.wrap`)
|
|
348
|
+
|
|
349
|
+
Decorate any async function to automatically route every invocation through Ahko:
|
|
350
|
+
|
|
351
|
+
```typescript
|
|
352
|
+
const fetchUser = ahko.wrap(
|
|
353
|
+
async (userId: string) => {
|
|
354
|
+
const res = await fetch(`https://api.example.com/users/${userId}`);
|
|
355
|
+
return res.json();
|
|
356
|
+
},
|
|
357
|
+
{ priority: "high", retry: { attempts: 2 } }
|
|
358
|
+
);
|
|
359
|
+
|
|
360
|
+
// Seamlessly executed via scheduler
|
|
361
|
+
const user = await fetchUser("usr_42");
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
### 17. Declarative Configuration (`config.ahko.json`)
|
|
365
|
+
|
|
366
|
+
Define scheduler defaults and workload profiles cleanly in JSON:
|
|
367
|
+
|
|
368
|
+
```json
|
|
369
|
+
{
|
|
370
|
+
"default": {
|
|
371
|
+
"concurrency": 2,
|
|
372
|
+
"minIntervalMs": 50,
|
|
373
|
+
"priority": "normal"
|
|
374
|
+
},
|
|
375
|
+
"profiles": {
|
|
376
|
+
"crawler": {
|
|
377
|
+
"concurrency": 4,
|
|
378
|
+
"minIntervalMs": 200,
|
|
379
|
+
"priority": "low"
|
|
380
|
+
},
|
|
381
|
+
"critical-gateway": {
|
|
382
|
+
"concurrency": 1,
|
|
383
|
+
"circuitBreaker": {
|
|
384
|
+
"failureThreshold": 3,
|
|
385
|
+
"resetTimeoutMs": 10000
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
```typescript
|
|
393
|
+
// Programmatically or from config file:
|
|
394
|
+
Ahko.loadConfig(config);
|
|
395
|
+
|
|
396
|
+
// Instantiate configured scheduler from profile
|
|
397
|
+
const gateway = Ahko.fromProfile("critical-gateway");
|
|
398
|
+
```
|
|
399
|
+
|
|
293
400
|
---
|
|
294
401
|
|
|
295
402
|
## Documentation
|
|
@@ -300,24 +407,29 @@ Comprehensive guides and technical documentation are available in the [`docs/`](
|
|
|
300
407
|
|---|---|
|
|
301
408
|
| [**Documentation Portal**](./docs/README.md) | Master overview and index of all guides and specifications. |
|
|
302
409
|
| [**Getting Started**](./docs/guides/getting-started.md) | Quickstart guide, installation, and fundamental usage patterns. |
|
|
410
|
+
| [**Declarative Configuration**](./docs/guides/configuration.md) | Centralizing limits in `config.ahko.json`, `$schema` validation, named profiles, and fallback rules. |
|
|
303
411
|
| [**Library API**](./docs/guides/library.md) | Complete programmatic API reference, TypeScript interfaces, and options. |
|
|
304
412
|
| [**Production Recipes**](./docs/guides/recipes.md) | Battle-tested recipes (paced API client, debounced search, throttled scroll, graceful shutdown). |
|
|
305
413
|
| [**Architecture**](./docs/architecture/ARCHITECTURE.md) | Architectural specifications, lifecycle state machine, and design decisions. |
|
|
306
|
-
| [**Roadmap**](./docs/architecture/ROADMAP.md) | Milestone progression from 0.1.0 through 1.
|
|
414
|
+
| [**Roadmap**](./docs/architecture/ROADMAP.md) | Milestone progression from 0.1.0 through 1.1.0. |
|
|
307
415
|
| [**Engineering Log**](./docs/architecture/LOG.md) | Chronological log of engineering decisions and ADRs. |
|
|
308
416
|
|
|
417
|
+
> **Runnable Examples:** A comprehensive suite of standalone, runnable Node.js scripts is available in the [`examples/`](./examples/) folder. See [`examples/README.md`](./examples/README.md) for details.
|
|
418
|
+
|
|
309
419
|
---
|
|
310
420
|
|
|
311
421
|
## API Reference
|
|
312
422
|
|
|
313
423
|
### `new Ahko(options?: IAhkoOptions)`
|
|
314
424
|
|
|
315
|
-
Creates an
|
|
425
|
+
Creates an ahko scheduler instance.
|
|
316
426
|
|
|
317
427
|
| Option | Type | Default | Description |
|
|
318
428
|
|---|---|---|---|
|
|
319
429
|
| `concurrency` | `number` | `Infinity` | Maximum concurrent tasks allowed to run simultaneously. Must be $\ge 1$. |
|
|
320
430
|
| `minIntervalMs` | `number` | `0` | Minimum interval in milliseconds between consecutive task starts. Must be $\ge 0$. |
|
|
431
|
+
| `circuitBreaker` | `ICircuitBreakerOptions` | `undefined` | Optional failure threshold and cooldown reset configuration. |
|
|
432
|
+
| `profile` | `string` | `undefined` | Name of declarative profile to inherit settings from. |
|
|
321
433
|
|
|
322
434
|
### `ahko.schedule<T>(task: ITask<T>, options?: IScheduleOptions): Promise<T>`
|
|
323
435
|
|
|
@@ -326,23 +438,37 @@ Schedules an asynchronous task with full return type inference.
|
|
|
326
438
|
| Option | Type | Default | Description |
|
|
327
439
|
|---|---|---|---|
|
|
328
440
|
| `strategy` | `"immediate" \| "delay" \| "idle" \| "throttle" \| "debounce"` | `"immediate"` | Scheduling execution strategy. |
|
|
441
|
+
| `priority` | `"high" \| "normal" \| "low" \| number` | `"normal"` | Task priority weight for queue ordering. |
|
|
329
442
|
| `delay` | `number` | `0` | Delay in milliseconds when strategy is `"delay"`. |
|
|
330
443
|
| `key` | `string \| symbol` | `undefined` | Explicit identity key for `"debounce"` and `"throttle"`. |
|
|
331
444
|
| `waitMs` | `number` | `undefined` | Window duration in ms for debounce quiet period or throttle interval. |
|
|
332
445
|
| `idleTimeout` | `number` | `undefined` | Maximum time to wait for idle window before forcing queue entry. |
|
|
333
446
|
| `retry` | `IRetryOptions` | `undefined` | Automatic retry policy (attempts, backoff, jitter, predicate). |
|
|
334
447
|
| `timeoutMs` | `number` | `undefined` | Maximum execution duration in milliseconds per attempt before aborting with `AhkoTimeoutError`. |
|
|
448
|
+
| `totalTimeoutMs` | `number` | `undefined` | Total execution budget across wait time, retries, and execution. |
|
|
335
449
|
| `signal` | `AbortSignal` | `undefined` | Optional external `AbortSignal` for cooperative cancellation. |
|
|
336
450
|
|
|
337
|
-
### `ahko.
|
|
451
|
+
### `ahko.wrap(fn, options?)`
|
|
452
|
+
|
|
453
|
+
Returns a wrapped version of `fn` routed through the scheduler.
|
|
454
|
+
|
|
455
|
+
### `ahko.pause() / ahko.resume() / ahko.isPaused()`
|
|
456
|
+
|
|
457
|
+
Pauses and resumes task dispatching.
|
|
458
|
+
|
|
459
|
+
### `ahko.circuitState`
|
|
460
|
+
|
|
461
|
+
Returns current circuit breaker state (`"closed" | "open" | "half_open"` or `undefined`).
|
|
462
|
+
|
|
463
|
+
### `ahko.debounce<T>(key, task, waitMs, options?): Promise<T>`
|
|
338
464
|
|
|
339
465
|
Convenience method scheduling a debounced task with key-based Promise coalescing.
|
|
340
466
|
|
|
341
|
-
### `ahko.throttle<T>(key
|
|
467
|
+
### `ahko.throttle<T>(key, task, waitMs, options?): Promise<T>`
|
|
342
468
|
|
|
343
469
|
Convenience method scheduling a throttled task with leading execution and coalesced trailing run.
|
|
344
470
|
|
|
345
|
-
### `ahko.idle<T>(task
|
|
471
|
+
### `ahko.idle<T>(task, options?): Promise<T>`
|
|
346
472
|
|
|
347
473
|
Convenience method scheduling a task under `strategy: "idle"`.
|
|
348
474
|
|
|
@@ -376,7 +502,7 @@ Returns mascot battery status and quote.
|
|
|
376
502
|
|
|
377
503
|
### `ahko.stats(): IAhkoStats`
|
|
378
504
|
|
|
379
|
-
Returns a snapshot of current task counters, retry counts, total dispatches, and queue capacity.
|
|
505
|
+
Returns a snapshot of current task counters, retry counts, total dispatches, pause status, circuit state, and queue capacity.
|
|
380
506
|
|
|
381
507
|
---
|
|
382
508
|
|
|
@@ -388,7 +514,8 @@ All scheduler errors inherit from `AhkoError`:
|
|
|
388
514
|
- `AhkoCancellationError`: Thrown when a task is aborted.
|
|
389
515
|
- `AhkoConfigurationError`: Thrown when invalid options are provided.
|
|
390
516
|
- `AhkoQueueError`: Thrown when queue constraints are violated.
|
|
391
|
-
- `AhkoTimeoutError`: Thrown when a task exceeds its configured duration.
|
|
517
|
+
- `AhkoTimeoutError`: Thrown when a task exceeds its configured duration or totalTimeoutMs.
|
|
518
|
+
- `AhkoCircuitBreakerOpenError`: Thrown when task execution is fast-failed because the circuit breaker is OPEN.
|
|
392
519
|
|
|
393
520
|
---
|
|
394
521
|
|
package/dist/ahko.d.ts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
+
import type { ECircuitState } from "./models/circuit-breaker.model.js";
|
|
2
|
+
import type { IAhkoFileConfig } from "./models/config.model.js";
|
|
1
3
|
import type { TAhkoEventName, TAhkoEventHandler, TAhkoUnsubscribe } from "./models/events.model.js";
|
|
2
4
|
import type { IAhkoOptions, IScheduleOptions } from "./models/options.model.js";
|
|
3
5
|
import type { IAhkoStats } from "./models/stats.model.js";
|
|
4
6
|
import type { ITask } from "./models/task.model.js";
|
|
7
|
+
import type { CircuitBreakerCoordinator } from "./scheduler/circuit-breaker.js";
|
|
5
8
|
/**
|
|
6
9
|
* Ahko — Low-energy asynchronous task scheduler.
|
|
7
10
|
*
|
|
8
|
-
* Coordinates execution timing, enforces concurrency limits,
|
|
9
|
-
*
|
|
11
|
+
* Coordinates execution timing, enforces concurrency limits, manages priorities,
|
|
12
|
+
* provides circuit-breaker stability, supports pause/resume flow control,
|
|
13
|
+
* and cooperates natively with AbortSignal cancellation.
|
|
10
14
|
*
|
|
11
15
|
* @example
|
|
12
16
|
* ```typescript
|
|
@@ -23,6 +27,37 @@ import type { ITask } from "./models/task.model.js";
|
|
|
23
27
|
export declare class Ahko {
|
|
24
28
|
/** Internal queue and concurrency manager */
|
|
25
29
|
private readonly queue;
|
|
30
|
+
/** Default schedule options inherited from profile if configured */
|
|
31
|
+
private readonly defaultScheduleOptions?;
|
|
32
|
+
/**
|
|
33
|
+
* Programmatically loads a declarative configuration into memory.
|
|
34
|
+
* Works universally across Node.js, browsers, and edge runtimes.
|
|
35
|
+
*
|
|
36
|
+
* @param config - File configuration object containing default and named profiles.
|
|
37
|
+
*/
|
|
38
|
+
static loadConfig(config: IAhkoFileConfig): void;
|
|
39
|
+
/**
|
|
40
|
+
* Asynchronously loads a configuration file from disk (Node.js).
|
|
41
|
+
*
|
|
42
|
+
* @param filePath - Path to configuration file (default: "config.ahko.json").
|
|
43
|
+
*/
|
|
44
|
+
static loadConfigFile(filePath?: string): Promise<IAhkoFileConfig | undefined>;
|
|
45
|
+
/**
|
|
46
|
+
* Resets the active declarative configuration.
|
|
47
|
+
*/
|
|
48
|
+
static resetConfig(): void;
|
|
49
|
+
/**
|
|
50
|
+
* Retrieves the currently active declarative configuration.
|
|
51
|
+
*/
|
|
52
|
+
static getActiveConfig(): IAhkoFileConfig | undefined;
|
|
53
|
+
/**
|
|
54
|
+
* Instantiates an Ahko scheduler initialized with settings from a declarative profile.
|
|
55
|
+
*
|
|
56
|
+
* @param profileName - Optional name of the profile (e.g. "api", "background").
|
|
57
|
+
* @param overrides - Optional scheduler options overriding profile values.
|
|
58
|
+
* @returns A new configured Ahko instance.
|
|
59
|
+
*/
|
|
60
|
+
static fromProfile(profileName?: string, overrides?: IAhkoOptions): Ahko;
|
|
26
61
|
/**
|
|
27
62
|
* Initializes a new Ahko scheduler instance.
|
|
28
63
|
*
|
|
@@ -35,28 +70,62 @@ export declare class Ahko {
|
|
|
35
70
|
* ```
|
|
36
71
|
*/
|
|
37
72
|
constructor(options?: IAhkoOptions);
|
|
73
|
+
/**
|
|
74
|
+
* Pauses scheduler dispatch. In-flight tasks run to completion, but pending tasks remain queued.
|
|
75
|
+
*/
|
|
76
|
+
pause(): void;
|
|
77
|
+
/**
|
|
78
|
+
* Resumes scheduler dispatch, immediately executing waiting tasks up to available concurrency.
|
|
79
|
+
*/
|
|
80
|
+
resume(): void;
|
|
81
|
+
/**
|
|
82
|
+
* Checks whether the scheduler is currently paused.
|
|
83
|
+
*/
|
|
84
|
+
isPaused(): boolean;
|
|
85
|
+
/**
|
|
86
|
+
* Current circuit breaker state if circuit breaker protection is configured.
|
|
87
|
+
*/
|
|
88
|
+
get circuitState(): ECircuitState | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* Access to the underlying circuit breaker coordinator instance if configured.
|
|
91
|
+
*/
|
|
92
|
+
get circuitBreaker(): CircuitBreakerCoordinator | undefined;
|
|
93
|
+
/**
|
|
94
|
+
* Wraps an async function so every execution is automatically routed through this Ahko scheduler.
|
|
95
|
+
*
|
|
96
|
+
* @template TArgs - Parameter types of the wrapped function.
|
|
97
|
+
* @template TReturn - Return type of the wrapped function.
|
|
98
|
+
* @param fn - The function to wrap.
|
|
99
|
+
* @param options - Optional scheduling options applied to every wrapped call.
|
|
100
|
+
* @returns A wrapped function returning a Promise.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```typescript
|
|
104
|
+
* const fetchUser = ahko.wrap(async (id: string) => api.getUser(id), { priority: "high" });
|
|
105
|
+
* const user = await fetchUser("usr_123");
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
wrap<TArgs extends unknown[], TReturn>(fn: (...args: TArgs) => Promise<TReturn> | TReturn, options?: IScheduleOptions): (...args: TArgs) => Promise<TReturn>;
|
|
38
109
|
/**
|
|
39
110
|
* Schedules a task for execution with full return type inference.
|
|
40
111
|
*
|
|
41
112
|
* @template T - Inferred return type of the task.
|
|
42
113
|
* @param task - Asynchronous or synchronous task function accepting an {@link ITaskContext}.
|
|
43
|
-
* @param options - Task-specific scheduling options such as strategy, delay, and cancellation signal.
|
|
114
|
+
* @param options - Task-specific scheduling options such as strategy, priority, delay, and cancellation signal.
|
|
44
115
|
* @returns A promise that resolves with the task's return value.
|
|
45
116
|
*
|
|
46
117
|
* @throws {AhkoConfigurationError} If the task is not a function or options are invalid.
|
|
47
118
|
* @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.
|
|
48
|
-
* @throws {AhkoTimeoutError} If task execution exceeds timeoutMs.
|
|
119
|
+
* @throws {AhkoTimeoutError} If task execution exceeds timeoutMs or totalTimeoutMs.
|
|
120
|
+
* @throws {AhkoCircuitBreakerOpenError} If the circuit breaker is OPEN and rejects the execution.
|
|
49
121
|
*
|
|
50
122
|
* @example
|
|
51
123
|
* ```typescript
|
|
52
124
|
* // Immediate execution (subject to concurrency)
|
|
53
125
|
* const count = await ahko.schedule(async () => 42);
|
|
54
126
|
*
|
|
55
|
-
* //
|
|
56
|
-
* await ahko.schedule(
|
|
57
|
-
* async ({ signal }) => doWork({ signal }),
|
|
58
|
-
* { strategy: "delay", delay: 1000 }
|
|
59
|
-
* );
|
|
127
|
+
* // High priority task
|
|
128
|
+
* await ahko.schedule(doUrgentWork, { priority: "high" });
|
|
60
129
|
* ```
|
|
61
130
|
*/
|
|
62
131
|
schedule<T>(task: ITask<T>, options?: IScheduleOptions): Promise<T>;
|
|
@@ -102,12 +171,12 @@ export declare class Ahko {
|
|
|
102
171
|
/**
|
|
103
172
|
* Retrieves real-time telemetry metrics from the scheduler.
|
|
104
173
|
*
|
|
105
|
-
* @returns An {@link IAhkoStats} snapshot of active, pending, completed, failed, cancelled,
|
|
174
|
+
* @returns An {@link IAhkoStats} snapshot of active, pending, completed, failed, cancelled, timed out tasks, pause status, and circuit state.
|
|
106
175
|
*
|
|
107
176
|
* @example
|
|
108
177
|
* ```typescript
|
|
109
178
|
* const stats = ahko.stats();
|
|
110
|
-
* console.log(`Active: ${stats.activeTasks}, Pending: ${stats.pendingTasks}`);
|
|
179
|
+
* console.log(`Active: ${stats.activeTasks}, Pending: ${stats.pendingTasks}, Paused: ${stats.isPaused}`);
|
|
111
180
|
* ```
|
|
112
181
|
*/
|
|
113
182
|
stats(): IAhkoStats;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { IAhkoFileConfig, IAhkoProfileConfig } from "../models/config.model.js";
|
|
2
|
+
/**
|
|
3
|
+
* Programmatically loads and activates a declarative configuration.
|
|
4
|
+
* Universal across Node.js, browsers, and edge environments.
|
|
5
|
+
*
|
|
6
|
+
* @param config - Complete configuration object conforming to `IAhkoFileConfig`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function loadConfig(config: IAhkoFileConfig): void;
|
|
9
|
+
/**
|
|
10
|
+
* Resets the currently active configuration in memory to undefined.
|
|
11
|
+
*/
|
|
12
|
+
export declare function resetConfig(): void;
|
|
13
|
+
/**
|
|
14
|
+
* Asynchronously loads a `config.ahko.json` or custom config file from the filesystem in Node.js.
|
|
15
|
+
* Sets the active configuration in memory upon successful read and parse.
|
|
16
|
+
*
|
|
17
|
+
* @param filePath - Optional relative or absolute path to the configuration file (default: "config.ahko.json").
|
|
18
|
+
* @returns The parsed configuration object, or `undefined` if not running in Node.js or if file cannot be read.
|
|
19
|
+
*/
|
|
20
|
+
export declare function loadConfigFile(filePath?: string): Promise<IAhkoFileConfig | undefined>;
|
|
21
|
+
/**
|
|
22
|
+
* Returns the currently active declarative configuration, attempting auto-discovery if in Node.js.
|
|
23
|
+
*/
|
|
24
|
+
export declare function getActiveConfig(): IAhkoFileConfig | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Retrieves a specific profile configuration by name, or the default profile if no name is provided.
|
|
27
|
+
*
|
|
28
|
+
* @param profileName - Optional name of the profile (e.g. "api", "background").
|
|
29
|
+
* @returns The profile configuration if defined, or undefined.
|
|
30
|
+
*/
|
|
31
|
+
export declare function getProfileConfig(profileName?: string): IAhkoProfileConfig | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { loadConfig, resetConfig, loadConfigFile, getActiveConfig, getProfileConfig, } from "./config-loader.js";
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { AhkoError } from "./ahko.error.js";
|
|
2
|
+
/**
|
|
3
|
+
* Options describing the circuit breaker open state.
|
|
4
|
+
*/
|
|
5
|
+
export interface IAhkoCircuitBreakerErrorOptions {
|
|
6
|
+
/** Time remaining in milliseconds before the circuit attempts half-open trial */
|
|
7
|
+
resetTimeoutMs?: number;
|
|
8
|
+
/** Timestamp when the circuit tripped open */
|
|
9
|
+
trippedAt?: number;
|
|
10
|
+
/** Consecutive failures that caused the trip */
|
|
11
|
+
consecutiveFailures?: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Thrown when attempting to execute a task while the scheduler's circuit breaker is in OPEN state.
|
|
15
|
+
*/
|
|
16
|
+
export declare class AhkoCircuitBreakerOpenError extends AhkoError {
|
|
17
|
+
/** Time remaining in milliseconds before trial execution is allowed */
|
|
18
|
+
readonly resetTimeoutMs?: number;
|
|
19
|
+
/** Timestamp when the circuit tripped open */
|
|
20
|
+
readonly trippedAt?: number;
|
|
21
|
+
/** Total consecutive failures that caused the trip */
|
|
22
|
+
readonly consecutiveFailures?: number;
|
|
23
|
+
constructor(message?: string, options?: IAhkoCircuitBreakerErrorOptions);
|
|
24
|
+
}
|
package/dist/errors/index.d.ts
CHANGED