@jfrz38/adaptive-admission-node 0.1.0 → 0.2.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/COMPONENT.md CHANGED
@@ -1,60 +1,60 @@
1
- # Embedded stable component
2
-
3
- The npm package embeds a WebAssembly component built from an exact crates.io dependency. Installing
4
- or using the package does not require Cargo or a Rust toolchain.
5
-
6
- | Field | Value |
7
- | --- | --- |
8
- | Registry | `https://crates.io` |
9
- | Crate | `adaptive-admission-core` |
10
- | Crate version | `0.1.0` |
11
- | Crate owner | `jfrz38` |
12
- | Crate checksum | `823b1ca077228a3fd229aad05e958e585663072571f0f7709bdbfb70f28dab90` |
13
- | Upstream repository | `https://github.com/jfrz38/adaptive-admission-controller` |
14
- | Upstream commit | `b821533645e6dfbfb611b9459345d0e5030bf83a` |
15
- | WIT world | `jfrz38:adaptive-admission/adaptive-admission@0.1.0` |
16
- | Rust | `rustc 1.99.0 (b940084d7 2026-09-28)` |
17
- | Cargo | `cargo 1.99.0 (5f94df478 2026-08-27)` |
18
- | wasm-tools | `1.262.0` |
19
- | wit-bindgen | `0.63.0` |
20
- | jco-transpile | `0.20.0` |
21
-
22
- The resulting component SHA-256 is:
23
-
24
- ```text
25
- cbb610c98d9a53efa04379bfc9cb21bd8acbcfe9680c3f052daa4082e496fd6a
26
- ```
27
-
28
- `component/COMPONENT.json` relates the crate, build manifest, upstream release manifest, WIT,
29
- conformance suite, toolchain, and generated artifact. Host generation fails before transpilation if
30
- any checksum or required contract operation differs. `make verify-node-component` additionally
31
- rebuilds and validates the component, then checks its exact SHA-256 against the value recorded for
32
- the current build host. Rust/LLVM can emit different Wasm bytes on Windows and Linux even for the
33
- same `wasm32-unknown-unknown` inputs, so both host-specific reproducible hashes are recorded in the
34
- build manifest. The committed npm artifact's exact checksum is always verified separately.
35
-
36
- ## Updating the component
37
-
38
- 1. Confirm the new `adaptive-admission-core` version, owner, checksum, release commit, and WIT.
39
- 2. Set an exact `=X.Y.Z` dependency in `component-build/Cargo.toml` and update the WIT package
40
- version when required.
41
- 3. Run `cargo update --manifest-path code/hosts/node/component-build/Cargo.toml -p
42
- adaptive-admission-core --precise X.Y.Z` so Cargo records the registry checksum.
43
- 4. Build with the pinned Rust and wasm-tools versions, validate the component, and replace the
44
- versioned artifact under `component/`.
45
- 5. Update `adaptive-admission-build-vX.Y.Z.json`, `COMPONENT.json`, `SHA256SUMS`, and this document.
46
- 6. Run `make verify-node-component`, `make validate-node`, and `make test-consumer-packages`.
47
-
48
- There is no fallback to a Git branch. A rollback repeats this procedure with a previously published
49
- exact crate version and produces a new npm package release; mutable Git references are never used as
50
- the component source.
51
-
52
- ## Retiring the TypeScript package
53
-
54
- After Node `0.1.0`, Express `0.2.0`, and NestJS `0.2.0` are published successfully from `main`, the
55
- old package can be marked deprecated without deleting its existing versions:
56
-
57
- ```bash
58
- npm deprecate '@jfrz38/pid-controller-core@*' \
59
- 'Deprecated: use @jfrz38/adaptive-admission-node or the Express/NestJS adapters.'
60
- ```
1
+ # Embedded stable component
2
+
3
+ The npm package embeds a WebAssembly component built from an exact crates.io dependency. Installing
4
+ or using the package does not require Cargo or a Rust toolchain.
5
+
6
+ | Field | Value |
7
+ | --- | --- |
8
+ | Registry | `https://crates.io` |
9
+ | Crate | `adaptive-admission-core` |
10
+ | Crate version | `0.1.0` |
11
+ | Crate owner | `jfrz38` |
12
+ | Crate checksum | `823b1ca077228a3fd229aad05e958e585663072571f0f7709bdbfb70f28dab90` |
13
+ | Upstream repository | `https://github.com/jfrz38/adaptive-admission-controller` |
14
+ | Upstream commit | `b821533645e6dfbfb611b9459345d0e5030bf83a` |
15
+ | WIT world | `jfrz38:adaptive-admission/adaptive-admission@0.1.0` |
16
+ | Rust | `rustc 1.99.0 (b940084d7 2026-09-28)` |
17
+ | Cargo | `cargo 1.99.0 (5f94df478 2026-08-27)` |
18
+ | wasm-tools | `1.262.0` |
19
+ | wit-bindgen | `0.63.0` |
20
+ | jco-transpile | `0.20.0` |
21
+
22
+ The resulting component SHA-256 is:
23
+
24
+ ```text
25
+ cbb610c98d9a53efa04379bfc9cb21bd8acbcfe9680c3f052daa4082e496fd6a
26
+ ```
27
+
28
+ `component/COMPONENT.json` relates the crate, build manifest, upstream release manifest, WIT,
29
+ conformance suite, toolchain, and generated artifact. Host generation fails before transpilation if
30
+ any checksum or required contract operation differs. `make verify-node-component` additionally
31
+ rebuilds and validates the component, then checks its exact SHA-256 against the value recorded for
32
+ the current build host. Rust/LLVM can emit different Wasm bytes on Windows and Linux even for the
33
+ same `wasm32-unknown-unknown` inputs, so both host-specific reproducible hashes are recorded in the
34
+ build manifest. The committed npm artifact's exact checksum is always verified separately.
35
+
36
+ ## Updating the component
37
+
38
+ 1. Confirm the new `adaptive-admission-core` version, owner, checksum, release commit, and WIT.
39
+ 2. Set an exact `=X.Y.Z` dependency in `component-build/Cargo.toml` and update the WIT package
40
+ version when required.
41
+ 3. Run `cargo update --manifest-path code/hosts/node/component-build/Cargo.toml -p
42
+ adaptive-admission-core --precise X.Y.Z` so Cargo records the registry checksum.
43
+ 4. Build with the pinned Rust and wasm-tools versions, validate the component, and replace the
44
+ versioned artifact under `component/`.
45
+ 5. Update `adaptive-admission-build-vX.Y.Z.json`, `COMPONENT.json`, `SHA256SUMS`, and this document.
46
+ 6. Run `make verify-node-component`, `make validate-node`, and `make test-consumer-packages`.
47
+
48
+ There is no fallback to a Git branch. A rollback repeats this procedure with a previously published
49
+ exact crate version and produces a new npm package release; mutable Git references are never used as
50
+ the component source.
51
+
52
+ ## Retiring the TypeScript package
53
+
54
+ After Node `0.2.0`, Express `0.2.1`, Fastify `0.1.0`, and NestJS `0.3.0` are published successfully
55
+ from `main`, the old package can be marked deprecated without deleting its existing versions:
56
+
57
+ ```bash
58
+ npm deprecate '@jfrz38/pid-controller-core@*' \
59
+ 'Deprecated: use @jfrz38/adaptive-admission-node or the Express/NestJS adapters.'
60
+ ```
package/README.md CHANGED
@@ -9,156 +9,185 @@
9
9
  ESM-only Node.js host for the portable
10
10
  [`adaptive-admission-controller`](https://github.com/jfrz38/adaptive-admission-controller)
11
11
  WebAssembly component. Node.js 24 or newer is required.
12
-
13
- The component owns admission, priority queueing, concurrency, statistics, PID feedback, adaptive
14
- timeouts, and automatic tuning. This package owns JavaScript tasks, promises, monotonic time, and
15
- the timer that drives component deadlines.
16
-
17
- The embedded component is built reproducibly from the exact crates.io dependency recorded in
18
- [COMPONENT.md](./COMPONENT.md).
19
-
20
- ## Installation
21
-
22
- ```bash
23
- pnpm add @jfrz38/adaptive-admission-node
24
- ```
25
-
26
- The package is ESM-only:
27
-
28
- ```ts
29
- import { AdaptiveAdmissionController, Priority } from '@jfrz38/adaptive-admission-node';
30
- ```
31
-
32
- CommonJS `require()` is not supported.
33
-
34
- ## Execute work
35
-
36
- ```ts
37
- const controller = new AdaptiveAdmissionController();
38
-
39
- try {
40
- const result = await controller.run(
41
- async () => performWork(),
42
- Priority.fromTier(1, 0),
43
- );
44
- console.log(result);
45
- } finally {
46
- controller.shutdown();
47
- }
48
- ```
49
-
50
- Synchronous return values and promises are supported. If the task throws or rejects, its original
51
- error is preserved after the component records the failed outcome.
52
-
53
- ## Priorities
54
-
55
- Priorities range from `0` (most important) to `767` (least important). Work waiting for capacity is
56
- ordered by priority and FIFO within the same priority.
57
-
58
- ```ts
59
- Priority.fromValue(10);
60
- Priority.fromTier(2, 42); // Six tiers, each with 128 cohorts.
61
- Priority.default(); // Tier 5 with a random cohort.
62
- ```
63
-
64
- ## Cancellation
65
-
66
- Pass an `AbortSignal` as a run option:
67
-
68
- ```ts
69
- const abortController = new AbortController();
70
- const result = controller.run(
71
- () => performWork(),
72
- Priority.fromValue(100),
73
- { signal: abortController.signal },
74
- );
75
-
76
- abortController.abort();
77
- await result;
78
- ```
79
-
80
- An already-aborted signal prevents submission. Aborting queued work removes it from the component
81
- queue and rejects with `CancelledRequestError`. JavaScript work that has already started cannot be
82
- interrupted by the controller and is allowed to finish.
83
-
84
- ## Configuration
85
-
86
- Omitted values use the defaults defined by the pinned Rust component.
87
-
88
- | Option | Default | Purpose |
89
- | --- | ---: | --- |
90
- | `initialThreshold` | `768` | Initial admission boundary; priorities below it are admitted. |
91
- | `maxConcurrentRequests` | `10` | Initial number of tasks allowed to run concurrently. |
92
- | `maxQueuedRequests` | `1000` | Maximum number of tasks waiting for capacity. |
93
- | `queueTimeoutMs` | `500` | Initial queue deadline in milliseconds. |
94
- | `queueTimeoutRatio` | `0.33` | Ratio used to adapt queue deadlines from observed latency. |
95
- | `statistics.minWindowMs` | `2000` | Minimum statistics window duration. |
96
- | `statistics.maxWindowMs` | `30000` | Maximum statistics window duration. |
97
- | `statistics.minSamples` | `250` | Successful samples needed to close a ready window. |
98
- | `statistics.minPercentileSamples` | `250` | Priority samples needed for percentile decisions. |
99
- | `statistics.maxSamples` | `1000` | Maximum samples retained per window. |
100
- | `statistics.latencyPercentile` | `90` | Latency percentile used by adaptive control. |
101
- | `pid.proportionalGain` | `0.2` | PID proportional gain. |
102
- | `pid.integralGain` | `0.5` | PID integral gain. |
103
- | `pid.derivativeGain` | `0` | PID derivative gain. |
104
- | `pid.intervalMs` | `500` | PID evaluation interval. |
105
- | `pid.maxDeltaPercentage` | `10` | Maximum threshold change per PID update. |
106
- | `pid.integralDecay` | `0.5` | Decay applied to accumulated integral error. |
107
-
108
- Integer fields represented as WIT `u64` accept a safe JavaScript integer or `bigint`. Invalid host
109
- values throw `RangeError`; values rejected by the component throw `ConfigurationError`.
110
-
111
- ## Errors
112
-
113
- | Error | Meaning |
114
- | --- | --- |
115
- | `AdmissionRequestError` | Base class for request rejection, eviction, cancellation, and shutdown errors. |
116
- | `ThresholdRejectedError` | Priority was outside the current admission threshold. |
117
- | `QueueFullError` | The bounded waiting queue was full. |
118
- | `EvictedRequestError` | Queued work exceeded its deadline. |
119
- | `CancelledRequestError` | Queued work was explicitly cancelled. |
120
- | `ControllerShutdownError` | Work was queued or submitted after shutdown. |
121
- | `ConfigurationError` | Rust rejected the supplied configuration. |
122
- | `ControllerProtocolError` | The component detected an invalid lifecycle transition. |
123
-
124
- All package errors extend `AdaptiveAdmissionError`. Request lifecycle errors extend
125
- `AdmissionRequestError`; configuration and protocol failures do not. Errors thrown by the user's
126
- task remain distinct and are preserved unchanged.
127
-
128
- ## Lifecycle and shutdown
129
-
130
- Each controller owns independent queue, PID, statistics, and timer state. Call `shutdown()` during
131
- service teardown. It is idempotent, rejects new work, cancels queued work, clears unnecessary
132
- deadlines, and allows already-started JavaScript tasks to finish.
133
-
134
- One controller limits only its current Node.js process or worker. Instances do not coordinate
135
- limits across workers, processes, containers, or hosts.
136
-
137
- ## Diagnostics
138
-
139
- Operational tools can subscribe to low-volume events:
140
-
141
- ```ts
142
- const unsubscribe = controller.onDiagnostic((event) => {
143
- console.log(event);
144
- });
145
-
146
- unsubscribe();
147
- ```
148
-
149
- Events include `threshold-changed`, `concurrency-changed`, `statistics-published`, and
150
- `controller-diagnostics`. Listener failures are isolated and cannot change admission decisions or
151
- task outcomes. Diagnostics are intended for observability and simulations, not admission logic.
152
-
153
- `latestStatistics()` returns the latest completed statistics window, while
154
- `priorityPercentile(percentile)` queries recently observed priorities.
155
-
156
- ## Component provenance
157
-
158
- Builds read `component/COMPONENT.json`, validate every artifact checksum, compare the embedded WIT
159
- export with the checked-in contract, and verify both upstream release and local build provenance
160
- before transpilation. `make verify-node-component` rebuilds the committed artifact from the exact
161
- crates.io package, locked transitive dependencies, and pinned toolchain. Generated JavaScript and
12
+
13
+ The component owns admission, priority queueing, concurrency, statistics, PID feedback, adaptive
14
+ timeouts, and automatic tuning. This package owns JavaScript tasks, promises, monotonic time, and
15
+ the timer that drives component deadlines.
16
+
17
+ The embedded component is built reproducibly from the exact crates.io dependency recorded in
18
+ [COMPONENT.md](./COMPONENT.md).
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ pnpm add @jfrz38/adaptive-admission-node
24
+ ```
25
+
26
+ The package is ESM-only:
27
+
28
+ ```ts
29
+ import { AdaptiveAdmissionController, Priority } from '@jfrz38/adaptive-admission-node';
30
+ ```
31
+
32
+ CommonJS `require()` is not supported.
33
+
34
+ ## Execute work
35
+
36
+ ```ts
37
+ const controller = new AdaptiveAdmissionController();
38
+
39
+ try {
40
+ const result = await controller.run(
41
+ async () => performWork(),
42
+ Priority.fromTier(1, 0),
43
+ );
44
+ console.log(result);
45
+ } finally {
46
+ controller.shutdown();
47
+ }
48
+ ```
49
+
50
+ Synchronous return values and promises are supported. If the task throws or rejects, its original
51
+ error is preserved after the component records the failed outcome.
52
+
53
+ ## Separate admission from completion
54
+
55
+ Framework integrations that begin and finish work in different lifecycle hooks can acquire an
56
+ admission permit directly:
57
+
58
+ ```ts
59
+ const abortController = new AbortController();
60
+ const permit = await controller.acquire(
61
+ Priority.fromTier(1, 0),
62
+ { signal: abortController.signal },
63
+ );
64
+
65
+ try {
66
+ await performWork();
67
+ } catch (error) {
68
+ permit.complete('failure');
69
+ throw error;
70
+ }
71
+ permit.complete('success');
72
+ ```
73
+
74
+ `acquire()` resolves only when the component starts the work. Every acquired permit must be
75
+ completed exactly once with `success` or `failure`; a second completion throws an error. Aborting
76
+ the signal cancels only work that is still queued. Once acquired, a permit remains valid and must
77
+ be completed even if the signal is aborted or the controller begins shutdown.
78
+
79
+ `run()` is implemented using the same permit lifecycle and remains the simpler API when one
80
+ callback can represent the complete lifetime of the work.
81
+
82
+ ## Priorities
83
+
84
+ Priorities range from `0` (most important) to `767` (least important). Work waiting for capacity is
85
+ ordered by priority and FIFO within the same priority.
86
+
87
+ ```ts
88
+ Priority.fromValue(10);
89
+ Priority.fromTier(2, 42); // Six tiers, each with 128 cohorts.
90
+ Priority.default(); // Tier 5 with a random cohort.
91
+ ```
92
+
93
+ ## Cancellation
94
+
95
+ Pass an `AbortSignal` as a run option:
96
+
97
+ ```ts
98
+ const abortController = new AbortController();
99
+ const result = controller.run(
100
+ () => performWork(),
101
+ Priority.fromValue(100),
102
+ { signal: abortController.signal },
103
+ );
104
+
105
+ abortController.abort();
106
+ await result;
107
+ ```
108
+
109
+ An already-aborted signal prevents submission. Aborting queued work removes it from the component
110
+ queue and rejects with `CancelledRequestError`. JavaScript work that has already started cannot be
111
+ interrupted by the controller and is allowed to finish.
112
+
113
+ ## Configuration
114
+
115
+ Omitted values use the defaults defined by the pinned Rust component.
116
+
117
+ | Option | Default | Purpose |
118
+ | --- | ---: | --- |
119
+ | `initialThreshold` | `768` | Initial admission boundary; priorities below it are admitted. |
120
+ | `maxConcurrentRequests` | `10` | Initial number of tasks allowed to run concurrently. |
121
+ | `maxQueuedRequests` | `1000` | Maximum number of tasks waiting for capacity. |
122
+ | `queueTimeoutMs` | `500` | Initial queue deadline in milliseconds. |
123
+ | `queueTimeoutRatio` | `0.33` | Ratio used to adapt queue deadlines from observed latency. |
124
+ | `statistics.minWindowMs` | `2000` | Minimum statistics window duration. |
125
+ | `statistics.maxWindowMs` | `30000` | Maximum statistics window duration. |
126
+ | `statistics.minSamples` | `250` | Successful samples needed to close a ready window. |
127
+ | `statistics.minPercentileSamples` | `250` | Priority samples needed for percentile decisions. |
128
+ | `statistics.maxSamples` | `1000` | Maximum samples retained per window. |
129
+ | `statistics.latencyPercentile` | `90` | Latency percentile used by adaptive control. |
130
+ | `pid.proportionalGain` | `0.2` | PID proportional gain. |
131
+ | `pid.integralGain` | `0.5` | PID integral gain. |
132
+ | `pid.derivativeGain` | `0` | PID derivative gain. |
133
+ | `pid.intervalMs` | `500` | PID evaluation interval. |
134
+ | `pid.maxDeltaPercentage` | `10` | Maximum threshold change per PID update. |
135
+ | `pid.integralDecay` | `0.5` | Decay applied to accumulated integral error. |
136
+
137
+ Integer fields represented as WIT `u64` accept a safe JavaScript integer or `bigint`. Invalid host
138
+ values throw `RangeError`; values rejected by the component throw `ConfigurationError`.
139
+
140
+ ## Errors
141
+
142
+ | Error | Meaning |
143
+ | --- | --- |
144
+ | `AdmissionRequestError` | Base class for request rejection, eviction, cancellation, and shutdown errors. |
145
+ | `ThresholdRejectedError` | Priority was outside the current admission threshold. |
146
+ | `QueueFullError` | The bounded waiting queue was full. |
147
+ | `EvictedRequestError` | Queued work exceeded its deadline. |
148
+ | `CancelledRequestError` | Queued work was explicitly cancelled. |
149
+ | `ControllerShutdownError` | Work was queued or submitted after shutdown. |
150
+ | `ConfigurationError` | Rust rejected the supplied configuration. |
151
+ | `ControllerProtocolError` | The component detected an invalid lifecycle transition. |
152
+
153
+ All package errors extend `AdaptiveAdmissionError`. Request lifecycle errors extend
154
+ `AdmissionRequestError`; configuration and protocol failures do not. Errors thrown by the user's
155
+ task remain distinct and are preserved unchanged.
156
+
157
+ ## Lifecycle and shutdown
158
+
159
+ Each controller owns independent queue, PID, statistics, and timer state. Call `shutdown()` during
160
+ service teardown. It is idempotent, rejects new work, cancels queued work, clears unnecessary
161
+ deadlines, and allows already-started JavaScript tasks to finish.
162
+
163
+ One controller limits only its current Node.js process or worker. Instances do not coordinate
164
+ limits across workers, processes, containers, or hosts.
165
+
166
+ ## Diagnostics
167
+
168
+ Operational tools can subscribe to low-volume events:
169
+
170
+ ```ts
171
+ const unsubscribe = controller.onDiagnostic((event) => {
172
+ console.log(event);
173
+ });
174
+
175
+ unsubscribe();
176
+ ```
177
+
178
+ Events include `threshold-changed`, `concurrency-changed`, `statistics-published`, and
179
+ `controller-diagnostics`. Listener failures are isolated and cannot change admission decisions or
180
+ task outcomes. Diagnostics are intended for observability and simulations, not admission logic.
181
+
182
+ `latestStatistics()` returns the latest completed statistics window, while
183
+ `priorityPercentile(percentile)` queries recently observed priorities.
184
+
185
+ ## Component provenance
186
+
187
+ Builds read `component/COMPONENT.json`, validate every artifact checksum, compare the embedded WIT
188
+ export with the checked-in contract, and verify both upstream release and local build provenance
189
+ before transpilation. `make verify-node-component` rebuilds the committed artifact from the exact
190
+ crates.io package, locked transitive dependencies, and pinned toolchain. Generated JavaScript and
162
191
  WebAssembly modules are included in the npm tarball, so consumers do not need Cargo or Rust.
163
192
 
164
193
  ## More information
@@ -1,5 +1,5 @@
1
1
  import { Priority } from './priority.js';
2
- import type { ControllerDiagnosticListener, ControllerOptions, RunOptions, StatisticsSnapshot } from './types.js';
2
+ import type { AcquireOptions, AdmissionPermit, ControllerDiagnosticListener, ControllerOptions, RunOptions, StatisticsSnapshot } from './types.js';
3
3
  export interface MonotonicClock {
4
4
  nowMilliseconds(): bigint;
5
5
  }
@@ -24,6 +24,8 @@ export declare class AdaptiveAdmissionController {
24
24
  private latestControllerDiagnostics;
25
25
  constructor(options?: ControllerOptions, dependencies?: ControllerDependencies);
26
26
  run<T>(task: () => T | Promise<T>, priority?: Priority, options?: RunOptions): Promise<T>;
27
+ acquire(priority?: Priority, options?: AcquireOptions): Promise<AdmissionPermit>;
28
+ private runWithPermit;
27
29
  shutdown(): void;
28
30
  latestStatistics(): StatisticsSnapshot | undefined;
29
31
  priorityPercentile(percentile: number): number | undefined;
@@ -32,8 +34,8 @@ export declare class AdaptiveAdmissionController {
32
34
  private publishControllerDiagnostics;
33
35
  private publishDiagnostic;
34
36
  private start;
35
- private completeSuccess;
36
- private completeFailure;
37
+ private createPermit;
38
+ private complete;
37
39
  private reject;
38
40
  private settleRejected;
39
41
  private observeAbort;
@@ -28,6 +28,9 @@ export class AdaptiveAdmissionController {
28
28
  this.component = createValidatedComponentController(options);
29
29
  }
30
30
  run(task, priority = Priority.default(), options = {}) {
31
+ return this.runWithPermit(task, priority, options);
32
+ }
33
+ acquire(priority = Priority.default(), options = {}) {
31
34
  if (this.shutdownRequested) {
32
35
  return Promise.reject(new ControllerShutdownError());
33
36
  }
@@ -42,7 +45,7 @@ export class AdaptiveAdmissionController {
42
45
  });
43
46
  try {
44
47
  const submission = this.component.submit(priority.value, this.now());
45
- this.pending.set(submission.requestId, { task, resolve, reject, state: 'queued' });
48
+ this.pending.set(submission.requestId, { resolve, reject, state: 'queued' });
46
49
  this.processActions(submission.actions);
47
50
  this.observeAbort(submission.requestId, options.signal);
48
51
  this.rescheduleDeadline();
@@ -52,6 +55,24 @@ export class AdaptiveAdmissionController {
52
55
  }
53
56
  return promise;
54
57
  }
58
+ async runWithPermit(task, priority, options) {
59
+ const permit = await this.acquire(priority, options);
60
+ let value;
61
+ try {
62
+ value = await task();
63
+ }
64
+ catch (taskError) {
65
+ try {
66
+ permit.complete('failure');
67
+ }
68
+ catch {
69
+ // Preserve the task's original failure after the work has already run.
70
+ }
71
+ throw taskError;
72
+ }
73
+ permit.complete('success');
74
+ return value;
75
+ }
55
76
  shutdown() {
56
77
  if (this.shutdownRequested) {
57
78
  return;
@@ -155,36 +176,34 @@ export class AdaptiveAdmissionController {
155
176
  }
156
177
  pending.state = 'started';
157
178
  this.removeAbortListener(pending);
158
- this.dependencies.defer(() => {
159
- Promise.resolve()
160
- .then(pending.task)
161
- .then((value) => this.completeSuccess(requestId, pending, value), (error) => this.completeFailure(requestId, pending, error));
162
- });
179
+ const permit = this.createPermit(requestId);
180
+ this.dependencies.defer(() => pending.resolve(permit));
163
181
  }
164
- completeSuccess(requestId, pending, value) {
165
- this.pending.delete(requestId);
166
- try {
167
- this.processActions(this.component.complete(requestId, 'success', this.now()));
168
- pending.resolve(value);
169
- }
170
- catch (error) {
171
- pending.reject(this.translateProtocolError(error));
172
- }
173
- finally {
174
- this.rescheduleDeadline();
175
- }
182
+ createPermit(requestId) {
183
+ let completed = false;
184
+ return {
185
+ complete: (outcome) => {
186
+ if (completed) {
187
+ throw new Error('Admission permit has already been completed');
188
+ }
189
+ completed = true;
190
+ this.complete(requestId, outcome);
191
+ },
192
+ };
176
193
  }
177
- completeFailure(requestId, pending, taskError) {
194
+ complete(requestId, outcome) {
195
+ const pending = this.pending.get(requestId);
196
+ if (!pending || pending.state !== 'started') {
197
+ throw new Error(`cannot complete unknown or non-started request ${requestId}`);
198
+ }
178
199
  this.pending.delete(requestId);
179
200
  try {
180
- this.processActions(this.component.complete(requestId, 'failure', this.now()));
201
+ this.processActions(this.component.complete(requestId, outcome, this.now()));
181
202
  }
182
- catch {
183
- // The task's original failure remains the public result. Protocol failures are not allowed to
184
- // replace application errors after the task has already run.
203
+ catch (error) {
204
+ throw this.translateProtocolError(error);
185
205
  }
186
206
  finally {
187
- pending.reject(taskError);
188
207
  this.rescheduleDeadline();
189
208
  }
190
209
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { AdaptiveAdmissionController } from './controller.js';
2
2
  export { AdaptiveAdmissionError, AdmissionRequestError, CancelledRequestError, ConfigurationError, ControllerProtocolError, ControllerShutdownError, EvictedRequestError, QueueFullError, RejectedRequestError, ThresholdRejectedError, } from './errors.js';
3
3
  export { Priority } from './priority.js';
4
- export type { ControllerDiagnosticEvent, ControllerDiagnosticListener, ControllerDiagnostics, ControllerOptions, PidOptions, RunOptions, StatisticsOptions, StatisticsSnapshot, U64Input, } from './types.js';
4
+ export type { AcquireOptions, AdmissionOutcome, AdmissionPermit, ControllerDiagnosticEvent, ControllerDiagnosticListener, ControllerDiagnostics, ControllerOptions, PidOptions, RunOptions, StatisticsOptions, StatisticsSnapshot, U64Input, } from './types.js';
package/dist/types.d.ts CHANGED
@@ -27,6 +27,11 @@ export interface ControllerOptions {
27
27
  export interface RunOptions {
28
28
  signal?: AbortSignal;
29
29
  }
30
+ export type AcquireOptions = RunOptions;
31
+ export type AdmissionOutcome = 'success' | 'failure';
32
+ export interface AdmissionPermit {
33
+ complete(outcome: AdmissionOutcome): void;
34
+ }
30
35
  export interface StatisticsSnapshot {
31
36
  id: bigint;
32
37
  startedAtMs: bigint;
package/package.json CHANGED
@@ -1,58 +1,58 @@
1
- {
2
- "name": "@jfrz38/adaptive-admission-node",
3
- "version": "0.1.0",
4
- "description": "Node.js host SDK for the Adaptive Admission Controller WebAssembly component",
5
- "license": "MIT",
6
- "type": "module",
7
- "engines": {
8
- "node": ">=24"
9
- },
10
- "main": "./dist/index.js",
11
- "types": "./dist/index.d.ts",
12
- "exports": {
13
- ".": {
14
- "types": "./dist/index.d.ts",
15
- "import": "./dist/index.js"
16
- }
17
- },
18
- "files": [
19
- "dist",
20
- "component",
21
- "README.md",
22
- "COMPONENT.md"
23
- ],
24
- "scripts": {
25
- "generate": "node scripts/generate.mjs",
26
- "validate:component": "node scripts/generate.mjs",
27
- "build": "node scripts/build.mjs",
28
- "clean": "node scripts/clean.mjs",
29
- "test": "pnpm generate && vitest run",
30
- "test:coverage": "pnpm generate && vitest run --coverage",
31
- "test:conformance": "pnpm generate && vitest run tests/conformance.spec.ts",
32
- "test:package": "node scripts/package-smoke.mjs",
33
- "test:component-build": "node scripts/verify-component-build.mjs",
34
- "lint": "eslint src tests --ignore-pattern src/generated/**",
35
- "lint:src": "eslint src --ignore-pattern src/generated/**",
36
- "lint:fix": "eslint \"{src,tests}/**/*.ts\" --fix",
37
- "prepack": "node scripts/verify-package-policy.mjs pack && pnpm build",
38
- "prepublishOnly": "node scripts/verify-package-policy.mjs publish"
39
- },
40
- "repository": {
41
- "type": "git",
42
- "url": "git+https://github.com/jfrz38/rate-limit-pid-controller.git",
43
- "directory": "code/hosts/node"
44
- },
45
- "publishConfig": {
46
- "access": "public"
47
- },
48
- "keywords": [
49
- "admission-control",
50
- "load-shedding",
51
- "pid-controller",
52
- "webassembly",
53
- "nodejs"
54
- ],
55
- "devDependencies": {
56
- "@bytecodealliance/jco-transpile": "0.21.0"
57
- }
58
- }
1
+ {
2
+ "name": "@jfrz38/adaptive-admission-node",
3
+ "version": "0.2.0",
4
+ "description": "Node.js host SDK for the Adaptive Admission Controller WebAssembly component",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=24"
9
+ },
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "component",
21
+ "README.md",
22
+ "COMPONENT.md"
23
+ ],
24
+ "scripts": {
25
+ "generate": "node scripts/generate.mjs",
26
+ "validate:component": "node scripts/generate.mjs",
27
+ "build": "node scripts/build.mjs",
28
+ "clean": "node scripts/clean.mjs",
29
+ "test": "pnpm generate && vitest run",
30
+ "test:coverage": "pnpm generate && vitest run --coverage",
31
+ "test:conformance": "pnpm generate && vitest run tests/conformance.spec.ts",
32
+ "test:package": "node scripts/package-smoke.mjs",
33
+ "test:component-build": "node scripts/verify-component-build.mjs",
34
+ "lint": "eslint src tests --ignore-pattern src/generated/**",
35
+ "lint:src": "eslint src --ignore-pattern src/generated/**",
36
+ "lint:fix": "eslint \"{src,tests}/**/*.ts\" --fix",
37
+ "prepack": "node scripts/verify-package-policy.mjs pack && pnpm build",
38
+ "prepublishOnly": "node scripts/verify-package-policy.mjs publish"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/jfrz38/rate-limit-pid-controller.git",
43
+ "directory": "code/hosts/node"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "keywords": [
49
+ "admission-control",
50
+ "load-shedding",
51
+ "pid-controller",
52
+ "webassembly",
53
+ "nodejs"
54
+ ],
55
+ "devDependencies": {
56
+ "@bytecodealliance/jco-transpile": "0.21.0"
57
+ }
58
+ }