| 1 | /** |
| 2 | * Frees API_PORT before `nest start --watch` binds it. |
| 3 | * |
| 4 | * Two watchers for the same app are the real cause of the recurring |
| 5 | * EADDRINUSE. The Nest CLI watcher keeps its tsc file-watcher alive even after |
| 6 | * its child app process dies, and turbo can detach that watcher from the |
| 7 | * `bun dev` that spawned it. A stale watcher is invisible — nothing on the |
| 8 | * port, no app logs — until the next edit, when it recompiles and spawns its |
| 9 | * own server on API_PORT, racing the watcher you actually meant to run. |
| 10 | * Whoever loses prints "address already in use". |
| 11 | * |
| 12 | * Killing the port holder is not enough: the rival watcher survives and wins |
| 13 | * the race on the *next* edit. So this kills any other Nest watcher for this |
| 14 | * app, its descendants, and anything still listening on the port. |
| 15 | */ |
| 16 | import { execFileSync } |
| 17 | import { dirname, resolve |
| 18 | import { fileURLToPath } |
| 19 | |
| 20 | const port = process |
| 21 | const appDir = resolve |
| 22 | |
| 23 | function run(cmd, |
| 24 | try { |
| 25 | return execFileSync(cmd |
| 26 | encoding: 'utf8', |
| 27 | stdio: ['ignore', |
| 28 | }); |
| 29 | } catch { |
| 30 | // A non-zero exit just means "no matches". |
| 31 | return ''; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | const lines = ( |
| 36 | output |
| 37 | .split('\n') |
| 38 | .map((line) |
| 39 | .filter(Boolean); |
| 40 | |
| 41 | function pidsOnPort() { |
| 42 | if (process.platform |
| 43 | return lines(run |
| 44 | .filter((line) |
| 45 | .map((line) |
| 46 | .filter((pid) |
| 47 | } |
| 48 | return lines(run |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Other `nest start --watch` processes for *this* app. Matching on the app |
| 53 | * directory keeps the blast radius to this workspace — a Nest watcher in |
| 54 | * another checkout is left alone. |
| 55 | */ |
| 56 | function rivalWatchers() { |
| 57 | if (process.platform |
| 58 | const ancestry = |
| 59 | descendantsOf(String(process |
| 60 | ); |
| 61 | return lines(run |
| 62 | (pid) => |
| 63 | ); |
| 64 | } |
| 65 | |
| 66 | function descendantsOf(pid, |
| 67 | for (const child |
| 68 | if (seen.has |
| 69 | seen.add(child |
| 70 | descendantsOf(child, seen |
| 71 | } |
| 72 | return [...seen |
| 73 | } |
| 74 | |
| 75 | const watchers = rivalWatchers |
| 76 | const targets = new |
| 77 | ...watchers, |
| 78 | ...watchers.flatMap( |
| 79 | ...pidsOnPort(), |
| 80 | ]); |
| 81 | targets.delete(String( |
| 82 | |
| 83 | for (const pid |
| 84 | try { |
| 85 | // SIGKILL, not SIGTERM: a watcher whose shutdown hooks hang (e.g. waiting |
| 86 | // on `pool.end()` against an unreachable database) is exactly the case |
| 87 | // that leaves the port held. |
| 88 | process.kill(Number |
| 89 | console.log(`[free-port] killed stale process |
| 90 | } catch (error) |
| 91 | if (error.code |
| 92 | console.warn(`[free-port] could not kill |
| 93 | } |
| 94 | } |
| 95 | } |