Distinguishing a request deadline from user cancellation in Node.js
Combine a preview request deadline with a panel's cancellation signal. A local HTTP example exercises successful JSON, cancellation after headers, and an expired deadline.
In this article
- Set the deadline over the entire preview
- Carry the first cancellation reason into the caller
- Observe what happens after the server sends its headers
- Distinguish the result on the client from the result on the server
- Keep an older completion away from a newer pane
- Use measured latency when choosing production limits
Set the deadline over the entire preview
A preview pane calls a service after a user selects a file. Two things can make the request no longer useful: the user may close the pane, or the service may run out of time. The first can be an ordinary navigation event. The second may leave an open pane with no preview and a reason to offer a retry. Code handling both cases needs to identify the cause before it chooses what to show. Let's define completion as receiving a usable JSON body. Fetch can make a Response available after the headers arrive while the body is still incoming. A deadline that ends at the first header therefore gives up control over part of the operation. Keep the same signal on the request while the body is consumed and treat that point as the end of work for this interface.
Carry the first cancellation reason into the caller
The pane owns one controller and the request layer creates a fresh deadline signal for each call. AbortSignal.any turns them into a signal that aborts when one input aborts. Its reason comes from the input that caused that transition. The local example distinguishes inputs by comparing that reason to the reason object on each source. After a close deadline, both sources might already appear aborted by the time an error is handled, so inspecting a boolean on one source alone can misclassify an outcome. Use distinct reason objects if identity determines the outcome. An ordinary network or JSON parsing failure can arrive with the combined signal still active. Preserve that failure for the caller. The narrow sample exercises two HTTP success routes and cancellation, so a real application should also check the HTTP response status before consuming it as a preview.
Observe what happens after the server sends its headers
The test starts a server on a local loopback port. Its slow route sends headers, then waits three hundred milliseconds before ending the body. One call takes the ordinary fast path. A second cancels as soon as the headers become available. A third leaves its pane open and hits a forty-millisecond deadline. On Windows with Node.js 24.19.0 the states were received, cancelled and timed-out in that order. The first result also contained the expected JSON property. Testing cancellation after the headers is deliberate. It demonstrates that a later stage can still be interrupted, even after the application has a Response object. The assertions check the returned states rather than relying on when a line happens to appear in the console. The test closes the loopback server after the cases complete; it makes no requests to any external service.
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {once} from 'node:events';
import {setTimeout as wait} from 'node:timers/promises';
const server = createServer(async (request, response) => {
response.setHeader('content-type', 'application/json');
if (request.url === '/slow') {
response.flushHeaders();
await wait(300);
}
response.end('{"ready":true}');
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const origin = 'http://127.0.0.1:' + server.address().port;
async function load(path, caller, timeoutMs, onHeaders = () => {}) {
const deadline = AbortSignal.timeout(timeoutMs);
const signal = AbortSignal.any([caller, deadline]);
try {
const response = await fetch(origin + path, {signal});
onHeaders();
return {state: 'received', body: await response.json()};
} catch (error) {
if (!signal.aborted) throw error;
if (caller.aborted && signal.reason === caller.reason) return {state: 'cancelled'};
if (deadline.aborted && signal.reason === deadline.reason) return {state: 'timed-out'};
throw error;
}
}
try {
const first = new AbortController();
const second = new AbortController();
const third = new AbortController();
const results = [
await load('/fast', first.signal, 1000),
await load('/slow', second.signal, 1000, () => second.abort(new Error('panel closed'))),
await load('/slow', third.signal, 40)
];
assert.deepEqual(results, [
{state:'received',body:{ready:true}},
{state:'cancelled'},
{state:'timed-out'}
]);
console.log(results.map(x => x.state).join(', '));
} finally {
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
}
Distinguish the result on the client from the result on the server
A client stopping its wait tells you what happened in that client's workflow. The service may still compute the response, finish a database write or queue a file in the background. For a read-only preview, the simplest recovery may be to request it again. For operations with lasting effects, retain an operation identity and check whether the original attempt committed before retrying it. A message that says the preview timed out does not convey any transaction outcome. When expensive work can be interrupted, verify that path on the actual server and in downstream services. Cancellation may save capacity only when those components observe it. The test above does not implement a server-side job cancellation protocol. It demonstrates the contract at the fetch and body-reading boundary.
Keep an older completion away from a newer pane
If a user closes a pane and reopens it, create a new controller for the next request. A state update should also confirm that its request is still the active one. A monotonically increasing request ID, or an owned handle for a single preview, provides that check. It covers the narrow case where the previous operation finished just before the close event and scheduled a result that has not yet been applied. Use cancellation, timeout and normal connection failure as separate cases at the point where UI decisions are made. The labels in the sample are for code; the interface can simply keep a closed pane closed, keep an active pane available for retry, or show a parsing error as appropriate. Test with the keyboard and a slow preview so selection changes while the request is still live.
Use measured latency when choosing production limits
The experimental forty milliseconds exists to exercise the test case, not to prescribe a product deadline. Measure time until headers and time until the complete body for the actual preview sizes. Tag cancellations separately from deadline expirations so ordinary navigation does not inflate a service reliability metric. Keep identifiers in logs where they support diagnosis, and choose a limited set of outcome labels for aggregates. Add tests for an already aborted signal, an invalid body, and an error status where previews are frequently retried. A local test can prove the control flow, while production traces can tell you how often each path is needed. Run the after-headers case when changing the request wrapper. It guards the exact boundary that a shorter smoke test would miss.
Reader discussion
What would you change first for maintainability and testing in your own project?
No comments yet. Be the first to contribute.
Write a comment