@sentry/node
Version:
Sentry Node SDK using OpenTelemetry for performance instrumentation
60 lines (59 loc) • 2.26 kB
JavaScript
import { GLOBAL_OBJ, getActiveSpan, getRootSpan } from "@sentry/core";
import { _INTERNAL_safeUnref } from "@sentry/core/server";
import { subscribeDiagnosticsChannel } from "@sentry/server-utils";
// src/sdk/vercel.ts
const HTTP_ON_SERVER_RESPONSE_FINISH = "http.server.response.finish";
const REQUEST_END_TIMEOUT_MS = 2e3;
let keepAliveClient;
/**
* Keeps Vercel Node.js functions alive until the SDK has sent the telemetry of each request.
*
* Vercel can suspend a function as soon as the response is sent, so buffered events, spans, logs and metrics
* (and the timers that flush them) arrive late or never. When a response
* finishes, we register one `waitUntil` that waits for the response to close and the request's root span to
* end (2 seconds at most), and then flushes the client.
*/
function setupVercelKeepAlive(client) {
const isRegistered = !!keepAliveClient;
keepAliveClient = client;
if (isRegistered) return;
process.on("SIGTERM", async () => {
await keepAliveClient?.flush(200);
});
subscribeDiagnosticsChannel(HTTP_ON_SERVER_RESPONSE_FINISH, (message) => {
const { response } = message;
const requestContext = GLOBAL_OBJ[Symbol.for("@vercel/request-context")]?.get?.();
const client = keepAliveClient;
if (!client || !response || !requestContext?.waitUntil) return;
const activeSpan = getActiveSpan();
const rootSpan = activeSpan && getRootSpan(activeSpan);
requestContext.waitUntil(waitForRequestEnd(client, response, rootSpan, REQUEST_END_TIMEOUT_MS).then(() => client.flush(2e3)));
});
}
function waitForRequestEnd(client, response, rootSpan, timeout) {
return new Promise((resolve) => {
let responseClosed = false;
let rootSpanEnded = !rootSpan?.isRecording();
const done = () => {
clearTimeout(timer);
unsubscribe();
resolve();
};
const doneIfRequestEnded = () => {
if (responseClosed && rootSpanEnded) done();
};
const timer = _INTERNAL_safeUnref(setTimeout(done, timeout));
const unsubscribe = client.on("spanEnd", (span) => {
if (span === rootSpan) {
rootSpanEnded = true;
doneIfRequestEnded();
}
});
response.once("close", () => {
responseClosed = true;
doneIfRequestEnded();
});
});
}
export { setupVercelKeepAlive };
//# sourceMappingURL=vercel.js.map