r/javascript • • 20d ago

Got tired of scattering console.log('here 1') to find promises that hang silently, so I built a zero-dep dev tool to trace them

https://github.com/YourDarkstFear/hang-trace
1 Upvotes

14 comments sorted by

2

u/raks1991 16d ago

A never-settling promise doesn't keep Node alive by itself. If nothing else is pending, this exits with code 0:

async function main() {
  await new Promise(() => {});
  console.log('done'); // never prints
}
main();

That matters for hang-trace: the diagnostic timer is unref'd, so in this case Node exits before it fires and the hang never gets reported. Top-level await instead exits with code 13, with a "Detected unsettled top-level await" warning on Node 22+. For a process that really stays stuck, process.getActiveResourcesInfo() names the resources holding the event loop open.

1

u/ksneteto 16d ago

Spot on. in a standalone script where nothing else holds the libuv event loop open, an unsettled promise doesn't keep Node alive, and because `hang-trace` calls `.unref()` on its timer, the process exits before the warning fires.

`hang-trace` is primarily aimed at environments where the loop is already kept alive; like HTTP servers, long-running workers, or browsers; where a single request or async call stalls indefinitely without crashing the whole process.

Also, while `process.getActiveResourcesInfo()` is super useful for inspecting open libuv handles in Node, it won't catch pure JS-level hangs (like an `EventEmitter` listener or in-memory lock that never resolves) nor pinpoint the exact call-site line number across Node and browser runtimes.

Though exposing an optional `unref: false` flag for debugging short-lived CLI scripts is actually a great idea, thanks for bringing this up!

1

u/azhder 20d ago

Good idea.

I've made such wrappers in a previous project, they were primarily for promises that were left for years without even a `.catch` (yup, that much silent), but I didn't make many of them report if they hang - only a single spot where calls to BE were being made. This looks nice, the other half of the problem.

Not so good idea.

The first time I noticed something like `process.env.NODE_ENV === 'production'` I thought it was a nice and polite thing people did for others. Now I'm not so sure. It's bordering "bad design" since it's a hidden input.

I'm not talking about "hidden input" as something not explained in the documentation, the readme file etc. I'm talking in terms of functional programming i.e. the output depends only on the arguments you give it.

If your entire library changes behavior not because of the arguments you have given it, like a configuration object, but an outside environment change... Let's consider this. What if I want it to work if `NODE_ENV` is set as `production` due to reasons (legacy software can be one example)?

1

u/ksneteto 20d ago

That is actually a fantastic point regarding functional purity and edge-case environments (like staging or legacy setups running with `NODE_ENV=production`).

Right now, the library strictly short-circuits on `NODE_ENV === 'production'`, meaning developers can't force-enable it in production-like containers even if they explicitly want to trace a stubborn hang.

I'll address this in `v1.1.0` by introducing an explicit override option:

- Allowing an explicit `force: true` or `enabled: boolean` flag in options to take precedence over `NODE_ENV`.

- Keeping the production check only as the default fallback when no explicit flag is passed.

Thanks a lot for the thoughtful architectural feedback!

1

u/azhder 20d ago

Why even use an override? You can make it simpler if you let that be the only way. People can always channel their NODE_ENV variable to it.

const utility = configure({ enable: !! process.env.ON })

The next step would be if you make it more complex by using a differently named environment variable (instead of NODE_ENV), then if you use two variables (one more on top of NODE_ENV) etc.

I just mentioned the simplest solution that doesn't require hidden inputs: don't use hidden inputs, be explicit.

1

u/ksneteto 20d ago

I really appreciate this perspective, from a pure functional design standpoint, removing hidden inputs entirely and delegating all control to the caller is definitely the cleanest model.

The main reason I kept `process.env.NODE_ENV` built-in by default comes down to static dead code elimination (tree-shaking) and developer friction:

  1. Modern bundlers (Vite, esbuild, Webpack, Rollup) statically replace `process.env.NODE_ENV === 'production'` at build time. When it's hardcoded as a static check, bundlers can drop the entire diagnostic branch from client production bundles. If the toggle is purely dynamic/runtime-configured via a factory, bundlers can't reliably eliminate that code path.
  2. Zero-Config DX: When hunting down a bug, most devs just want to `import { trace } from 'hang-trace'` and wrap the suspected line immediately without having to set up a shared `tracer.ts` config module first.

That said, your point about flexibility is totally valid. A clean middle ground might be:

- Keep the zero-config `trace()` with the static `NODE_ENV` guard + an explicit override option (`enabled?: boolean` or `force?: boolean`).

- Also export a `createTracer(options)` factory for people who want pure, explicit dependency injection without relying on global env checks.

Thanks for the push on this it’s a great architectural trade-off to think through!

1

u/azhder 20d ago

I know why you used it, just didn't want to write all of that and then come up with workarounds for it, so I just said I'm using the simplest solution, not the only, not the most performant or whatever other metric you care about.

1

u/ksneteto 20d ago

Fair enough! Different design goals, different trade-offs. Thanks for the insightful exchange!

1

u/h_emily_3279 11d ago

Would a per-trace timeout make sense? A long poll and a genuinely stuck request need different definitions of 'hung'.

1

u/ksneteto 6d ago

100% agree, a long poll or heavy background job has a completely different baseline than a standard API request.

hang-trace actually supports this out of the box via the per-call timeoutMs option (falling back to 4000ms only when omitted):

// Strict threshold for a fast DB/API query
await trace(getUser(id), { timeoutMs: 1500, label: 'getUser' });

// Relaxed threshold for long polling
await trace(pollEvents(), { timeoutMs: 30000, label: 'pollEvents' });

It works the exact same way with wrapAsync(fn, { timeoutMs }) so you can tailor thresholds per function or call site.

1

u/oneeyedziggy 20d ago

Mostly look for any thens without  catches and you're most of the way there... But thanks for making a tool... Probably beats manual search... (though not as good as a blocking lint rule on a husky commit hook... Ifk if that's a thing...  I just don't want the path to have to be exercised in order to be found ) 

1

u/azhder 20d ago

Linters work on static code analysis. How will someone check for it without running it?

If you didn't mean "executed" instead of "exercised", great pun on running/exercise.

1

u/oneeyedziggy 20d ago

Could check for a lack of timeout, or missing catch where it failed silently... Probably non-trivial,  but also probably doable with custom lint rules? 

1

u/walkerpaul-62 5d ago

A missing catch handles rejected promises; a never-settling one never reaches it. A timeout is separate.