Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test(e2e): put each suite's server on a loopback port

Yudhi Armyndharis9c422ff2d04f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a0103e4ee..dcaf0117b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Settled outbound delivery records are pruned after `WEBHOOK_OUTBOX_RETENTION_DAYS` (default 7). A record that can still be replayed is never pruned on age, and a non-positive window falls back to the default rather than letting the table grow without bound.
- `PLUGIN_STATE_DIR` moves the plugin registry and per-plugin storage off the default `./data`. It was the one piece of state with no path knob, so a test run rewrote the developer's own registry and every suite in that run inherited whatever the previous one left in it.
- The e2e lane sweeps the throwaway state roots it creates. Each suite gets its own, nothing removed them, and the temp directory accumulated hundreds of entries over a few days of runs.
+- e2e assertions are no longer answered by unrelated processes on the host. supertest starts a listener per request on the wildcard address and then dials 127.0.0.1, and macOS both permits that bind over a port another process holds on 127.0.0.1 specifically and routes the connection to the more specific holder, so a run could assert against a status the app has no route for. Each suite's server now listens on loopback while it initialises, which supertest reuses instead of opening one, taking the lane from 230 listeners a run to 27.
### Tests
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.md
index 8e761e5a8..c5753ae29 100644
--- a/docs/09-testing-strategy.md
+++ b/docs/09-testing-strategy.md
@@ -126,9 +126,10 @@ E2E smoke tests live in `test/` and use `test/jest-e2e.json`.
> **They run one at a time (`maxWorkers: 1`), and that is a correctness requirement, not a
> performance preference.** Each suite boots a real application, and not every piece of application
-> state is redirected to a per-worker location. `dataDir` is a hard-coded `./data` with no
-> environment lever, so every worker's plugin loader read-modify-writes the same
-> `data/plugins/registry.json`. Measured on a single parallel run: 52 writes from 12 processes, 30
+> state is redirected to a per-worker location. The plugin registry once had no environment
+> lever, so every worker's plugin loader read-modify-wrote the same
+> `data/plugins/registry.json`. `PLUGIN_STATE_DIR` now redirects it and each suite takes its own state
+> roots, so that particular collision is closed. Measured on a single parallel run: 52 writes from 12 processes, 30
> of them within 500ms of a write by a different process. Individual writes are atomic; the
> read-modify-write cycle is not.
>
@@ -137,7 +138,15 @@ E2E smoke tests live in `test/` and use `test/jest-e2e.json`.
> reproduced when a suite ran on its own, which is what made it look like flakiness. Serially it
> does not occur.
>
-> Adding a suite is safe. Restoring parallelism is not, until each worker gets its own data root.
+> Adding a suite is safe. Restoring parallelism has not been retried since those roots landed, so it
+> is untested rather than known-safe.
+>
+> A second requirement has nothing to do with parallelism: each suite's server is put on a **loopback**
+> port while it initialises (`test/setup-e2e.ts`). Left alone, supertest starts a listener per request
+> on the wildcard address and then dials 127.0.0.1, and macOS both permits that bind over a port
+> another process holds on 127.0.0.1 specifically and routes the connection to the more specific
+> holder. An assertion then reads a status from an unrelated program on the host, which is why the lane
+> could fail on a status no route can return. `setup-e2e-env.e2e-spec.ts` holds that contract.
```text
test/
diff --git a/test/setup-e2e-env.e2e-spec.ts b/test/setup-e2e-env.e2e-spec.ts
index 8110ee252..cc34112ec 100644
--- a/test/setup-e2e-env.e2e-spec.ts
+++ b/test/setup-e2e-env.e2e-spec.ts
@@ -6,9 +6,111 @@
* trivially; its regression value is in a shared-worker run after queue-on (or with a dirty
* ambient env), where a missing reset shows up as REDIS_ENABLED !== 'false' here.
*/
+import { Controller, Get, INestApplication, Module } from '@nestjs/common';
+import { NestFactory } from '@nestjs/core';
+import { Test } from '@nestjs/testing';
+import { Server } from 'http';
+import { AddressInfo } from 'net';
+import request from 'supertest';
+
describe('e2e boot environment', () => {
it('boots with queue and Redis disabled', () => {
expect(process.env.QUEUE_ENABLED).toBe('false');
expect(process.env.REDIS_ENABLED).toBe('false');
});
});
+
+@Controller()
+class PingController {
+ @Get('/__bind-probe')
+ probe(): { servedBy: string } {
+ return { servedBy: 'the app under test' };
+ }
+}
+
+/** A standalone app for the `listen()` handover, which needs a real NestFactory app rather than a fixture. */
+@Module({})
+class BareModule {}
+
+/**
+ * The listening contract setup-e2e.ts enforces, and the reason it exists.
+ *
+ * supertest starts a server per request with `listen(0)` and no host, which binds the wildcard
+ * address, and then dials 127.0.0.1 regardless of what it bound. macOS hands a wildcard listener an
+ * ephemeral port another process already holds on 127.0.0.1 specifically, allows the overlapping bind,
+ * and routes the loopback connection to the more specific binding, so that process answers instead of
+ * the app. The lane saw this as statuses no route can return, on a different test each run.
+ *
+ * setup-e2e.ts closes it by listening on 127.0.0.1 during `init()`, which is also the condition
+ * supertest branches on: a server that already has an address is reused rather than replaced. Both
+ * halves are asserted, because either one alone can hold while the protection is gone. Listening on
+ * the wildcard address still satisfies the second test, and never listening at all still satisfies
+ * neither, so the pair fails on a different side depending on which half was lost.
+ *
+ * The last two cover what taking that port early costs elsewhere: a bind that fails has to be
+ * reported rather than stall the boot, and an app that goes on to call `listen()` has to get its own
+ * socket back.
+ */
+describe('e2e listener bind contract', () => {
+ let app: INestApplication;
+
+ beforeAll(async () => {
+ const moduleRef = await Test.createTestingModule({ controllers: [PingController] }).compile();
+ app = moduleRef.createNestApplication();
+ await app.init();
+ });
+
+ afterAll(async () => {
+ await app?.close();
+ });
+
+ it('leaves the app listening on loopback, not the wildcard address', () => {
+ const address = (app.getHttpServer() as Server).address() as AddressInfo;
+ expect(address).not.toBeNull();
+ expect(address.address).toBe('127.0.0.1');
+ });
+
+ it('is the server that answers, so supertest never opens a wildcard one of its own', async () => {
+ const server = app.getHttpServer() as Server;
+ // Not "the port stayed the same": that holds either way. supertest opening its own listener is a
+ // `listen` call, so the call itself is what has to be absent.
+ const listen = jest.spyOn(Server.prototype, 'listen');
+ try {
+ await request(server).get('/__bind-probe').expect(200, { servedBy: 'the app under test' });
+ expect(listen).not.toHaveBeenCalled();
+ } finally {
+ listen.mockRestore();
+ }
+ });
+
+ // A bind failure is reported on 'error', never through the listen callback. Waiting on the callback
+ // alone stalls init() and lets Node throw the event with nothing listening, so the failure lands
+ // detached from the boot that caused it.
+ it('reports a failed bind instead of leaving init pending', async () => {
+ const failing = jest.spyOn(Server.prototype, 'listen').mockImplementation(function (this: Server) {
+ process.nextTick(() => this.emit('error', Object.assign(new Error('bind refused'), { code: 'EADDRINUSE' })));
+ return this;
+ });
+ const stalled = await NestFactory.create(BareModule, { logger: false });
+ try {
+ await expect(stalled.init()).rejects.toThrow('bind refused');
+ } finally {
+ failing.mockRestore();
+ await stalled.close().catch(() => undefined);
+ }
+ });
+
+ // Taking a port during init puts one on the same socket `listen()` wants, so without a handover it
+ // answers ERR_SERVER_ALREADY_LISTEN on a call that has nothing wrong with it. No suite calls
+ // `app.listen()` today, which is exactly why the breakage would surface as a puzzle later.
+ it('still lets an app call listen() afterwards, and puts that on loopback too', async () => {
+ const standalone = await NestFactory.create(BareModule, { logger: false });
+ try {
+ await standalone.listen(0);
+ const address = (standalone.getHttpServer() as Server).address() as AddressInfo;
+ expect(address.address).toBe('127.0.0.1');
+ } finally {
+ await standalone.close();
+ }
+ });
+});
diff --git a/test/setup-e2e.ts b/test/setup-e2e.ts
index c0b22dcc3..ce40f993b 100644
--- a/test/setup-e2e.ts
+++ b/test/setup-e2e.ts
@@ -22,6 +22,78 @@
import { join } from 'path';
import { tmpdir } from 'os';
import { rmSync } from 'fs';
+import { Server } from 'http';
+import { NestApplication } from '@nestjs/core';
+
+// Put every suite's server on a LOOPBACK port before supertest can start one of its own.
+//
+// supertest starts a server per request with `listen(0)` and no host (supertest/lib/test.js), which
+// binds the wildcard address, and then dials `http://127.0.0.1:<port>` whatever it bound. macOS hands
+// out an ephemeral port that an unrelated process already holds on 127.0.0.1 specifically (measured:
+// 40 of 40 such ports went to a wildcard listener), permits the overlapping bind, and routes the
+// loopback connection to the MORE specific binding. That process then answers, and its status reaches
+// the assertion: a captured run took a `501 Not Implemented` from a desktop helper on 127.0.0.1:49657,
+// on a machine holding 29 such loopback listeners. That is where this lane's statuses with no matching
+// route came from, on a different test each run, and no amount of state isolation could reach it.
+//
+// The host cannot simply be added to that `listen` call: a host argument routes the bind through
+// dns.lookup, so it completes a tick later, and supertest reads `address().port` synchronously.
+// Listening here instead means `app.address()` is already set, so supertest reuses this server and
+// never opens one. Binding 127.0.0.1 also makes a collision a refused bind rather than a silent
+// share, and the allocator skips ports already held on that address.
+//
+// Boundary worth knowing: this patches a prototype, so a suite that booted an app inside
+// `jest.isolateModules` would get a fresh, unpatched `@nestjs/core` and fall back to the exposed
+// path. Nothing does that today (the one caller only reads module metadata), but a new one would
+// need to listen on loopback itself.
+type AutoListened = Server & { __e2eAutoListened?: true };
+const nestAppProto = NestApplication.prototype as unknown as {
+ init: (...args: unknown[]) => Promise<unknown>;
+ listen: (...args: unknown[]) => Promise<unknown>;
+ getHttpServer: () => unknown;
+ __e2eLoopbackListening?: true;
+};
+if (!nestAppProto.__e2eLoopbackListening) {
+ const originalInit = nestAppProto.init;
+ nestAppProto.init = async function (this: typeof nestAppProto, ...args: unknown[]): Promise<unknown> {
+ const result = await originalInit.apply(this, args);
+ const server = this.getHttpServer() as AutoListened | undefined;
+ if (server && typeof server.listen === 'function' && !server.listening) {
+ // A failed bind arrives as an 'error' event, not as this callback. Waiting on the callback
+ // alone leaves init() pending AND, with nothing listening for 'error', Node throws it detached
+ // from the call that caused it. Either half is the unexplained failure this block exists to
+ // remove, so the event is what settles the wait.
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => {
+ server.removeListener('error', reject);
+ resolve();
+ });
+ });
+ server.__e2eAutoListened = true;
+ }
+ return result;
+ };
+
+ // `listen()` initialises first and then binds the SAME server, so the port taken above would meet it
+ // as ERR_SERVER_ALREADY_LISTEN on its own socket. Initialise here, hand that port back, and let the
+ // real call bind whatever it was asked for. A hostless port keeps the loopback the lane relies on,
+ // since a wildcard bind is exactly what the block above exists to avoid.
+ const originalListen = nestAppProto.listen;
+ nestAppProto.listen = async function (this: typeof nestAppProto, ...args: unknown[]): Promise<unknown> {
+ await this.init();
+ const server = this.getHttpServer() as AutoListened | undefined;
+ if (server?.__e2eAutoListened && server.listening) {
+ delete server.__e2eAutoListened;
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ }
+ const wantsDefaultHost = args.length <= 1 || typeof args[1] !== 'string';
+ return wantsDefaultHost
+ ? originalListen.call(this, args[0], '127.0.0.1', ...args.slice(1))
+ : originalListen.apply(this, args);
+ };
+ nestAppProto.__e2eLoopbackListening = true;
+}
process.env.NODE_ENV = 'test';
// The plugin registry + per-plugin storage: the last state a suite could not isolate.