runwarm 0.2.0 → 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 +15 -0
- package/README.md +109 -24
- package/package.json +1 -1
- package/src/client.d.ts +21 -0
- package/src/client.js +19 -2
- package/src/coordinator.js +56 -14
- package/src/metrics.js +34 -9
- package/src/pool.js +136 -40
- package/src/tap-plugin.d.ts +3 -0
- package/src/tap-plugin.js +40 -5
- package/src/worker.js +124 -32
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
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
|
+
|
|
3
18
|
## 0.2.0
|
|
4
19
|
|
|
5
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.
|
package/README.md
CHANGED
|
@@ -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
|
| :---: | :---: | :---: | :---: | :---: |
|
|
@@ -61,7 +61,10 @@ 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` |
|
|
65
68
|
| `app-timeout` | `30` | Seconds each profile hook may take, including `start`. A worker that runs over is discarded |
|
|
66
69
|
|
|
67
70
|
```yaml
|
|
@@ -70,9 +73,9 @@ app-workers: 4
|
|
|
70
73
|
disable-coverage: true
|
|
71
74
|
```
|
|
72
75
|
|
|
73
|
-
`app-workers` limits running
|
|
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.
|
|
74
77
|
|
|
75
|
-
The metrics report includes total duration, workers started,
|
|
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.
|
|
76
79
|
|
|
77
80
|
## Define an application profile
|
|
78
81
|
|
|
@@ -89,6 +92,50 @@ The application runs in a plain Node.js process, without the loaders tap adds to
|
|
|
89
92
|
|
|
90
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.
|
|
91
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
|
+
|
|
92
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`.
|
|
93
140
|
|
|
94
141
|
### How the pool works
|
|
@@ -97,9 +144,15 @@ The HTTPS example reads PEM files from `EXAMPLE_TLS_CERT` and `EXAMPLE_TLS_KEY`.
|
|
|
97
144
|
2. Each test file reserves a worker from the coordinator over a local socket.
|
|
98
145
|
3. The coordinator sends lifecycle commands to the application worker over IPC, and the worker runs your profile.
|
|
99
146
|
4. The test sends HTTP or HTTPS requests straight to the application.
|
|
100
|
-
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.
|
|
101
150
|
|
|
102
|
-
|
|
151
|
+
## Troubleshooting
|
|
152
|
+
|
|
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.
|
|
103
156
|
|
|
104
157
|
## Limitations
|
|
105
158
|
|
|
@@ -110,59 +163,91 @@ The runner listens on a Unix socket in a private temporary directory, or on a na
|
|
|
110
163
|
|
|
111
164
|
## Benchmarks
|
|
112
165
|
|
|
113
|
-
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.
|
|
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.
|
|
114
196
|
|
|
115
197
|
### 1,000 HTTP test files
|
|
116
198
|
|
|
117
|
-
The largest run has 1,000 tap files with one HTTP case each, 8 tap jobs and 8 pool workers. Without
|
|
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.
|
|
118
200
|
|
|
119
201
|
<p align="center">
|
|
120
|
-
<img alt="Wall time for 1,000 HTTP test files on Linux. Fastify:
|
|
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">
|
|
121
203
|
</p>
|
|
122
204
|
|
|
123
205
|
<p align="center">
|
|
124
|
-
<img alt="CPU time for 1,000 HTTP test files on Linux. Fastify: 1,
|
|
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">
|
|
125
207
|
</p>
|
|
126
208
|
|
|
127
209
|
| 1,000 files on Linux | App startups | Wall time | CPU time | Peak memory |
|
|
128
210
|
| --- | ---: | ---: | ---: | ---: |
|
|
129
|
-
| NestJS 11.2.12 | 1,000 → **
|
|
130
|
-
|
|
|
131
|
-
|
|
|
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 |
|
|
132
217
|
|
|
133
|
-
CPU time is the user and system time of the whole process tree, and peak memory is its proportional set size (PSS).
|
|
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.
|
|
134
219
|
|
|
135
220
|
### Smaller suites on Linux, Windows and macOS
|
|
136
221
|
|
|
137
222
|
<p align="center">
|
|
138
|
-
<img alt="Wall time for 120 HTTP test cases on Linux. Fastify:
|
|
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">
|
|
139
224
|
</p>
|
|
140
225
|
|
|
141
226
|
<p align="center">
|
|
142
|
-
<img alt="Wall time for 24 HTTP test cases on Windows. Fastify:
|
|
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">
|
|
143
228
|
</p>
|
|
144
229
|
|
|
145
230
|
<p align="center">
|
|
146
|
-
<img alt="Wall time for 24 HTTP test cases on macOS. Fastify:
|
|
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">
|
|
147
232
|
</p>
|
|
148
233
|
|
|
149
|
-
|
|
|
234
|
+
| New app per file → pool / instances | Linux, 120 cases | Windows, 24 cases | macOS, 24 cases |
|
|
150
235
|
| --- | ---: | ---: | ---: |
|
|
151
|
-
| NestJS 11.2.12 |
|
|
152
|
-
| Fastify 5.12.8 | 13.
|
|
153
|
-
| Express 5.3.0 | 13.
|
|
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%) |
|
|
154
239
|
|
|
155
|
-
These runs use 2 tap jobs and 2
|
|
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.
|
|
156
241
|
|
|
157
242
|
### Run it yourself
|
|
158
243
|
|
|
159
|
-
|
|
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.
|
|
160
245
|
|
|
161
246
|
```sh
|
|
162
247
|
npm run --silent benchmark -- --framework fastify --bootstrap-ms 0
|
|
163
248
|
```
|
|
164
249
|
|
|
165
|
-
`--framework` accepts `fastify`, `express` and `nestjs`. `--resources` adds CPU and memory sampling on Linux with procps, GNU `time` and GNU `timeout`. `node benchmark/chart.js` draws the charts from the result files.
|
|
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.
|
|
166
251
|
|
|
167
252
|
## Status and roadmap
|
|
168
253
|
|
package/package.json
CHANGED
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
|
-
|
|
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
|
-
|
|
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 {
|
package/src/coordinator.js
CHANGED
|
@@ -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, timeoutMs }) {
|
|
7
|
-
const pool = new Pool(profileURL, size, metrics, timeoutMs)
|
|
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,6 +28,26 @@ 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)
|
|
@@ -23,28 +55,36 @@ export async function startCoordinator(profileURL, size, metrics, { path, token,
|
|
|
23
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
|
|
32
|
-
|
|
33
|
-
|
|
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
|
|
68
|
+
app = await pool.openCase(slot, caseName)
|
|
39
69
|
} finally {
|
|
40
|
-
metrics?.record('
|
|
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
|
-
//
|
|
46
|
-
|
|
47
|
-
|
|
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)
|
|
48
88
|
}
|
|
49
89
|
if (!socket.destroyed && socket.writable) send(socket, { error: error.message })
|
|
50
90
|
} finally {
|
|
@@ -64,6 +104,8 @@ export async function startCoordinator(profileURL, size, metrics, { path, token,
|
|
|
64
104
|
// processes without waiting for this function to resolve.
|
|
65
105
|
server.listen(path)
|
|
66
106
|
await once(server, 'listening')
|
|
107
|
+
// Starts applications in the background while tap loads the test files.
|
|
108
|
+
if (prewarm > 0) pool.warm(prewarm)
|
|
67
109
|
return {
|
|
68
110
|
async close() {
|
|
69
111
|
const closed = new Promise(resolve => server.close(resolve))
|
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
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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)
|
|
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
|
@@ -6,12 +6,13 @@ function workerEnv() {
|
|
|
6
6
|
const env = { ...process.env }
|
|
7
7
|
delete env.RUNWARM_SOCKET
|
|
8
8
|
delete env.RUNWARM_TOKEN
|
|
9
|
+
delete env.RUNWARM_IDLE
|
|
9
10
|
return env
|
|
10
11
|
}
|
|
11
12
|
|
|
12
|
-
function startWorker(profileURL, metrics, timeoutMs) {
|
|
13
|
+
function startWorker(profileURL, capacity, metrics, timeoutMs) {
|
|
13
14
|
const workerId = randomUUID()
|
|
14
|
-
const args = [profileURL, workerId]
|
|
15
|
+
const args = [profileURL, workerId, String(capacity)]
|
|
15
16
|
if (metrics) args.push('--metrics')
|
|
16
17
|
const child = fork(new URL('./worker.js', import.meta.url), args, {
|
|
17
18
|
stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
|
|
@@ -20,37 +21,43 @@ function startWorker(profileURL, metrics, timeoutMs) {
|
|
|
20
21
|
})
|
|
21
22
|
if (metrics) child.once('spawn', () => metrics.workerStarted())
|
|
22
23
|
let dead = false
|
|
23
|
-
// Set when a command times out: the worker may
|
|
24
|
-
|
|
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()
|
|
25
29
|
const closed = new Promise(resolve => child.once('close', () => { dead = true; resolve() }))
|
|
26
|
-
// Async fork failures are also reported to any pending command.
|
|
27
|
-
child.on('error', () => {})
|
|
28
30
|
|
|
29
|
-
function
|
|
30
|
-
|
|
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) {
|
|
46
|
+
if (dead || !child.connected) return Promise.reject(new Error('Worker unavailable'))
|
|
31
47
|
return new Promise((resolve, reject) => {
|
|
48
|
+
const id = ++nextId
|
|
32
49
|
function finish(error, value) {
|
|
33
50
|
clearTimeout(timer)
|
|
34
|
-
|
|
35
|
-
child.off('exit', onExit)
|
|
36
|
-
child.off('error', onError)
|
|
51
|
+
pending.delete(id)
|
|
37
52
|
if (error) reject(error)
|
|
38
53
|
else resolve(value)
|
|
39
54
|
}
|
|
40
|
-
const onMessage = ({ metrics: sample, ...message }) => {
|
|
41
|
-
if (sample) metrics?.observeWorker(sample)
|
|
42
|
-
finish(message.error ? new Error(message.error) : null, message)
|
|
43
|
-
}
|
|
44
|
-
const onExit = () => finish(new Error('Worker exited during ' + action))
|
|
45
|
-
const onError = error => finish(error)
|
|
46
55
|
const timer = setTimeout(() => {
|
|
47
|
-
|
|
56
|
+
timedOut = true
|
|
48
57
|
finish(new Error('Worker timeout during ' + action))
|
|
49
58
|
}, timeoutMs)
|
|
50
|
-
|
|
51
|
-
child.
|
|
52
|
-
child.once('error', onError)
|
|
53
|
-
child.send({ action, caseName }, error => { if (error) finish(error) })
|
|
59
|
+
pending.set(id, { action, finish })
|
|
60
|
+
child.send({ id, action, ...fields }, error => { if (error) finish(error) })
|
|
54
61
|
})
|
|
55
62
|
}
|
|
56
63
|
|
|
@@ -58,7 +65,7 @@ function startWorker(profileURL, metrics, timeoutMs) {
|
|
|
58
65
|
// stop is reported after the process is gone.
|
|
59
66
|
async function retire() {
|
|
60
67
|
let failure
|
|
61
|
-
if (!dead && !
|
|
68
|
+
if (!dead && !timedOut && child.connected) {
|
|
62
69
|
try {
|
|
63
70
|
await command('stop')
|
|
64
71
|
} catch (error) {
|
|
@@ -70,27 +77,62 @@ function startWorker(profileURL, metrics, timeoutMs) {
|
|
|
70
77
|
if (failure) throw failure
|
|
71
78
|
}
|
|
72
79
|
|
|
73
|
-
return { command, retire, get alive() { return child.connected && !dead && !
|
|
80
|
+
return { command, retire, get alive() { return child.connected && !dead && !timedOut } }
|
|
74
81
|
}
|
|
75
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.
|
|
76
86
|
export class Pool {
|
|
77
|
-
constructor(profileURL, size, metrics, timeoutMs) {
|
|
87
|
+
constructor(profileURL, size, metrics, timeoutMs, capacity = 1) {
|
|
78
88
|
this.profileURL = profileURL
|
|
79
89
|
this.metrics = metrics
|
|
80
90
|
this.timeoutMs = timeoutMs
|
|
81
|
-
this.
|
|
91
|
+
this.capacity = capacity
|
|
92
|
+
this.entries = Array.from({ length: size }, () => ({ worker: null, active: 0, draining: false, retiring: null }))
|
|
82
93
|
this.waiters = []
|
|
94
|
+
this.background = new Set()
|
|
83
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
|
|
84
129
|
}
|
|
85
130
|
|
|
86
131
|
async acquire(signal) {
|
|
87
132
|
signal.throwIfAborted()
|
|
88
133
|
if (this.closing) throw new Error('Pool is closing')
|
|
89
|
-
const
|
|
90
|
-
if (
|
|
91
|
-
slot.busy = true
|
|
92
|
-
return slot
|
|
93
|
-
}
|
|
134
|
+
const entry = this.pick()
|
|
135
|
+
if (entry) return this.lease(entry)
|
|
94
136
|
return new Promise((resolve, reject) => {
|
|
95
137
|
const waiter = { resolve, reject }
|
|
96
138
|
const abort = () => {
|
|
@@ -103,16 +145,68 @@ export class Pool {
|
|
|
103
145
|
})
|
|
104
146
|
}
|
|
105
147
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
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)
|
|
109
205
|
}
|
|
110
206
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
waiter.detach()
|
|
115
|
-
waiter.resolve(slot)
|
|
207
|
+
track(promise) {
|
|
208
|
+
this.background.add(promise)
|
|
209
|
+
promise.finally(() => this.background.delete(promise))
|
|
116
210
|
}
|
|
117
211
|
|
|
118
212
|
async close() {
|
|
@@ -121,8 +215,10 @@ export class Pool {
|
|
|
121
215
|
waiter.detach()
|
|
122
216
|
waiter.reject(new Error('Pool is closing'))
|
|
123
217
|
}
|
|
218
|
+
// Warm-up commands and background stops are bounded by the hook timeout.
|
|
219
|
+
while (this.background.size) await Promise.allSettled(this.background)
|
|
124
220
|
// Every worker is retired even when another one fails to stop.
|
|
125
|
-
const results = await Promise.allSettled(this.
|
|
221
|
+
const results = await Promise.allSettled(this.entries.map(entry => entry.worker?.retire()))
|
|
126
222
|
const errors = results.filter(result => result.status === 'rejected').map(result => result.reason)
|
|
127
223
|
if (errors.length === 1) throw errors[0]
|
|
128
224
|
if (errors.length > 1) throw new AggregateError(errors, 'Workers failed to stop')
|
package/src/tap-plugin.d.ts
CHANGED
|
@@ -2,6 +2,9 @@ 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 }
|
|
5
8
|
'app-timeout': { type: 'number'; default: number; description: string }
|
|
6
9
|
}
|
|
7
10
|
|
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,6 +23,20 @@ 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
|
+
},
|
|
26
40
|
'app-timeout': {
|
|
27
41
|
type: 'number',
|
|
28
42
|
default: 30,
|
|
@@ -32,7 +46,11 @@ export const config = {
|
|
|
32
46
|
|
|
33
47
|
function host(t) {
|
|
34
48
|
const profile = process.env.TAP_APP_PROFILE
|
|
35
|
-
if (!profile)
|
|
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
|
+
}
|
|
36
54
|
const size = Number(process.env.TAP_APP_WORKERS || 1)
|
|
37
55
|
if (!Number.isSafeInteger(size) || size < 1) throw new Error('app-workers must be a positive integer')
|
|
38
56
|
const timeoutMs = Number(process.env.TAP_APP_TIMEOUT || 30) * 1000
|
|
@@ -44,7 +62,13 @@ function host(t) {
|
|
|
44
62
|
if (!statSync(file, { throwIfNoEntry: false })?.isFile()) {
|
|
45
63
|
throw new Error('app-profile not found: ' + file)
|
|
46
64
|
}
|
|
47
|
-
const
|
|
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
|
|
48
72
|
|
|
49
73
|
// Plugins load synchronously and the runner copies process.env right after,
|
|
50
74
|
// so the address and token are chosen here instead of read back from listen().
|
|
@@ -54,7 +78,7 @@ function host(t) {
|
|
|
54
78
|
process.env.RUNWARM_SOCKET = path
|
|
55
79
|
process.env.RUNWARM_TOKEN = token
|
|
56
80
|
|
|
57
|
-
const pool = startCoordinator(pathToFileURL(file).href, size, metrics, { path, token, timeoutMs })
|
|
81
|
+
const pool = startCoordinator(pathToFileURL(file).href, size, metrics, { path, token, timeoutMs, prewarm, instances })
|
|
58
82
|
// Reported from the teardown below.
|
|
59
83
|
pool.catch(() => {})
|
|
60
84
|
|
|
@@ -64,7 +88,18 @@ function host(t) {
|
|
|
64
88
|
await (await pool).close()
|
|
65
89
|
} finally {
|
|
66
90
|
if (dir) rmSync(dir, { recursive: true, force: true })
|
|
67
|
-
if (metrics)
|
|
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
|
+
}
|
|
68
103
|
}
|
|
69
104
|
}))
|
|
70
105
|
}
|
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
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
})
|