runwarm 0.1.0-alpha.1 → 0.3.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 CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ - Isolated profiles: a profile with `boot`, `instance`, `dispose` and `shutdown` hooks boots shared state once per worker and gives every case an application instance of its own, so no case waits for a reset. With the new `app-instances` option above `1`, one worker serves that many cases at the same time. A disconnected case only disposes its instance. Globals that appear in a worker after a case are reported on stderr and counted in `isolationWarnings`.
6
+ - A case now goes to a running worker before a new one is started, so it no longer pays a cold start while another worker sits idle.
7
+ - A discarded worker is stopped in the background: the failing case gets its error at once, and the worker's position is reused after `stop` finishes. With `app-instances` above `1`, the worker's other cases finish first.
8
+ - The metrics report adds `processStart` and `profileImport`, which with `bootstrap` make up a worker's cold start, and `peakConcurrentCases`.
9
+ - The benchmark adds the `instanced` mode, measures CPU and memory on Windows as well as Linux, and reports the memory of the application processes alone. The README compares GitHub Actions with a local 12-core machine, where instances use 81% to 90% less memory for the application processes than the pool.
10
+ - Lifecycle commands carry an id, so a late answer from a worker that timed out is never taken for another command's answer.
11
+ - `app-prewarm` option starts the given number of applications in the background before the first test asks for one, so a slow `start` overlaps with tap loading the test files. It is off by default. A warm-up that fails discards the worker, and the next test starts a new one and sees the real error.
12
+ - `app-metrics-file` option writes the metrics report as JSON to a file, so CI can read it without relying on the runner's stderr.
13
+ - The metrics report adds `workersDiscarded`, `resetFailures` and a `prepare` timing. The existing fields keep their meaning, and `prepare` and `reset` count every attempt, including failed ones.
14
+ - **Changed:** `withApp` now tells a loaded plugin without `app-profile` (`RunWarm is idle`) from a project without the plugin (`RunWarm is not running`). Code that matched the old message for the first case needs updating.
15
+ - A metrics file that cannot be written is reported on stderr and does not fail the run.
16
+ - The README documents the `EPERM` symlink error when adding the plugin on Windows and explains why `app-metrics` output may not show in the default reporter.
17
+
18
+ ## 0.2.0
19
+
20
+ First release outside the alpha channel. RunWarm follows semantic versioning: until 1.0.0, a minor version can change options or profile hook behavior, and each such change is marked below.
21
+
22
+ - **Changed:** the case name passed by `t.withApp()` is now the full name of `t`, including the test file and parent tests, such as `test/orders.test.js > checkout > pays by card`. Profiles that match on the bare test name need updating. Names passed to `withApp(caseName, callback)` are unchanged.
23
+ - **Changed:** a worker retired after a failed preparation or reset, or a disconnected client, now runs its `stop` hook before it is killed, unless it timed out. `stop` must cope with an application whose state was not reset.
24
+ - `app-timeout` option for the profile hook timeout, still 30 seconds by default.
25
+ - Application workers no longer inherit the pool's socket address and token.
26
+ - Shutdown stops every worker even when one `stop` hook fails, and reports all failures.
27
+ - The control message size limit applies to each message.
28
+ - The README explains how to use a TypeScript profile and shows benchmark results for 1,000 HTTP test files and for smaller suites on Linux, Windows and macOS.
29
+
3
30
  ## 0.1.0-alpha.1
4
31
 
5
32
  - Type declarations for `defineAppProfile` and `withApp`.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  <p align="center"><strong>A node-tap plugin that keeps your application running between integration tests.</strong></p>
4
4
 
5
5
  <p align="center">
6
- <a href="package.json"><img alt="Project version" src="https://img.shields.io/github/package-json/v/fabenejr/runwarm?label=version"></a>
6
+ <a href="https://www.npmjs.com/package/runwarm"><img alt="npm version" src="https://img.shields.io/npm/v/runwarm?logo=npm"></a>
7
7
  <a href="https://github.com/fabenejr/runwarm/actions/workflows/acceptance.yml"><img alt="Acceptance tests status" src="https://github.com/fabenejr/runwarm/actions/workflows/acceptance.yml/badge.svg"></a>
8
8
  <a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/github/license/fabenejr/runwarm"></a>
9
9
  </p>
@@ -21,7 +21,7 @@
21
21
  <img alt="Two separate test files share a running application worker. The worker's application state resets between uses." src="docs/assets/warm-worker-pool.webp" width="800">
22
22
  </p>
23
23
 
24
- When integration tests start the same app in every file, they repeat the work of loading routes, opening connections and preparing dependencies. RunWarm is a node-tap plugin: the tap runner keeps a bounded set of applications running, hands one to each test case through `t.withApp()` and resets its state afterwards. It works with any Node.js HTTP or HTTPS application, with ready-made examples for NestJS, Fastify and Express.
24
+ When integration tests start the same app in every file, they repeat the work of loading routes, opening connections and preparing dependencies. RunWarm is a node-tap plugin: the tap runner keeps a bounded set of applications running, hands one to each test case through `t.withApp()` and resets its state afterwards, or boots the slow parts once and gives every case a fresh application instance of its own. It works with any Node.js HTTP or HTTPS application, with ready-made examples for NestJS, Fastify and Express.
25
25
 
26
26
  | <a href="https://nodejs.org/"><img src="https://nodejs.org/static/logos/nodejsHex.svg" alt="Node.js" width="52"></a> | <a href="https://tapjs.org/"><img src="https://tapjs.org/static/small-logo.png" alt="node-tap" width="62"></a> | <a href="examples/nestjs/profile.js"><img src="https://cdn.simpleicons.org/nestjs" alt="NestJS" width="52"></a> | <a href="examples/fastify/profile.js"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cdn.simpleicons.org/fastify/ffffff"><img src="https://cdn.simpleicons.org/fastify/000000" alt="Fastify" width="52"></picture></a> | <a href="examples/express/profile.js"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cdn.simpleicons.org/express/ffffff"><img src="https://cdn.simpleicons.org/express/000000" alt="Express" width="52"></picture></a> |
27
27
  | :---: | :---: | :---: | :---: | :---: |
@@ -29,7 +29,7 @@ When integration tests start the same app in every file, they repeat the work of
29
29
 
30
30
  ## Quick start
31
31
 
32
- RunWarm needs Node.js 22.12.0 or later and node-tap 21.8.1 or later. Install it from npm. Until the first stable version, this installs the latest alpha.
32
+ RunWarm needs Node.js 22.12.0 or later and node-tap 21.8.1 or later. Install it from npm.
33
33
 
34
34
  ```sh
35
35
  npm install --save-dev runwarm
@@ -51,7 +51,7 @@ t.test('a new customer has no orders', t => t.withApp(async ({ url }) => {
51
51
  }))
52
52
  ```
53
53
 
54
- Await all requests and background operations owned by the test before the callback returns. The callback also receives a `workerId` for diagnostics. The case name passed to the profile hooks is the name of `t`. Outside a `t`, or to name the case yourself, import `withApp(caseName, callback)` from `runwarm`.
54
+ Await all requests and background operations owned by the test before the callback returns. The callback also receives a `workerId` for diagnostics. The case name passed to the profile hooks is the full name of `t`, which starts with the test file and includes the parent tests, such as `test/orders.test.js > checkout > pays by card`. Outside a `t`, or to name the case yourself, import `withApp(caseName, callback)` from `runwarm`.
55
55
 
56
56
  ## Options
57
57
 
@@ -61,7 +61,11 @@ Pass them on the command line or set them in `.taprc`.
61
61
  | --- | --- | --- |
62
62
  | `app-profile` | none | Module whose default export is the application profile. The plugin stays idle without it |
63
63
  | `app-workers` | `1` | Maximum number of running applications |
64
- | `app-metrics` | off | Write one `runwarm metrics: {...}` JSON line to stderr when the run ends |
64
+ | `app-metrics` | off | Write one `runwarm metrics: {...}` JSON line to stderr when the run ends. The default tap reporter hides the runner's stderr, so use `2>&1` or `app-metrics-file` |
65
+ | `app-metrics-file` | none | Write the same metrics as JSON to this file when the run ends. It works without `app-metrics` |
66
+ | `app-instances` | `1` | Cases each worker serves at the same time, each with an application instance of its own. Above `1` needs a profile with `instance` and `dispose` hooks, see [Isolated instances](#isolated-instances) |
67
+ | `app-prewarm` | `0` | Number of applications to start in the background before the first test asks for one, up to `app-workers`. Use it when `start` is slow. The applications start even if no test calls `withApp` |
68
+ | `app-timeout` | `30` | Seconds each profile hook may take, including `start`. A worker that runs over is discarded |
65
69
 
66
70
  ```yaml
67
71
  app-profile: test/profile.js
@@ -69,14 +73,16 @@ app-workers: 4
69
73
  disable-coverage: true
70
74
  ```
71
75
 
72
- `app-workers` limits running applications and tap's `--jobs` limits concurrent test files.
76
+ `app-workers` limits running application processes, `app-instances` limits the cases each of them serves at once, and tap's `--jobs` limits concurrent test files.
73
77
 
74
- The metrics report includes total duration, workers started, completed bootstrap hooks, time waiting for a worker, reset round-trip time and the highest peak RSS of any application process.
78
+ The metrics report includes total duration, workers started and discarded, failed resets, the highest number of cases served at once (`peakConcurrentCases`), globals left behind by isolated cases (`isolationWarnings`), each worker's cold start split into process start (`processStart`), profile import (`profileImport`) and the `start` or `boot` hook (`bootstrap`), time waiting for a free worker (`queueWait`), time to prepare a worker for a case (`prepare`, which includes `start` for the first case that reaches a new worker, or `instance` for isolated profiles), reset round-trip time (`dispose` for isolated profiles) and the highest peak RSS of any application process. The `prepare` and `reset` timings count every attempt, including failed ones, and `resetFailures` counts the failures.
75
79
 
76
80
  ## Define an application profile
77
81
 
78
82
  Export the result of `defineAppProfile` as the default export of the module named by `app-profile`. The pool loads one profile per run. The repository includes working profiles for [Fastify](examples/fastify/profile.js), [Express](examples/express/profile.js), [NestJS](examples/nestjs/profile.js), and [Node.js HTTPS](examples/https/profile.js).
79
83
 
84
+ The application runs in a plain Node.js process, without the loaders tap adds to test files. A TypeScript profile (`profile.ts`) works on Node.js 22.18.0 or later, which strips types by default. On older versions, or for syntax that type stripping does not support, compile the profile first or pass a loader through `NODE_OPTIONS`.
85
+
80
86
  | Hook | Responsibility |
81
87
  | --- | --- |
82
88
  | `start({ workerId })` | Start the server on an available port on `127.0.0.1`. Wait until it can accept requests, then return an object containing its `url` and any resources the other hooks need. |
@@ -86,6 +92,50 @@ Export the result of `defineAppProfile` as the default export of the module name
86
92
 
87
93
  Each worker gets a fresh UUID. A profile can use it to isolate database schemas or queues across workers. Include caches and fakes in the reset, and arrange cleanup for external resources that can outlive a crashed worker.
88
94
 
95
+ ### Isolated instances
96
+
97
+ Importing a framework and the application's modules is usually most of a cold start: about 80 ms for Express or Fastify and over 300 ms for NestJS before `start` even runs. An isolated profile pays that once per worker in `boot`, then gives every case a fresh application instance, which takes about 1 ms once the worker is warm. With `app-instances` above `1`, one worker serves several cases at the same time, and a case never waits for a reset.
98
+
99
+ ```js
100
+ import Fastify from 'fastify'
101
+ import { defineAppProfile } from 'runwarm'
102
+ import { connectDatabase, createSchema, routes } from '../src/app.js'
103
+
104
+ export default defineAppProfile({
105
+ // Once per worker: everything slow and read-only, such as a database pool.
106
+ async boot() {
107
+ return { db: await connectDatabase() }
108
+ },
109
+ // Once per case: everything the case can change.
110
+ async instance({ db }, { instanceId }) {
111
+ const schema = 'case_' + instanceId.replaceAll('-', '_')
112
+ await createSchema(db, schema)
113
+ const server = Fastify()
114
+ server.register(routes, { db, schema })
115
+ return { server, schema, url: await server.listen({ host: '127.0.0.1', port: 0 }) }
116
+ },
117
+ async dispose({ db }, { server, schema }) {
118
+ await server.close()
119
+ await db.query('DROP SCHEMA ' + schema + ' CASCADE')
120
+ },
121
+ shutdown: ({ db }) => db.end(),
122
+ })
123
+ ```
124
+
125
+ | Hook | Responsibility |
126
+ | --- | --- |
127
+ | `boot({ workerId })` | Optional. Create the state every case may share and none may change. Its result is passed to the other hooks. |
128
+ | `instance(shared, { workerId, instanceId, caseName })` | Build an application for one case and return an object with its `url`. `instanceId` is unique within the run. |
129
+ | `dispose(shared, instance, { workerId, instanceId, caseName })` | Close the instance and remove what it created. It also runs when the test disconnects early. |
130
+ | `shutdown(shared)` | Optional. Release the shared state when the worker stops. |
131
+
132
+ Cases share the worker's process, so isolation depends on where state lives:
133
+
134
+ - Keep everything a case can change in its instance: in-memory stores, caches, fakes and the server itself. Module-level variables and `boot` state are shared by every case in the worker.
135
+ - Give each instance its own slice of external state, such as a database schema, a transaction or a key prefix named after `instanceId`. Measure it: building a schema for every case can cost more than the reset it replaces.
136
+ - RunWarm compares the worker's globals after each `dispose` with those present after `boot`, prints a warning naming any new global and the case it was found after, and counts it in `isolationWarnings`.
137
+ - A failed `instance` or `dispose`, a timeout or a crash discards the worker, because its state is no longer known. Other cases already running in that worker finish first, unless the process died.
138
+
89
139
  The HTTPS example reads PEM files from `EXAMPLE_TLS_CERT` and `EXAMPLE_TLS_KEY`. Its acceptance test generates a temporary certificate and configures trust in the child processes with `NODE_EXTRA_CA_CERTS`.
90
140
 
91
141
  ### How the pool works
@@ -94,9 +144,15 @@ The HTTPS example reads PEM files from `EXAMPLE_TLS_CERT` and `EXAMPLE_TLS_KEY`.
94
144
  2. Each test file reserves a worker from the coordinator over a local socket.
95
145
  3. The coordinator sends lifecycle commands to the application worker over IPC, and the worker runs your profile.
96
146
  4. The test sends HTTP or HTTPS requests straight to the application.
97
- 5. On release, the worker resets the application and takes the next case.
147
+ 5. On release, the worker resets the application, or disposes the case's instance, and takes the next case.
148
+
149
+ The runner listens on a Unix socket in a private temporary directory, or on a named pipe on Windows, with a random token for each run. Workers start on demand. A case goes to a running worker with room for it, even one that is still starting, before a new worker is started, and callers queue in arrival order when all are busy. Test requests go directly to the application. If preparation or reset fails, or the client disconnects during a reservation, the coordinator discards the worker: it takes no new cases, and once its current cases end it runs the `stop` hook while it still responds and is killed. The failing case gets its error without waiting for that. A disconnected case of an isolated profile only disposes its instance. Lifecycle commands time out after `app-timeout` seconds. A worker that times out is discarded without `stop`. Application workers do not inherit the pool's socket address and token.
150
+
151
+ ## Troubleshooting
98
152
 
99
- The runner listens on a Unix socket in a private temporary directory, or on a named pipe on Windows, with a random token for each run. Workers start on demand and callers queue in arrival order when all are busy. Test requests go directly to the application. If preparation or reset fails, or the client disconnects during a reservation, the coordinator discards the affected worker. Lifecycle commands time out after 30 seconds.
153
+ - `RunWarm is not running`: the plugin is not installed in this project. Run `npx tap plugin add runwarm/plugin`.
154
+ - `RunWarm is idle`: the plugin is loaded but no profile is set. Pass `--app-profile=<module>` or set `app-profile` in `.taprc`.
155
+ - `EPERM: operation not permitted, symlink` on Windows while running `tap plugin add`: Windows only lets a process create directory symlinks with developer mode (Settings > System > For developers) or an elevated shell. Reopen the terminal and the editor after enabling it. This comes from node-tap's plugin build, not from RunWarm. To check the permission, run `node -e "require('fs').symlinkSync(process.cwd(), 'link-test', 'dir')"` and delete `link-test` afterwards.
100
156
 
101
157
  ## Limitations
102
158
 
@@ -107,19 +163,96 @@ The runner listens on a Unix socket in a private temporary directory, or on a na
107
163
 
108
164
  ## Benchmarks
109
165
 
110
- The benchmark packs RunWarm, installs it in a temporary project, adds the plugin and runs the same HTTP cases with a new application per case, a new application per file and the pool.
166
+ The benchmark packs RunWarm, installs it in a temporary project, adds the plugin and runs the same HTTP cases against a real Fastify, Express or NestJS application with no artificial startup delay. Each case lists, creates and lists orders. It compares a new application per case or per file with the RunWarm pool (`start`/`reset`/`stop`, one case per worker at a time) and with RunWarm instances (an [isolated profile](#isolated-instances) with `app-instances` equal to the tap jobs, so one worker serves every case).
167
+
168
+ ### GitHub Actions vs a local machine
169
+
170
+ On a developer machine tap runs as many test files at once as there are CPU cores. The pool then keeps one application process per busy job, while instances serve every job from one process. The same 120 cases were run on GitHub Actions (Linux, 2 jobs) and on a local Windows 11 machine with 12 cores (12 jobs). Each chart shows the two machines as separate blocks, and the percentage next to each instances bar compares it with the pool on the same machine.
171
+
172
+ <p align="center">
173
+ <img alt="Memory of the application processes, pool then instances. GitHub Actions, 2 jobs: Fastify 75 to 70 MiB (−6%), Express 61 to 37 MiB (−39%), NestJS 101 to 76 MiB (−24%). Local machine, 12 jobs: Fastify 407 to 76 MiB (−81%), Express 365 to 36 MiB (−90%), NestJS 633 to 78 MiB (−88%)." src="docs/assets/benchmark-ci-vs-local-app-memory.svg" width="760">
174
+ </p>
175
+
176
+ <p align="center">
177
+ <img alt="CPU time per file, pooled and with instances. GitHub Actions: Fastify 32.2, 28.2 and 27.8 s (−2% against the pool), Express 32.1, 30.8 and 31.1 s (+1%), NestJS 59.5, 45.6 and 46.0 s (+1%). Local machine: Fastify 59.6, 53.3 and 48.8 s (−9%), Express 56.3, 53.1 and 49.0 s (−8%), NestJS 78.8, 56.6 and 51.2 s (−10%)." src="docs/assets/benchmark-ci-vs-local-cpu.svg" width="760">
178
+ </p>
179
+
180
+ <p align="center">
181
+ <img alt="Wall time per file, pooled and with instances. GitHub Actions: Fastify 13.6, 12.1 and 12.0 s (−1% against the pool), Express 13.3, 12.8 and 13.1 s (+2%), NestJS 24.9, 19.6 and 19.8 s (+1%). Local machine: Fastify 8.4, 7.9 and 6.7 s (−14%), Express 8.0, 7.8 and 7.6 s (−2%), NestJS 10.5, 8.0 and 7.8 s (−3%)." src="docs/assets/benchmark-ci-vs-local-wall.svg" width="760">
182
+ </p>
183
+
184
+ | Pool → instances | Application processes | Their peak memory | CPU time | Wall time |
185
+ | --- | ---: | ---: | ---: | ---: |
186
+ | NestJS, Actions | 2 → **1** | 101 → **76 MiB** (−24%) | 45.6 → 46.0 s (+1%) | 19.6 → 19.8 s (+1%) |
187
+ | NestJS, local | 12 → **1** | 633 → **78 MiB** (−88%) | 56.6 → **51.2 s** (−10%) | 8.0 → 7.8 s (−3%) |
188
+ | Fastify, Actions | 2 → **1** | 75 → **70 MiB** (−6%) | 28.2 → 27.8 s (−2%) | 12.1 → 12.0 s (−1%) |
189
+ | Fastify, local | 11 → **1** | 407 → **76 MiB** (−81%) | 53.3 → **48.8 s** (−9%) | 7.9 → **6.7 s** (−14%) |
190
+ | Express, Actions | 2 → **1** | 61 → **37 MiB** (−39%) | 30.8 → 31.1 s (+1%) | 12.8 → 13.1 s (+2%) |
191
+ | Express, local | 11 → **1** | 365 → **36 MiB** (−90%) | 53.1 → **49.0 s** (−8%) | 7.8 → 7.6 s (−2%) |
192
+
193
+ Instances pay off where tap runs many jobs: locally they cut the memory of the application processes by 81% to 90% and CPU time by 8% to 10% against the pool, because one process replaces a cold start per job. On a CI runner with 2 jobs the pool already needs only 2 applications, so instances match it. Both stay ahead of a new application per file on both machines. The whole process tree, dominated by tap's own test processes, uses about the same memory in every mode: about 600 MiB on Actions and 3 GiB locally.
194
+
195
+ The local figures come from one machine and the median of 3 rounds. Memory is PSS on Linux and private bytes on Windows, so compare modes within one machine, not machines with each other. Windows has no CPU accounting for a process tree, so the local CPU time adds the last sample of each process and slightly undercounts short-lived ones.
196
+
197
+ ### 1,000 HTTP test files
198
+
199
+ The largest run has 1,000 tap files with one HTTP case each, 8 tap jobs and up to 8 pool workers. Without RunWarm, every file starts its own application. The pool starts 5 or fewer, and instances start one.
200
+
201
+ <p align="center">
202
+ <img alt="Wall time for 1,000 HTTP test files on Linux. Fastify: 375 s with a new app per case, 338 s with the RunWarm pool, 323 s with RunWarm instances. Express: 367 s, 330 s and 333 s. NestJS: 534 s, 389 s and 378 s." src="docs/assets/benchmark-1000-wall.svg" width="760">
203
+ </p>
204
+
205
+ <p align="center">
206
+ <img alt="CPU time for 1,000 HTTP test files on Linux. Fastify: 1,249 s with a new app per case, 1,112 s with the RunWarm pool, 1,066 s with RunWarm instances. Express: 1,256 s, 1,129 s and 1,140 s. NestJS: 1,777 s, 1,281 s and 1,253 s." src="docs/assets/benchmark-1000-cpu.svg" width="760">
207
+ </p>
208
+
209
+ | 1,000 files on Linux | App startups | Wall time | CPU time | Peak memory |
210
+ | --- | ---: | ---: | ---: | ---: |
211
+ | NestJS 11.2.12, pool | 1,000 → **5** | 534 s → **389 s** (−27%) | 1,777 s → **1,281 s** (−28%) | 1,930 → 1,797 MiB |
212
+ | NestJS 11.2.12, instances | 1,000 → **1** | 534 s → **378 s** (−29%) | 1,777 s → **1,253 s** (−29%) | 1,930 → 1,838 MiB |
213
+ | Fastify 5.12.8, pool | 1,000 → **3** | 375 s → **338 s** (−10%) | 1,249 s → **1,112 s** (−11%) | 1,821 → 1,675 MiB |
214
+ | Fastify 5.12.8, instances | 1,000 → **1** | 375 s → **323 s** (−14%) | 1,249 s → **1,066 s** (−15%) | 1,821 → 1,821 MiB |
215
+ | Express 5.3.0, pool | 1,000 → **5** | 367 s → **330 s** (−10%) | 1,256 s → **1,129 s** (−10%) | 1,861 → 1,746 MiB |
216
+ | Express 5.3.0, instances | 1,000 → **1** | 367 s → **333 s** (−9%) | 1,256 s → **1,140 s** (−9%) | 1,861 → 1,676 MiB |
217
+
218
+ CPU time is the user and system time of the whole process tree, and peak memory is its proportional set size (PSS). RunWarm saves machine time as well as wall time: the NestJS run uses about 8 fewer CPU minutes, which matters on shared CI runners and machines that run several suites at once. Peak memory barely moves, because the 8 tap jobs and their test processes dominate it. The 1,000-file figures come from one round each; the [10- and 100-file runs](benchmark/results) show the same trend with 3 rounds each.
219
+
220
+ ### Smaller suites on Linux, Windows and macOS
221
+
222
+ <p align="center">
223
+ <img alt="Wall time for 120 HTTP test cases on Linux. Fastify: 13.6 s per file, 12.1 s pooled, 12.0 s with instances. Express: 13.3 s, 12.8 s, 13.1 s. NestJS: 24.9 s, 19.6 s, 19.8 s." src="docs/assets/benchmark-wall-linux.svg" width="760">
224
+ </p>
225
+
226
+ <p align="center">
227
+ <img alt="Wall time for 24 HTTP test cases on Windows. Fastify: 6.1 s per file, 5.9 s pooled, 5.6 s with instances. Express: 5.9 s, 5.5 s, 5.6 s. NestJS: 7.8 s, 6.1 s, 6.7 s." src="docs/assets/benchmark-wall-windows.svg" width="760">
228
+ </p>
229
+
230
+ <p align="center">
231
+ <img alt="Wall time for 24 HTTP test cases on macOS. Fastify: 3.1 s per file, 3.0 s pooled, 3.4 s with instances. Express: 2.6 s, 2.6 s, 2.4 s. NestJS: 5.2 s, 3.6 s, 3.8 s." src="docs/assets/benchmark-wall-macos.svg" width="760">
232
+ </p>
233
+
234
+ | New app per file → pool / instances | Linux, 120 cases | Windows, 24 cases | macOS, 24 cases |
235
+ | --- | ---: | ---: | ---: |
236
+ | NestJS 11.2.12 | 24.9 s → **19.6 s** (−21%) / **19.8 s** (−20%) | 7.8 s → **6.1 s** (−22%) / **6.7 s** (−15%) | 5.2 s → **3.6 s** (−31%) / **3.8 s** (−26%) |
237
+ | Fastify 5.12.8 | 13.6 s → **12.1 s** (−11%) / **12.0 s** (−12%) | 6.1 s → **5.9 s** (−4%) / **5.6 s** (−8%) | 3.1 s → 3.0 s (−5%) / 3.4 s (+8%) |
238
+ | Express 5.3.0 | 13.3 s → **12.8 s** (−4%) / **13.1 s** (−1%) | 5.9 s → **5.5 s** (−6%) / **5.6 s** (−5%) | 2.6 s → 2.6 s (+3%) / **2.4 s** (−5%) |
239
+
240
+ These runs use 2 tap jobs and up to 2 workers and report the median of 3 rounds. With 2 jobs, the pool and instances are within the run-to-run variation of a shared runner of each other. The gain grows with the cost of starting the application: NestJS builds a dependency injection container on every start, while a minimal Express app starts quickly and saves little, because tap still starts a process for every test file. Applications that connect to databases, run migrations or warm caches at startup should save more than these minimal examples.
241
+
242
+ ### Run it yourself
243
+
244
+ The Actions figures come from the `Application pool benchmark` workflow on GitHub Actions (Node.js 24, node-tap 21.8.1), and the local ones from the same script on a Windows 11 machine. The raw results are in [benchmark/results](benchmark/results), with the local runs in the `windows-local-*` files.
111
245
 
112
246
  ```sh
113
247
  npm run --silent benchmark -- --framework fastify --bootstrap-ms 0
114
248
  ```
115
249
 
116
- `--framework` accepts `fastify`, `express` and `nestjs`. `--resources` adds CPU and memory sampling on Linux with procps, GNU `time` and GNU `timeout`. Published figures will be added after the plugin has been measured on GitHub Actions.
250
+ `--framework` accepts `fastify`, `express` and `nestjs`, and `--mode` picks `per-case`, `per-file`, `pooled` or `instanced` (all four by default). `--instances` sets the cases each worker serves in the `instanced` mode and defaults to `--jobs`. `--resources` adds CPU and memory sampling: on Linux with procps, GNU `time` and GNU `timeout`, and on Windows through CIM in PowerShell. To reproduce the local comparison on a 12-core machine, run `npm run --silent benchmark -- --framework nestjs --files 30 --cases 4 --jobs 12 --workers 12 --bootstrap-ms 0 --mode per-file --mode pooled --mode instanced --resources`. `node benchmark/chart.js` draws the charts from the result files.
117
251
 
118
252
  ## Status and roadmap
119
253
 
120
- RunWarm is an early alpha (`0.1.0-alpha.1`). The acceptance suite installs the package as a user would and covers reuse and reset, concurrent reservations, failing profiles, crashed workers, disconnected clients and interrupted runs.
254
+ RunWarm is at version 0.x: until 1.0.0, a minor version can still change options or profile hook behavior, and the [changelog](CHANGELOG.md) marks each such change. The acceptance suite installs the package as a user would and covers reuse and reset, concurrent reservations, failing profiles, crashed workers, disconnected clients and interrupted runs.
121
255
 
122
- - Publish benchmark results for the plugin.
123
256
  - Measure a real CI suite with a database-backed profile and background jobs.
124
257
  - Collect application coverage and track changed files for `tap --changed`.
125
258
  - Evaluate multiple profiles per run.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "runwarm",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.3.0",
4
4
  "description": "node-tap plugin that keeps HTTP applications warm between integration tests",
5
5
  "keywords": [
6
6
  "tapjs plugin",
package/src/client.d.ts CHANGED
@@ -6,6 +6,12 @@ export interface CaseContext extends HookContext {
6
6
  caseName: string
7
7
  }
8
8
 
9
+ export interface InstanceContext extends CaseContext {
10
+ /** Unique within the run. Use it to name per-case resources such as a database schema. */
11
+ instanceId: string
12
+ }
13
+
14
+ /** One application per worker, shared by its cases one at a time and reset between them. */
9
15
  export interface AppProfile<App extends { url: string }> {
10
16
  start(context: HookContext): App | Promise<App>
11
17
  prepare?(app: App, context: CaseContext): unknown
@@ -13,6 +19,21 @@ export interface AppProfile<App extends { url: string }> {
13
19
  stop(app: App): unknown
14
20
  }
15
21
 
22
+ /**
23
+ * Shared state booted once per worker, and an application instance of its own for
24
+ * each case. Cases run concurrently in the worker (see app-instances), so everything
25
+ * a case can change must live in its instance, never in `Shared` or in globals.
26
+ */
27
+ export interface IsolatedAppProfile<Shared, Instance extends { url: string }> {
28
+ boot?(context: HookContext): Shared | Promise<Shared>
29
+ instance(shared: Shared, context: InstanceContext): Instance | Promise<Instance>
30
+ dispose(shared: Shared, instance: Instance, context: InstanceContext): unknown
31
+ shutdown?(shared: Shared): unknown
32
+ }
33
+
34
+ export declare function defineAppProfile<Shared, Instance extends { url: string }>(
35
+ profile: IsolatedAppProfile<Shared, Instance>,
36
+ ): IsolatedAppProfile<Shared, Instance>
16
37
  export declare function defineAppProfile<App extends { url: string }>(profile: AppProfile<App>): AppProfile<App>
17
38
 
18
39
  export declare function withApp<T>(
package/src/client.js CHANGED
@@ -2,8 +2,22 @@ import { connect } from 'node:net'
2
2
  import { once } from 'node:events'
3
3
  import { messages, receive, send } from './protocol.js'
4
4
 
5
+ // A profile either starts one application that every case shares and resets
6
+ // (start, reset, stop), or boots shared state once and gives each case an
7
+ // application instance of its own (boot, instance, dispose, shutdown).
8
+ const classicHooks = ['start', 'reset', 'stop']
9
+ const isolatedHooks = ['instance', 'dispose']
10
+
11
+ export function isIsolatedProfile(profile) {
12
+ return typeof profile?.instance === 'function'
13
+ }
14
+
5
15
  export function defineAppProfile(profile) {
6
- for (const hook of ['start', 'reset', 'stop']) {
16
+ const isolated = ['boot', 'instance', 'dispose', 'shutdown'].some(hook => profile?.[hook] !== undefined)
17
+ if (isolated && ['start', 'prepare', 'reset', 'stop'].some(hook => profile[hook] !== undefined)) {
18
+ throw new TypeError('A profile uses either start, prepare, reset and stop, or boot, instance, dispose and shutdown')
19
+ }
20
+ for (const hook of isolated ? isolatedHooks : classicHooks) {
7
21
  if (typeof profile?.[hook] !== 'function') throw new TypeError('Missing profile hook: ' + hook)
8
22
  }
9
23
  return profile
@@ -13,7 +27,10 @@ export async function withApp(caseName, run) {
13
27
  const path = process.env.RUNWARM_SOCKET
14
28
  const token = process.env.RUNWARM_TOKEN
15
29
  if (!path || !token) {
16
- throw new Error('RunWarm is not running. Add the runwarm/plugin tap plugin and set app-profile')
30
+ if (process.env.RUNWARM_IDLE) {
31
+ throw new Error('RunWarm is idle: the plugin is loaded but there is no profile. Pass --app-profile=<module> or set app-profile in .taprc')
32
+ }
33
+ throw new Error('RunWarm is not running. Add the runwarm/plugin tap plugin (npx tap plugin add runwarm/plugin) and set app-profile')
17
34
  }
18
35
  const socket = connect(path)
19
36
  try {
@@ -3,10 +3,22 @@ import { once } from 'node:events'
3
3
  import { Pool } from './pool.js'
4
4
  import { messages, receive, send } from './protocol.js'
5
5
 
6
- export async function startCoordinator(profileURL, size, metrics, { path, token }) {
7
- const pool = new Pool(profileURL, size, metrics)
6
+ export async function startCoordinator(profileURL, size, metrics, { path, token, timeoutMs, prewarm = 0, instances = 1 }) {
7
+ const pool = new Pool(profileURL, size, metrics, timeoutMs, instances)
8
8
  const sessions = new Set()
9
9
  const sockets = new Set()
10
+ const reportedGlobals = new Set()
11
+
12
+ function reportGlobals(caseName, keys) {
13
+ metrics?.isolationWarning()
14
+ for (const key of keys) {
15
+ if (reportedGlobals.has(key)) continue
16
+ reportedGlobals.add(key)
17
+ process.stderr.write('runwarm: the application worker gained the global ' + JSON.stringify(key) +
18
+ ' by the end of "' + caseName + '"' + (instances > 1 ? ' (or of a case running at the same time)' : '') +
19
+ '; state kept in globals is shared by every case in that worker\n')
20
+ }
21
+ }
10
22
 
11
23
  async function serve(socket) {
12
24
  const controller = new AbortController()
@@ -16,34 +28,63 @@ export async function startCoordinator(profileURL, size, metrics, { path, token
16
28
  socket.on('error', cancel)
17
29
  const stream = messages(socket)
18
30
  let slot
31
+ let caseName
32
+ // An isolated instance that was opened but not closed yet.
33
+ let instanceId
34
+ // Set once the worker was asked to prepare the case; a case that ends before
35
+ // that leaves the worker untouched.
36
+ let opened = false
37
+ let closing = false
38
+ async function closeCase() {
39
+ closing = true
40
+ const resetAt = metrics && performance.now()
41
+ try {
42
+ const { leakedGlobals } = await pool.closeCase(slot, caseName, instanceId)
43
+ if (leakedGlobals) reportGlobals(caseName, leakedGlobals)
44
+ } catch (error) {
45
+ metrics?.resetFailed()
46
+ throw error
47
+ } finally {
48
+ metrics?.record('reset', performance.now() - resetAt)
49
+ }
50
+ }
19
51
  try {
20
52
  socket.setTimeout(5000, () => socket.destroy())
21
53
  const hello = await receive(stream)
22
54
  if (hello.token !== token) throw new Error('Invalid session')
23
- if (typeof hello.caseName !== 'string' || hello.caseName.length > 1024) {
55
+ if (typeof hello.caseName !== 'string' || hello.caseName.length > 4096) {
24
56
  throw new Error('Invalid test case name')
25
57
  }
58
+ caseName = hello.caseName
26
59
  socket.setTimeout(0)
27
60
  const queuedAt = metrics && performance.now()
28
61
  slot = await pool.acquire(controller.signal)
29
62
  metrics?.record('queueWait', performance.now() - queuedAt)
30
63
  controller.signal.throwIfAborted()
31
- const app = await pool.prepare(slot, hello.caseName)
32
- controller.signal.throwIfAborted()
33
- send(socket, app)
34
- const request = await receive(stream)
35
- if (request.release !== true) throw new Error('Expected release')
36
- const resetAt = metrics && performance.now()
64
+ const preparedAt = metrics && performance.now()
65
+ opened = true
66
+ let app
37
67
  try {
38
- await slot.worker.command('reset', hello.caseName)
68
+ app = await pool.openCase(slot, caseName)
39
69
  } finally {
40
- metrics?.record('reset', performance.now() - resetAt)
70
+ metrics?.record('prepare', performance.now() - preparedAt)
41
71
  }
72
+ instanceId = app.instanceId
73
+ controller.signal.throwIfAborted()
74
+ send(socket, { url: app.url, workerId: app.workerId })
75
+ const request = await receive(stream)
76
+ if (request.release !== true) throw new Error('Expected release')
77
+ await closeCase()
42
78
  send(socket, { ok: true })
43
79
  } catch (error) {
44
- if (slot?.worker) {
45
- await slot.worker.discard()
46
- slot.worker = null
80
+ if (slot?.worker && opened) {
81
+ // A case that ends early still disposes its own instance; the worker stays
82
+ // only if that works. A shared application is in an unknown state instead.
83
+ let kept = false
84
+ if (instanceId && !closing) {
85
+ kept = await closeCase().then(() => true, () => false)
86
+ }
87
+ if (!kept) pool.discard(slot)
47
88
  }
48
89
  if (!socket.destroyed && socket.writable) send(socket, { error: error.message })
49
90
  } finally {
@@ -63,13 +104,18 @@ export async function startCoordinator(profileURL, size, metrics, { path, token
63
104
  // processes without waiting for this function to resolve.
64
105
  server.listen(path)
65
106
  await once(server, 'listening')
107
+ // Starts applications in the background while tap loads the test files.
108
+ if (prewarm > 0) pool.warm(prewarm)
66
109
  return {
67
110
  async close() {
68
111
  const closed = new Promise(resolve => server.close(resolve))
69
112
  for (const socket of sockets) socket.destroy()
70
113
  await Promise.allSettled(sessions)
71
- await pool.close()
72
- await closed
114
+ try {
115
+ await pool.close()
116
+ } finally {
117
+ await closed
118
+ }
73
119
  },
74
120
  }
75
121
  }
package/src/metrics.js CHANGED
@@ -1,27 +1,52 @@
1
1
  export function createRunMetrics() {
2
2
  const startedAt = performance.now()
3
+ const timing = () => ({ count: 0, totalMs: 0, maxMs: 0 })
3
4
  const totals = {
4
5
  workersStarted: 0,
6
+ workersDiscarded: 0,
7
+ resetFailures: 0,
8
+ isolationWarnings: 0,
9
+ peakConcurrentCases: 0,
5
10
  maxAppProcessRssKiB: 0,
6
- bootstrap: { count: 0, totalMs: 0, maxMs: 0 },
7
- queueWait: { count: 0, totalMs: 0, maxMs: 0 },
8
- reset: { count: 0, totalMs: 0, maxMs: 0 },
11
+ // A worker's cold start is processStart + profileImport + bootstrap.
12
+ processStart: timing(),
13
+ profileImport: timing(),
14
+ bootstrap: timing(),
15
+ queueWait: timing(),
16
+ prepare: timing(),
17
+ reset: timing(),
9
18
  }
10
19
 
11
20
  function record(stage, durationMs) {
12
- const timing = totals[stage]
13
- timing.count++
14
- timing.totalMs += durationMs
15
- timing.maxMs = Math.max(timing.maxMs, durationMs)
21
+ const entry = totals[stage]
22
+ entry.count++
23
+ entry.totalMs += durationMs
24
+ entry.maxMs = Math.max(entry.maxMs, durationMs)
16
25
  }
17
26
 
18
27
  return {
19
28
  workerStarted() {
20
29
  totals.workersStarted++
21
30
  },
31
+ workerDiscarded() {
32
+ totals.workersDiscarded++
33
+ },
34
+ resetFailed() {
35
+ totals.resetFailures++
36
+ },
37
+ isolationWarning() {
38
+ totals.isolationWarnings++
39
+ },
40
+ observeActive(cases) {
41
+ totals.peakConcurrentCases = Math.max(totals.peakConcurrentCases, cases)
42
+ },
22
43
  record,
23
- observeWorker({ bootstrapMs, maxRssKiB }) {
24
- if (bootstrapMs !== undefined) record('bootstrap', bootstrapMs)
44
+ observeWorker({ processStartMs, importMs, bootstrapMs, maxRssKiB }) {
45
+ if (bootstrapMs !== undefined) {
46
+ record('processStart', processStartMs)
47
+ record('profileImport', importMs)
48
+ record('bootstrap', bootstrapMs)
49
+ }
25
50
  totals.maxAppProcessRssKiB = Math.max(totals.maxAppProcessRssKiB, maxRssKiB)
26
51
  },
27
52
  report() {
package/src/pool.js CHANGED
@@ -1,70 +1,138 @@
1
1
  import { fork } from 'node:child_process'
2
2
  import { randomUUID } from 'node:crypto'
3
3
 
4
- function startWorker(profileURL, metrics) {
4
+ // The application under test must not open pool sessions of its own.
5
+ function workerEnv() {
6
+ const env = { ...process.env }
7
+ delete env.RUNWARM_SOCKET
8
+ delete env.RUNWARM_TOKEN
9
+ delete env.RUNWARM_IDLE
10
+ return env
11
+ }
12
+
13
+ function startWorker(profileURL, capacity, metrics, timeoutMs) {
5
14
  const workerId = randomUUID()
6
- const args = [profileURL, workerId]
15
+ const args = [profileURL, workerId, String(capacity)]
7
16
  if (metrics) args.push('--metrics')
8
17
  const child = fork(new URL('./worker.js', import.meta.url), args, {
9
18
  stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
10
19
  execArgv: [],
20
+ env: workerEnv(),
11
21
  })
12
22
  if (metrics) child.once('spawn', () => metrics.workerStarted())
13
23
  let dead = false
24
+ // Set when a command times out: the worker may be wedged, so it takes no new cases
25
+ // and is killed without running its stop hook.
26
+ let timedOut = false
27
+ let nextId = 0
28
+ const pending = new Map()
14
29
  const closed = new Promise(resolve => child.once('close', () => { dead = true; resolve() }))
15
- // Async fork failures are also reported to any pending command.
16
- child.on('error', () => {})
17
30
 
18
- function command(action, caseName) {
31
+ function failAll(error) {
32
+ for (const { finish } of pending.values()) finish(error)
33
+ }
34
+ child.on('message', ({ id, metrics: sample, ...message }) => {
35
+ if (sample) metrics?.observeWorker(sample)
36
+ // A reply that arrives after its command timed out has no pending entry and is dropped.
37
+ pending.get(id)?.finish(message.error ? new Error(message.error) : null, message)
38
+ })
39
+ child.once('exit', () => {
40
+ for (const { action, finish } of pending.values()) finish(new Error('Worker exited during ' + action))
41
+ })
42
+ // Async fork failures are reported to every pending command.
43
+ child.on('error', failAll)
44
+
45
+ function command(action, fields) {
19
46
  if (dead || !child.connected) return Promise.reject(new Error('Worker unavailable'))
20
47
  return new Promise((resolve, reject) => {
48
+ const id = ++nextId
21
49
  function finish(error, value) {
22
50
  clearTimeout(timer)
23
- child.off('message', onMessage)
24
- child.off('exit', onExit)
25
- child.off('error', onError)
51
+ pending.delete(id)
26
52
  if (error) reject(error)
27
53
  else resolve(value)
28
54
  }
29
- const onMessage = ({ metrics: sample, ...message }) => {
30
- if (sample) metrics?.observeWorker(sample)
31
- finish(message.error ? new Error(message.error) : null, message)
32
- }
33
- const onExit = () => finish(new Error('Worker exited during ' + action))
34
- const onError = error => finish(error)
35
- const timer = setTimeout(() => finish(new Error('Worker timeout during ' + action)), 30_000)
36
- child.once('message', onMessage)
37
- child.once('exit', onExit)
38
- child.once('error', onError)
39
- child.send({ action, caseName }, error => { if (error) finish(error) })
55
+ const timer = setTimeout(() => {
56
+ timedOut = true
57
+ finish(new Error('Worker timeout during ' + action))
58
+ }, timeoutMs)
59
+ pending.set(id, { action, finish })
60
+ child.send({ id, action, ...fields }, error => { if (error) finish(error) })
40
61
  })
41
62
  }
42
63
 
43
- async function discard() {
64
+ // Runs the stop hook while the worker still responds, then kills it. A failed
65
+ // stop is reported after the process is gone.
66
+ async function retire() {
67
+ let failure
68
+ if (!dead && !timedOut && child.connected) {
69
+ try {
70
+ await command('stop')
71
+ } catch (error) {
72
+ failure = error
73
+ }
74
+ }
44
75
  if (!dead) child.kill('SIGKILL')
45
76
  await closed
77
+ if (failure) throw failure
46
78
  }
47
79
 
48
- return { command, discard, get alive() { return child.connected && !dead } }
80
+ return { command, retire, get alive() { return child.connected && !dead && !timedOut } }
49
81
  }
50
82
 
83
+ // Each entry is one worker process position. A classic profile serves one case per
84
+ // worker; an isolated profile serves up to `capacity` cases at once, each with its
85
+ // own application instance.
51
86
  export class Pool {
52
- constructor(profileURL, size, metrics) {
87
+ constructor(profileURL, size, metrics, timeoutMs, capacity = 1) {
53
88
  this.profileURL = profileURL
54
89
  this.metrics = metrics
55
- this.slots = Array.from({ length: size }, () => ({ busy: false, worker: null }))
90
+ this.timeoutMs = timeoutMs
91
+ this.capacity = capacity
92
+ this.entries = Array.from({ length: size }, () => ({ worker: null, active: 0, draining: false, retiring: null }))
56
93
  this.waiters = []
94
+ this.background = new Set()
57
95
  this.closing = false
96
+ this.leased = 0
97
+ }
98
+
99
+ usable(entry) {
100
+ return !entry.draining && entry.worker?.alive === true
101
+ }
102
+
103
+ spawn(entry) {
104
+ // A worker that died between cases is replaced here; the process is already gone.
105
+ if (entry.worker) this.metrics?.workerDiscarded()
106
+ entry.worker = startWorker(this.profileURL, this.capacity, this.metrics, this.timeoutMs)
107
+ }
108
+
109
+ // Prefers a running worker, even one still booting, over a cold start: joining it
110
+ // costs at most the rest of its boot. Among running workers the least busy wins.
111
+ pick() {
112
+ if (this.closing) return undefined
113
+ let best
114
+ for (const entry of this.entries) {
115
+ if (this.usable(entry) && entry.active < this.capacity && (!best || entry.active < best.active)) best = entry
116
+ }
117
+ if (best) return best
118
+ // A position is reused only after its previous worker has fully stopped.
119
+ const empty = this.entries.find(entry => entry.active === 0 && !entry.retiring && !this.usable(entry))
120
+ if (empty) this.spawn(empty)
121
+ return empty
122
+ }
123
+
124
+ lease(entry) {
125
+ entry.active++
126
+ this.leased++
127
+ this.metrics?.observeActive(this.leased)
128
+ return entry
58
129
  }
59
130
 
60
131
  async acquire(signal) {
61
132
  signal.throwIfAborted()
62
133
  if (this.closing) throw new Error('Pool is closing')
63
- const slot = this.slots.find(candidate => !candidate.busy)
64
- if (slot) {
65
- slot.busy = true
66
- return slot
67
- }
134
+ const entry = this.pick()
135
+ if (entry) return this.lease(entry)
68
136
  return new Promise((resolve, reject) => {
69
137
  const waiter = { resolve, reject }
70
138
  const abort = () => {
@@ -77,16 +145,68 @@ export class Pool {
77
145
  })
78
146
  }
79
147
 
80
- async prepare(slot, caseName) {
81
- if (!slot.worker?.alive) slot.worker = startWorker(this.profileURL, this.metrics)
82
- return slot.worker.command('prepare', caseName)
148
+ dispatch() {
149
+ while (this.waiters.length) {
150
+ const entry = this.pick()
151
+ if (!entry) return
152
+ const waiter = this.waiters.shift()
153
+ waiter.detach()
154
+ waiter.resolve(this.lease(entry))
155
+ }
156
+ }
157
+
158
+ openCase(entry, caseName) {
159
+ return entry.worker.command('prepare', { caseName })
160
+ }
161
+
162
+ closeCase(entry, caseName, instanceId) {
163
+ return entry.worker.command('reset', { caseName, instanceId })
164
+ }
165
+
166
+ // Starts up to `count` workers ahead of the first test. Cases that arrive during
167
+ // the warm-up join the booting worker instead of starting another one. A failed
168
+ // warm-up is not reported here: the next case starts a new worker and sees the real error.
169
+ warm(count) {
170
+ for (const entry of this.entries.slice(0, count)) {
171
+ if (this.closing || entry.worker) continue
172
+ this.spawn(entry)
173
+ const { worker } = entry
174
+ // Only the worker this warm-up started is discarded, never one that replaced it.
175
+ this.track(worker.command('warm').catch(() => { if (entry.worker === worker) this.discard(entry) }))
176
+ }
83
177
  }
84
178
 
85
- release(slot) {
86
- const waiter = this.waiters.shift()
87
- if (!waiter) { slot.busy = false; return }
88
- waiter.detach()
89
- waiter.resolve(slot)
179
+ // The worker takes no new cases and is stopped once its current cases are released.
180
+ discard(entry) {
181
+ if (!entry.worker || entry.draining) return
182
+ entry.draining = true
183
+ this.metrics?.workerDiscarded()
184
+ if (entry.active === 0) this.retire(entry)
185
+ }
186
+
187
+ release(entry) {
188
+ entry.active--
189
+ this.leased--
190
+ if (entry.draining && entry.active === 0) this.retire(entry)
191
+ this.dispatch()
192
+ }
193
+
194
+ // Stops the worker in the background, so no case waits for its stop hook. The
195
+ // case that discarded it already failed with the original error, so a failed stop
196
+ // is not reported.
197
+ retire(entry) {
198
+ entry.retiring = entry.worker.retire().catch(() => {}).finally(() => {
199
+ entry.worker = null
200
+ entry.draining = false
201
+ entry.retiring = null
202
+ this.dispatch()
203
+ })
204
+ this.track(entry.retiring)
205
+ }
206
+
207
+ track(promise) {
208
+ this.background.add(promise)
209
+ promise.finally(() => this.background.delete(promise))
90
210
  }
91
211
 
92
212
  async close() {
@@ -95,13 +215,12 @@ export class Pool {
95
215
  waiter.detach()
96
216
  waiter.reject(new Error('Pool is closing'))
97
217
  }
98
- await Promise.all(this.slots.map(async ({ worker, busy }) => {
99
- if (!worker) return
100
- try {
101
- if (worker.alive && !busy) await worker.command('stop')
102
- } finally {
103
- await worker.discard()
104
- }
105
- }))
218
+ // Warm-up commands and background stops are bounded by the hook timeout.
219
+ while (this.background.size) await Promise.allSettled(this.background)
220
+ // Every worker is retired even when another one fails to stop.
221
+ const results = await Promise.allSettled(this.entries.map(entry => entry.worker?.retire()))
222
+ const errors = results.filter(result => result.status === 'rejected').map(result => result.reason)
223
+ if (errors.length === 1) throw errors[0]
224
+ if (errors.length > 1) throw new AggregateError(errors, 'Workers failed to stop')
106
225
  }
107
226
  }
package/src/protocol.js CHANGED
@@ -4,19 +4,23 @@ export function send(socket, message) {
4
4
  socket.write(JSON.stringify(message) + '\n')
5
5
  }
6
6
 
7
+ const maxMessageBytes = 8192
8
+
7
9
  // Control messages contain only short identifiers, status and a loopback URL.
10
+ // The limit applies to each message, not to everything a chunk carries.
8
11
  export async function* messages(socket) {
9
12
  let pending = ''
10
13
  socket.setEncoding('utf8')
11
14
  for await (const chunk of socket) {
12
15
  pending += chunk
13
- if (Buffer.byteLength(pending) > 8192) throw new Error('Control message too large')
14
16
  let end
15
17
  while ((end = pending.indexOf('\n')) >= 0) {
16
18
  const line = pending.slice(0, end)
17
19
  pending = pending.slice(end + 1)
20
+ if (Buffer.byteLength(line) > maxMessageBytes) throw new Error('Control message too large')
18
21
  yield JSON.parse(line)
19
22
  }
23
+ if (Buffer.byteLength(pending) > maxMessageBytes) throw new Error('Control message too large')
20
24
  }
21
25
  }
22
26
 
@@ -2,6 +2,10 @@ export declare const config: {
2
2
  'app-profile': { type: 'string'; description: string }
3
3
  'app-workers': { type: 'number'; default: number; description: string }
4
4
  'app-metrics': { type: 'boolean'; description: string }
5
+ 'app-metrics-file': { type: 'string'; description: string }
6
+ 'app-prewarm': { type: 'number'; default: number; description: string }
7
+ 'app-instances': { type: 'number'; default: number; description: string }
8
+ 'app-timeout': { type: 'number'; default: number; description: string }
5
9
  }
6
10
 
7
11
  export interface RunWarm {
package/src/tap-plugin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // node-tap plugin. The tap runner hosts the application pool and
2
2
  // test files reach it through t.withApp().
3
3
  import { randomBytes } from 'node:crypto'
4
- import { mkdtempSync, rmSync, statSync } from 'node:fs'
4
+ import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'
5
5
  import { tmpdir } from 'node:os'
6
6
  import { join, resolve } from 'node:path'
7
7
  import { pathToFileURL } from 'node:url'
@@ -23,18 +23,52 @@ export const config = {
23
23
  type: 'boolean',
24
24
  description: 'Print pool metrics to stderr when the run ends',
25
25
  },
26
+ 'app-metrics-file': {
27
+ type: 'string',
28
+ description: 'Write the pool metrics as JSON to this file when the run ends',
29
+ },
30
+ 'app-prewarm': {
31
+ type: 'number',
32
+ default: 0,
33
+ description: 'Number of application workers to start before the first test asks for one',
34
+ },
35
+ 'app-instances': {
36
+ type: 'number',
37
+ default: 1,
38
+ description: 'Cases each worker serves at the same time, each with its own application instance. Above 1 needs a profile with instance and dispose hooks',
39
+ },
40
+ 'app-timeout': {
41
+ type: 'number',
42
+ default: 30,
43
+ description: 'Seconds each profile hook may take before its worker is discarded',
44
+ },
26
45
  }
27
46
 
28
47
  function host(t) {
29
48
  const profile = process.env.TAP_APP_PROFILE
30
- if (!profile) return
49
+ if (!profile) {
50
+ // Lets withApp() tell a loaded plugin without a profile from a missing plugin.
51
+ process.env.RUNWARM_IDLE = '1'
52
+ return
53
+ }
31
54
  const size = Number(process.env.TAP_APP_WORKERS || 1)
32
55
  if (!Number.isSafeInteger(size) || size < 1) throw new Error('app-workers must be a positive integer')
56
+ const timeoutMs = Number(process.env.TAP_APP_TIMEOUT || 30) * 1000
57
+ // setTimeout() treats delays above 2^31 - 1 ms as 1 ms.
58
+ if (!(timeoutMs > 0 && timeoutMs <= 2_147_483_647)) {
59
+ throw new Error('app-timeout must be a positive number of seconds up to 2147483')
60
+ }
33
61
  const file = resolve(profile)
34
62
  if (!statSync(file, { throwIfNoEntry: false })?.isFile()) {
35
63
  throw new Error('app-profile not found: ' + file)
36
64
  }
37
- const metrics = process.env.TAP_APP_METRICS === '1' ? createRunMetrics() : undefined
65
+ const prewarm = Number(process.env.TAP_APP_PREWARM || 0)
66
+ if (!Number.isSafeInteger(prewarm) || prewarm < 0) throw new Error('app-prewarm must be a non-negative integer')
67
+ const instances = Number(process.env.TAP_APP_INSTANCES || 1)
68
+ if (!Number.isSafeInteger(instances) || instances < 1) throw new Error('app-instances must be a positive integer')
69
+ const metricsFile = process.env.TAP_APP_METRICS_FILE ? resolve(process.env.TAP_APP_METRICS_FILE) : undefined
70
+ const printMetrics = process.env.TAP_APP_METRICS === '1'
71
+ const metrics = printMetrics || metricsFile ? createRunMetrics() : undefined
38
72
 
39
73
  // Plugins load synchronously and the runner copies process.env right after,
40
74
  // so the address and token are chosen here instead of read back from listen().
@@ -44,7 +78,7 @@ function host(t) {
44
78
  process.env.RUNWARM_SOCKET = path
45
79
  process.env.RUNWARM_TOKEN = token
46
80
 
47
- const pool = startCoordinator(pathToFileURL(file).href, size, metrics, { path, token })
81
+ const pool = startCoordinator(pathToFileURL(file).href, size, metrics, { path, token, timeoutMs, prewarm, instances })
48
82
  // Reported from the teardown below.
49
83
  pool.catch(() => {})
50
84
 
@@ -54,16 +88,39 @@ function host(t) {
54
88
  await (await pool).close()
55
89
  } finally {
56
90
  if (dir) rmSync(dir, { recursive: true, force: true })
57
- if (metrics) process.stderr.write('runwarm metrics: ' + JSON.stringify(metrics.report()) + '\n')
91
+ if (metrics) {
92
+ const report = JSON.stringify(metrics.report())
93
+ if (printMetrics) process.stderr.write('runwarm metrics: ' + report + '\n')
94
+ // A report that cannot be written must not fail the run or hide a pool shutdown error.
95
+ if (metricsFile) {
96
+ try {
97
+ writeFileSync(metricsFile, report + '\n')
98
+ } catch (error) {
99
+ process.stderr.write('runwarm: cannot write app-metrics-file: ' + error.message + '\n')
100
+ }
101
+ }
102
+ }
58
103
  }
59
104
  }))
60
105
  }
61
106
 
107
+ // The test file followed by the names of the test and its parents, so cases with
108
+ // the same name in different files stay apart. tap's own fullname also includes
109
+ // the name of the root test, which is always "TAP".
110
+ function caseName(test) {
111
+ const names = []
112
+ let root = test
113
+ for (; root.parent; root = root.parent) names.unshift(root.name)
114
+ const suffix = ' > ' + root.name
115
+ const file = root.fullname.endsWith(suffix) ? root.fullname.slice(0, -suffix.length) : root.fullname
116
+ return [file, ...names].join(' > ')
117
+ }
118
+
62
119
  export function plugin(t, opts) {
63
120
  if (opts?.context === Symbol.for('tap.isRunner')) host(t)
64
121
  return {
65
122
  withApp(run) {
66
- return withApp(t.t.name, run)
123
+ return withApp(caseName(t.t), run)
67
124
  },
68
125
  }
69
126
  }
package/src/worker.js CHANGED
@@ -1,41 +1,133 @@
1
- import { defineAppProfile } from './client.js'
1
+ import { defineAppProfile, isIsolatedProfile } from './client.js'
2
2
 
3
- const [profileURL, workerId, metricsFlag] = process.argv.slice(2)
4
- // Loaded on first use so that import and validation errors reach the test.
5
- let profile
3
+ // Time from process start to this module, reported as part of the cold start.
4
+ const processStartMs = performance.now()
5
+ const [profileURL, workerId, capacityArg, metricsFlag] = process.argv.slice(2)
6
+ const capacity = Number(capacityArg)
6
7
  const context = { workerId }
7
- let app
8
8
 
9
- process.once('disconnect', () => process.exit(1))
10
- process.on('message', async ({ action, caseName }) => {
11
- let bootstrapMs
12
- function reply(message) {
13
- if (metricsFlag) message.metrics = { bootstrapMs, maxRssKiB: process.resourceUsage().maxRSS }
14
- process.send(message)
9
+ let loading
10
+ let booting
11
+ let importMs
12
+ let bootstrapMs
13
+ let coldStartReported = false
14
+ // Isolated profiles: instances still open, and the globals that existed after boot.
15
+ const instances = new Map()
16
+ let nextInstance = 0
17
+ let baseline
18
+
19
+ // Loaded on first use so that import and validation errors reach the test.
20
+ function load() {
21
+ loading ??= (async () => {
22
+ const startedAt = performance.now()
23
+ const profile = defineAppProfile((await import(profileURL)).default)
24
+ importMs = performance.now() - startedAt
25
+ if (capacity > 1 && !isIsolatedProfile(profile)) {
26
+ throw new Error('app-instances above 1 needs a profile with instance and dispose hooks')
27
+ }
28
+ return profile
29
+ })()
30
+ return loading
31
+ }
32
+
33
+ // Starts the application once per worker, also when several commands ask at the same time.
34
+ function boot() {
35
+ booting ??= (async () => {
36
+ const profile = await load()
37
+ const startedAt = performance.now()
38
+ const shared = isIsolatedProfile(profile) ? await profile.boot?.(context) : await profile.start(context)
39
+ bootstrapMs = performance.now() - startedAt
40
+ baseline = new Set(Reflect.ownKeys(globalThis))
41
+ return { profile, shared }
42
+ })()
43
+ return booting
44
+ }
45
+
46
+ function checkURL(app) {
47
+ const url = new URL(app?.url)
48
+ if (!['http:', 'https:'].includes(url.protocol) || url.hostname !== '127.0.0.1') {
49
+ throw new Error('Profile must expose an HTTP or HTTPS URL on 127.0.0.1')
50
+ }
51
+ return url.href
52
+ }
53
+
54
+ // Globals that appear while instances run are shared by every later case in this worker.
55
+ // With concurrent cases, the case that closes first is named even if another one added them.
56
+ function newGlobals() {
57
+ const added = Reflect.ownKeys(globalThis).filter(key => !baseline.has(key))
58
+ for (const key of added) baseline.add(key)
59
+ return added.length ? added.map(String) : undefined
60
+ }
61
+
62
+ async function open(caseName) {
63
+ const { profile, shared } = await boot()
64
+ if (!isIsolatedProfile(profile)) {
65
+ const url = checkURL(shared)
66
+ await profile.prepare?.(shared, { workerId, caseName })
67
+ return { url, workerId }
15
68
  }
69
+ const instanceId = workerId.slice(0, 8) + '-' + ++nextInstance
70
+ const instance = await profile.instance(shared, { workerId, instanceId, caseName })
71
+ instances.set(instanceId, { instance, caseName })
72
+ return { url: checkURL(instance), workerId, instanceId }
73
+ }
16
74
 
75
+ async function close(caseName, instanceId) {
76
+ const { profile, shared } = await boot()
77
+ if (!isIsolatedProfile(profile)) {
78
+ await profile.reset(shared, { workerId, caseName })
79
+ return { ok: true }
80
+ }
81
+ const entry = instances.get(instanceId)
82
+ if (!entry) throw new Error('Unknown application instance ' + instanceId)
83
+ instances.delete(instanceId)
84
+ await profile.dispose(shared, entry.instance, { workerId, instanceId, caseName })
85
+ return { ok: true, leakedGlobals: newGlobals() }
86
+ }
87
+
88
+ async function stop() {
89
+ // An application that never started has nothing to stop.
90
+ const booted = await booting?.catch(() => undefined)
91
+ if (!booted) return { ok: true }
92
+ const { profile, shared } = booted
93
+ if (!isIsolatedProfile(profile)) {
94
+ await profile.stop(shared)
95
+ return { ok: true }
96
+ }
97
+ // Instances of cases that never released are closed before the shared state goes away.
98
+ const failures = []
99
+ for (const [instanceId, { instance, caseName }] of instances) {
100
+ await profile.dispose(shared, instance, { workerId, instanceId, caseName }).catch(error => failures.push(error))
101
+ }
102
+ instances.clear()
103
+ await profile.shutdown?.(shared)
104
+ if (failures.length) throw failures[0]
105
+ return { ok: true }
106
+ }
107
+
108
+ const actions = {
109
+ warm: () => boot().then(() => ({ ok: true })),
110
+ prepare: ({ caseName }) => open(caseName),
111
+ reset: ({ caseName, instanceId }) => close(caseName, instanceId),
112
+ stop,
113
+ }
114
+
115
+ process.once('disconnect', () => process.exit(1))
116
+ // Commands carry an id, so several cases can share this worker and a late answer
117
+ // to a timed-out command is never taken for the answer to another one.
118
+ process.on('message', async ({ id, action, ...fields }) => {
119
+ let message
17
120
  try {
18
- if (action === 'prepare') {
19
- profile ??= defineAppProfile((await import(profileURL)).default)
20
- if (!app) {
21
- const startedAt = metricsFlag && performance.now()
22
- app = await profile.start(context)
23
- if (metricsFlag) bootstrapMs = performance.now() - startedAt
24
- }
25
- const url = new URL(app.url)
26
- if (!['http:', 'https:'].includes(url.protocol) || url.hostname !== '127.0.0.1') {
27
- throw new Error('Profile must expose an HTTP or HTTPS URL on 127.0.0.1')
28
- }
29
- await profile.prepare?.(app, { workerId, caseName })
30
- reply({ url: url.href, workerId })
31
- } else if (action === 'reset') {
32
- await profile.reset(app, { workerId, caseName })
33
- reply({ ok: true })
34
- } else if (action === 'stop') {
35
- if (app) await profile.stop(app)
36
- reply({ ok: true })
37
- }
121
+ message = await actions[action](fields)
38
122
  } catch (error) {
39
- reply({ error: String(error?.message ?? error).slice(0, 1024) })
123
+ message = { error: String(error?.message ?? error).slice(0, 1024) }
124
+ }
125
+ if (metricsFlag) {
126
+ message.metrics = { maxRssKiB: process.resourceUsage().maxRSS }
127
+ if (bootstrapMs !== undefined && !coldStartReported) {
128
+ coldStartReported = true
129
+ Object.assign(message.metrics, { processStartMs, importMs, bootstrapMs })
130
+ }
40
131
  }
132
+ process.send({ id, ...message })
41
133
  })