runwarm 0.0.0-stage → 0.1.0-alpha.1

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 ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0-alpha.1
4
+
5
+ - Type declarations for `defineAppProfile` and `withApp`.
6
+ - `funding` field pointing to GitHub Sponsors.
7
+ - The npm page now shows the npm install instructions and describes how the pool works without a Mermaid diagram.
8
+
9
+ ## 0.1.0-alpha.0
10
+
11
+ First pre-release.
12
+
13
+ - node-tap plugin (`runwarm/plugin`) with `t.withApp()` and the `app-profile`, `app-workers` and `app-metrics` options.
14
+ - Bounded pool of application workers with `start`, `prepare`, `reset` and `stop` profile hooks.
15
+ - Workers are discarded after a failed preparation or reset, a crash or a disconnected client.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paulo Fabene
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,133 @@
1
- # Temporary Holding Version
1
+ <h1 align="center">RunWarm</h1>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center"><strong>A node-tap plugin that keeps your application running between integration tests.</strong></p>
4
+
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>
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
+ <a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/github/license/fabenejr/runwarm"></a>
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://nodejs.org/"><img alt="Supported Node.js version" src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Ffabenejr%2Frunwarm%2Fmain%2Fpackage.json&amp;query=%24.engines.node&amp;label=Node.js&amp;logo=nodedotjs&amp;logoColor=white&amp;color=339933"></a>
13
+ <a href="https://tapjs.org/"><img alt="node-tap version used in tests" src="https://img.shields.io/github/package-json/dependency-version/fabenejr/runwarm/dev/tap?label=node-tap"></a>
14
+ <a href="examples/fastify/profile.js"><img alt="Fastify version used in the example" src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Ffabenejr%2Frunwarm%2Fmain%2Fpackage-lock.json&amp;query=%24%5B%27packages%27%5D%5B%27node_modules%2Ffastify%27%5D%5B%27version%27%5D&amp;label=Fastify%20example&amp;logo=fastify&amp;logoColor=white&amp;color=222222"></a>
15
+ <a href="examples/express/profile.js"><img alt="Express version used in the example" src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Ffabenejr%2Frunwarm%2Fmain%2Fpackage-lock.json&amp;query=%24%5B%27packages%27%5D%5B%27node_modules%2Fexpress%27%5D%5B%27version%27%5D&amp;label=Express%20example&amp;logo=express&amp;logoColor=white&amp;color=222222"></a>
16
+ <a href="examples/nestjs/profile.js"><img alt="NestJS version used in the example" src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Ffabenejr%2Frunwarm%2Fmain%2Fpackage-lock.json&amp;query=%24%5B%27packages%27%5D%5B%27node_modules%2F%40nestjs%2Fcore%27%5D%5B%27version%27%5D&amp;label=NestJS%20example&amp;logo=nestjs&amp;logoColor=white&amp;color=E0234E"></a>
17
+ <a href="examples/https/profile.js"><img alt="selfsigned version used for TLS test certificates" src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Ffabenejr%2Frunwarm%2Fmain%2Fpackage-lock.json&amp;query=%24%5B%27packages%27%5D%5B%27node_modules%2Fselfsigned%27%5D%5B%27version%27%5D&amp;label=selfsigned&amp;color=64748b"></a>
18
+ </p>
19
+
20
+ <p align="center">
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
+ </p>
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.
25
+
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
+ | :---: | :---: | :---: | :---: | :---: |
28
+ | **Node.js** | **node-tap** | **NestJS** | **Fastify** | **Express** |
29
+
30
+ ## Quick start
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.
33
+
34
+ ```sh
35
+ npm install --save-dev runwarm
36
+ npx tap plugin add runwarm/plugin
37
+ npx tap --disable-coverage --app-profile=profile.js
38
+ ```
39
+
40
+ On Windows, `tap plugin add` needs permission to create symlinks (developer mode or an elevated shell).
41
+
42
+ ## Write a test
43
+
44
+ ```js
45
+ import t from 'tap'
46
+
47
+ t.test('a new customer has no orders', t => t.withApp(async ({ url }) => {
48
+ const response = await fetch(new URL('/orders', url))
49
+ t.equal(response.status, 200)
50
+ t.same(await response.json(), [])
51
+ }))
52
+ ```
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`.
55
+
56
+ ## Options
57
+
58
+ Pass them on the command line or set them in `.taprc`.
59
+
60
+ | Option | Default | Purpose |
61
+ | --- | --- | --- |
62
+ | `app-profile` | none | Module whose default export is the application profile. The plugin stays idle without it |
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 |
65
+
66
+ ```yaml
67
+ app-profile: test/profile.js
68
+ app-workers: 4
69
+ disable-coverage: true
70
+ ```
71
+
72
+ `app-workers` limits running applications and tap's `--jobs` limits concurrent test files.
73
+
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.
75
+
76
+ ## Define an application profile
77
+
78
+ 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
+
80
+ | Hook | Responsibility |
81
+ | --- | --- |
82
+ | `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. |
83
+ | `prepare(app, { workerId, caseName })` | Optionally set up fixtures before the test receives the application. |
84
+ | `reset(app, { workerId, caseName })` | Drain outstanding work and restore the initial state, including after a test callback throws. |
85
+ | `stop(app)` | Close the server and release its resources during normal shutdown. |
86
+
87
+ 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
+
89
+ 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
+
91
+ ### How the pool works
92
+
93
+ 1. The tap runner loads the plugin, which starts the pool coordinator.
94
+ 2. Each test file reserves a worker from the coordinator over a local socket.
95
+ 3. The coordinator sends lifecycle commands to the application worker over IPC, and the worker runs your profile.
96
+ 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.
98
+
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.
100
+
101
+ ## Limitations
102
+
103
+ - Coverage and `--changed` do not follow the application process.
104
+ - Each run loads one profile.
105
+ - node-tap still runs every test file in its own process. RunWarm saves application startups, not test process startups.
106
+ - Interrupting the runner behaves as in plain node-tap, which can wait for the test timeout before exiting. If the runner is killed, workers exit without running `stop`.
107
+
108
+ ## Benchmarks
109
+
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.
111
+
112
+ ```sh
113
+ npm run --silent benchmark -- --framework fastify --bootstrap-ms 0
114
+ ```
115
+
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.
117
+
118
+ ## Status and roadmap
119
+
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.
121
+
122
+ - Publish benchmark results for the plugin.
123
+ - Measure a real CI suite with a database-backed profile and background jobs.
124
+ - Collect application coverage and track changed files for `tap --changed`.
125
+ - Evaluate multiple profiles per run.
126
+
127
+ ## Contributing
128
+
129
+ See the [contributing guide](CONTRIBUTING.md) for the development setup and commit conventions.
130
+
131
+ ## License
132
+
133
+ [MIT](LICENSE) © 2026 Paulo Fabene.
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "runwarm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "node-tap plugin that keeps HTTP applications warm between integration tests",
5
+ "keywords": [
6
+ "tapjs plugin",
7
+ "node-tap",
8
+ "tap",
9
+ "integration testing",
10
+ "warm pool"
11
+ ],
12
+ "packageManager": "npm@11.19.1",
13
+ "license": "MIT",
14
+ "author": "Paulo Fabene",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/fabenejr/runwarm.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/fabenejr/runwarm/issues"
21
+ },
22
+ "homepage": "https://github.com/fabenejr/runwarm#readme",
23
+ "funding": "https://github.com/sponsors/fabenejr",
24
+ "files": [
25
+ "src",
26
+ "CHANGELOG.md"
27
+ ],
28
+ "type": "module",
29
+ "engines": {
30
+ "node": ">=22.12.0"
31
+ },
32
+ "exports": {
33
+ ".": {
34
+ "types": "./src/client.d.ts",
35
+ "default": "./src/client.js"
36
+ },
37
+ "./plugin": {
38
+ "types": "./src/tap-plugin.d.ts",
39
+ "default": "./src/tap-plugin.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "scripts": {
47
+ "test": "node --test test/acceptance.test.js",
48
+ "benchmark": "node benchmark/run.js"
49
+ },
50
+ "peerDependencies": {
51
+ "tap": "^21.8.1"
52
+ },
53
+ "devDependencies": {
54
+ "@nestjs/common": "11.2.12",
55
+ "@nestjs/core": "11.2.12",
56
+ "@nestjs/platform-express": "11.2.12",
57
+ "express": "5.3.0",
58
+ "fastify": "^5.6.0",
59
+ "reflect-metadata": "0.2.2",
60
+ "rxjs": "7.8.2",
61
+ "selfsigned": "^5.5.0",
62
+ "tap": "21.8.1"
63
+ },
64
+ "overrides": {
65
+ "tar@<8.0.2": "8.1.2",
66
+ "glob@<14.0.6": "14.0.7",
67
+ "minimatch@<11.0.8": "11.0.10"
68
+ }
69
+ }
@@ -0,0 +1,21 @@
1
+ export interface HookContext {
2
+ workerId: string
3
+ }
4
+
5
+ export interface CaseContext extends HookContext {
6
+ caseName: string
7
+ }
8
+
9
+ export interface AppProfile<App extends { url: string }> {
10
+ start(context: HookContext): App | Promise<App>
11
+ prepare?(app: App, context: CaseContext): unknown
12
+ reset(app: App, context: CaseContext): unknown
13
+ stop(app: App): unknown
14
+ }
15
+
16
+ export declare function defineAppProfile<App extends { url: string }>(profile: AppProfile<App>): AppProfile<App>
17
+
18
+ export declare function withApp<T>(
19
+ caseName: string,
20
+ run: (app: { url: string; workerId: string }) => T | Promise<T>,
21
+ ): Promise<T>
package/src/client.js ADDED
@@ -0,0 +1,45 @@
1
+ import { connect } from 'node:net'
2
+ import { once } from 'node:events'
3
+ import { messages, receive, send } from './protocol.js'
4
+
5
+ export function defineAppProfile(profile) {
6
+ for (const hook of ['start', 'reset', 'stop']) {
7
+ if (typeof profile?.[hook] !== 'function') throw new TypeError('Missing profile hook: ' + hook)
8
+ }
9
+ return profile
10
+ }
11
+
12
+ export async function withApp(caseName, run) {
13
+ const path = process.env.RUNWARM_SOCKET
14
+ const token = process.env.RUNWARM_TOKEN
15
+ if (!path || !token) {
16
+ throw new Error('RunWarm is not running. Add the runwarm/plugin tap plugin and set app-profile')
17
+ }
18
+ const socket = connect(path)
19
+ try {
20
+ await once(socket, 'connect')
21
+ const stream = messages(socket)
22
+ send(socket, { token, caseName })
23
+ const { url, workerId } = await receive(stream)
24
+ let result
25
+ let callbackFailed = false
26
+ let callbackError
27
+ try {
28
+ result = await run({ url, workerId })
29
+ } catch (error) {
30
+ callbackFailed = true
31
+ callbackError = error
32
+ }
33
+ try {
34
+ send(socket, { release: true })
35
+ await receive(stream)
36
+ } catch (error) {
37
+ if (callbackFailed) throw new AggregateError([callbackError, error], 'Test and cleanup failed')
38
+ throw error
39
+ }
40
+ if (callbackFailed) throw callbackError
41
+ return result
42
+ } finally {
43
+ socket.destroy()
44
+ }
45
+ }
@@ -0,0 +1,75 @@
1
+ import { createServer } from 'node:net'
2
+ import { once } from 'node:events'
3
+ import { Pool } from './pool.js'
4
+ import { messages, receive, send } from './protocol.js'
5
+
6
+ export async function startCoordinator(profileURL, size, metrics, { path, token }) {
7
+ const pool = new Pool(profileURL, size, metrics)
8
+ const sessions = new Set()
9
+ const sockets = new Set()
10
+
11
+ async function serve(socket) {
12
+ const controller = new AbortController()
13
+ const cancel = () => controller.abort(new Error('Test disconnected'))
14
+ socket.once('close', cancel)
15
+ socket.once('end', cancel)
16
+ socket.on('error', cancel)
17
+ const stream = messages(socket)
18
+ let slot
19
+ try {
20
+ socket.setTimeout(5000, () => socket.destroy())
21
+ const hello = await receive(stream)
22
+ if (hello.token !== token) throw new Error('Invalid session')
23
+ if (typeof hello.caseName !== 'string' || hello.caseName.length > 1024) {
24
+ throw new Error('Invalid test case name')
25
+ }
26
+ socket.setTimeout(0)
27
+ const queuedAt = metrics && performance.now()
28
+ slot = await pool.acquire(controller.signal)
29
+ metrics?.record('queueWait', performance.now() - queuedAt)
30
+ 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()
37
+ try {
38
+ await slot.worker.command('reset', hello.caseName)
39
+ } finally {
40
+ metrics?.record('reset', performance.now() - resetAt)
41
+ }
42
+ send(socket, { ok: true })
43
+ } catch (error) {
44
+ if (slot?.worker) {
45
+ await slot.worker.discard()
46
+ slot.worker = null
47
+ }
48
+ if (!socket.destroyed && socket.writable) send(socket, { error: error.message })
49
+ } finally {
50
+ if (slot) pool.release(slot)
51
+ socket.end()
52
+ }
53
+ }
54
+
55
+ const server = createServer(socket => {
56
+ sockets.add(socket)
57
+ socket.once('close', () => sockets.delete(socket))
58
+ const session = serve(socket)
59
+ sessions.add(session)
60
+ session.finally(() => sessions.delete(session))
61
+ })
62
+ // listen() runs before the first await, so the caller can hand the path to test
63
+ // processes without waiting for this function to resolve.
64
+ server.listen(path)
65
+ await once(server, 'listening')
66
+ return {
67
+ async close() {
68
+ const closed = new Promise(resolve => server.close(resolve))
69
+ for (const socket of sockets) socket.destroy()
70
+ await Promise.allSettled(sessions)
71
+ await pool.close()
72
+ await closed
73
+ },
74
+ }
75
+ }
package/src/metrics.js ADDED
@@ -0,0 +1,31 @@
1
+ export function createRunMetrics() {
2
+ const startedAt = performance.now()
3
+ const totals = {
4
+ workersStarted: 0,
5
+ 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 },
9
+ }
10
+
11
+ function record(stage, durationMs) {
12
+ const timing = totals[stage]
13
+ timing.count++
14
+ timing.totalMs += durationMs
15
+ timing.maxMs = Math.max(timing.maxMs, durationMs)
16
+ }
17
+
18
+ return {
19
+ workerStarted() {
20
+ totals.workersStarted++
21
+ },
22
+ record,
23
+ observeWorker({ bootstrapMs, maxRssKiB }) {
24
+ if (bootstrapMs !== undefined) record('bootstrap', bootstrapMs)
25
+ totals.maxAppProcessRssKiB = Math.max(totals.maxAppProcessRssKiB, maxRssKiB)
26
+ },
27
+ report() {
28
+ return { version: 1, durationMs: performance.now() - startedAt, ...totals }
29
+ },
30
+ }
31
+ }
package/src/pool.js ADDED
@@ -0,0 +1,107 @@
1
+ import { fork } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+
4
+ function startWorker(profileURL, metrics) {
5
+ const workerId = randomUUID()
6
+ const args = [profileURL, workerId]
7
+ if (metrics) args.push('--metrics')
8
+ const child = fork(new URL('./worker.js', import.meta.url), args, {
9
+ stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
10
+ execArgv: [],
11
+ })
12
+ if (metrics) child.once('spawn', () => metrics.workerStarted())
13
+ let dead = false
14
+ 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
+
18
+ function command(action, caseName) {
19
+ if (dead || !child.connected) return Promise.reject(new Error('Worker unavailable'))
20
+ return new Promise((resolve, reject) => {
21
+ function finish(error, value) {
22
+ clearTimeout(timer)
23
+ child.off('message', onMessage)
24
+ child.off('exit', onExit)
25
+ child.off('error', onError)
26
+ if (error) reject(error)
27
+ else resolve(value)
28
+ }
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) })
40
+ })
41
+ }
42
+
43
+ async function discard() {
44
+ if (!dead) child.kill('SIGKILL')
45
+ await closed
46
+ }
47
+
48
+ return { command, discard, get alive() { return child.connected && !dead } }
49
+ }
50
+
51
+ export class Pool {
52
+ constructor(profileURL, size, metrics) {
53
+ this.profileURL = profileURL
54
+ this.metrics = metrics
55
+ this.slots = Array.from({ length: size }, () => ({ busy: false, worker: null }))
56
+ this.waiters = []
57
+ this.closing = false
58
+ }
59
+
60
+ async acquire(signal) {
61
+ signal.throwIfAborted()
62
+ 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
+ }
68
+ return new Promise((resolve, reject) => {
69
+ const waiter = { resolve, reject }
70
+ const abort = () => {
71
+ this.waiters = this.waiters.filter(item => item !== waiter)
72
+ reject(signal.reason)
73
+ }
74
+ signal.addEventListener('abort', abort, { once: true })
75
+ waiter.detach = () => signal.removeEventListener('abort', abort)
76
+ this.waiters.push(waiter)
77
+ })
78
+ }
79
+
80
+ async prepare(slot, caseName) {
81
+ if (!slot.worker?.alive) slot.worker = startWorker(this.profileURL, this.metrics)
82
+ return slot.worker.command('prepare', caseName)
83
+ }
84
+
85
+ release(slot) {
86
+ const waiter = this.waiters.shift()
87
+ if (!waiter) { slot.busy = false; return }
88
+ waiter.detach()
89
+ waiter.resolve(slot)
90
+ }
91
+
92
+ async close() {
93
+ this.closing = true
94
+ for (const waiter of this.waiters.splice(0)) {
95
+ waiter.detach()
96
+ waiter.reject(new Error('Pool is closing'))
97
+ }
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
+ }))
106
+ }
107
+ }
@@ -0,0 +1,28 @@
1
+ import { Buffer } from 'node:buffer'
2
+
3
+ export function send(socket, message) {
4
+ socket.write(JSON.stringify(message) + '\n')
5
+ }
6
+
7
+ // Control messages contain only short identifiers, status and a loopback URL.
8
+ export async function* messages(socket) {
9
+ let pending = ''
10
+ socket.setEncoding('utf8')
11
+ for await (const chunk of socket) {
12
+ pending += chunk
13
+ if (Buffer.byteLength(pending) > 8192) throw new Error('Control message too large')
14
+ let end
15
+ while ((end = pending.indexOf('\n')) >= 0) {
16
+ const line = pending.slice(0, end)
17
+ pending = pending.slice(end + 1)
18
+ yield JSON.parse(line)
19
+ }
20
+ }
21
+ }
22
+
23
+ export async function receive(stream) {
24
+ const { value, done } = await stream.next()
25
+ if (done) throw new Error('Pool connection closed')
26
+ if (value.error) throw new Error(value.error)
27
+ return value
28
+ }
@@ -0,0 +1,11 @@
1
+ export declare const config: {
2
+ 'app-profile': { type: 'string'; description: string }
3
+ 'app-workers': { type: 'number'; default: number; description: string }
4
+ 'app-metrics': { type: 'boolean'; description: string }
5
+ }
6
+
7
+ export interface RunWarm {
8
+ withApp<T>(run: (app: { url: string; workerId: string }) => T | Promise<T>): Promise<T>
9
+ }
10
+
11
+ export declare const plugin: (t: any, opts?: {}) => RunWarm
@@ -0,0 +1,69 @@
1
+ // node-tap plugin. The tap runner hosts the application pool and
2
+ // test files reach it through t.withApp().
3
+ import { randomBytes } from 'node:crypto'
4
+ import { mkdtempSync, rmSync, statSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { join, resolve } from 'node:path'
7
+ import { pathToFileURL } from 'node:url'
8
+ import { withApp } from './client.js'
9
+ import { startCoordinator } from './coordinator.js'
10
+ import { createRunMetrics } from './metrics.js'
11
+
12
+ export const config = {
13
+ 'app-profile': {
14
+ type: 'string',
15
+ description: 'Module whose default export is a RunWarm application profile',
16
+ },
17
+ 'app-workers': {
18
+ type: 'number',
19
+ default: 1,
20
+ description: 'Maximum number of warm application workers',
21
+ },
22
+ 'app-metrics': {
23
+ type: 'boolean',
24
+ description: 'Print pool metrics to stderr when the run ends',
25
+ },
26
+ }
27
+
28
+ function host(t) {
29
+ const profile = process.env.TAP_APP_PROFILE
30
+ if (!profile) return
31
+ const size = Number(process.env.TAP_APP_WORKERS || 1)
32
+ if (!Number.isSafeInteger(size) || size < 1) throw new Error('app-workers must be a positive integer')
33
+ const file = resolve(profile)
34
+ if (!statSync(file, { throwIfNoEntry: false })?.isFile()) {
35
+ throw new Error('app-profile not found: ' + file)
36
+ }
37
+ const metrics = process.env.TAP_APP_METRICS === '1' ? createRunMetrics() : undefined
38
+
39
+ // Plugins load synchronously and the runner copies process.env right after,
40
+ // so the address and token are chosen here instead of read back from listen().
41
+ const dir = process.platform === 'win32' ? undefined : mkdtempSync(join(tmpdir(), 'runwarm-'))
42
+ const path = dir ? join(dir, 'pool.sock') : '\\\\.\\pipe\\runwarm-' + randomBytes(16).toString('hex')
43
+ const token = randomBytes(32).toString('hex')
44
+ process.env.RUNWARM_SOCKET = path
45
+ process.env.RUNWARM_TOKEN = token
46
+
47
+ const pool = startCoordinator(pathToFileURL(file).href, size, metrics, { path, token })
48
+ // Reported from the teardown below.
49
+ pool.catch(() => {})
50
+
51
+ // The teardown plugin may not be applied yet while this plugin is loading.
52
+ queueMicrotask(() => t.t.teardown(async () => {
53
+ try {
54
+ await (await pool).close()
55
+ } finally {
56
+ if (dir) rmSync(dir, { recursive: true, force: true })
57
+ if (metrics) process.stderr.write('runwarm metrics: ' + JSON.stringify(metrics.report()) + '\n')
58
+ }
59
+ }))
60
+ }
61
+
62
+ export function plugin(t, opts) {
63
+ if (opts?.context === Symbol.for('tap.isRunner')) host(t)
64
+ return {
65
+ withApp(run) {
66
+ return withApp(t.t.name, run)
67
+ },
68
+ }
69
+ }
package/src/worker.js ADDED
@@ -0,0 +1,41 @@
1
+ import { defineAppProfile } from './client.js'
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
6
+ const context = { workerId }
7
+ let app
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)
15
+ }
16
+
17
+ 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
+ }
38
+ } catch (error) {
39
+ reply({ error: String(error?.message ?? error).slice(0, 1024) })
40
+ }
41
+ })