Skip to content

[PoC] feat: Add support for server-side instrumentation #13776

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions packages/adapter-node/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readFileSync, writeFileSync } from 'node:fs';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { rollup } from 'rollup';
import { nodeResolve } from '@rollup/plugin-node-resolve';
Expand Down Expand Up @@ -48,14 +48,21 @@ export default function (opts = {}) {

const pkg = JSON.parse(readFileSync('package.json', 'utf8'));

/** @type {Record<string, string>} */
const input = {
index: `${tmp}/index.js`,
manifest: `${tmp}/manifest.js`
};

if (existsSync(`${tmp}/instrument.server.js`)) {
input['instrument.server'] = `${tmp}/instrument.server.js`;
}

// we bundle the Vite output so that deployments only need
// their production dependencies. Anything in devDependencies
// will get included in the bundled code
const bundle = await rollup({
input: {
index: `${tmp}/index.js`,
manifest: `${tmp}/manifest.js`
},
input,
external: [
// dependencies could have deep exports, so we need a regex
...Object.keys(pkg.dependencies || {}).map((d) => new RegExp(`^${d}(\\/.*)?$`))
Expand Down
9 changes: 9 additions & 0 deletions packages/adapter-node/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ export default [
format: 'esm'
},
plugins: [nodeResolve({ preferBuiltins: true }), commonjs(), json(), prefixBuiltinModules()],
external: ['./start.js']
},
{
input: 'src/start.js',
output: {
file: 'files/start.js',
format: 'esm'
},
plugins: [nodeResolve({ preferBuiltins: true }), commonjs(), json(), prefixBuiltinModules()],
external: ['ENV', 'HANDLER']
},
{
Expand Down
113 changes: 16 additions & 97 deletions packages/adapter-node/src/index.js
Original file line number Diff line number Diff line change
@@ -1,105 +1,24 @@
import process from 'node:process';
import { handler } from 'HANDLER';
import { env } from 'ENV';
import polka from 'polka';
import { existsSync } from 'node:fs';
import { join } from 'node:path';

export const path = env('SOCKET_PATH', false);
export const host = env('HOST', '0.0.0.0');
export const port = env('PORT', !path && '3000');
const dirname = new URL('.', import.meta.url).pathname;

const shutdown_timeout = parseInt(env('SHUTDOWN_TIMEOUT', '30'));
const idle_timeout = parseInt(env('IDLE_TIMEOUT', '0'));
const listen_pid = parseInt(env('LISTEN_PID', '0'));
const listen_fds = parseInt(env('LISTEN_FDS', '0'));
// https://www.freedesktop.org/software/systemd/man/latest/sd_listen_fds.html
const SD_LISTEN_FDS_START = 3;
const instrumentFile = join(dirname, 'server', 'instrument.server.js');

if (listen_pid !== 0 && listen_pid !== process.pid) {
throw new Error(`received LISTEN_PID ${listen_pid} but current process id is ${process.pid}`);
}
if (listen_fds > 1) {
throw new Error(
`only one socket is allowed for socket activation, but LISTEN_FDS was set to ${listen_fds}`
);
}

const socket_activation = listen_pid === process.pid && listen_fds === 1;

let requests = 0;
/** @type {NodeJS.Timeout | void} */
let shutdown_timeout_id;
/** @type {NodeJS.Timeout | void} */
let idle_timeout_id;

const server = polka().use(handler);

if (socket_activation) {
server.listen({ fd: SD_LISTEN_FDS_START }, () => {
console.log(`Listening on file descriptor ${SD_LISTEN_FDS_START}`);
});
if (existsSync(instrumentFile)) {
import(instrumentFile)
.catch((err) => {
console.error('Failed to import instrument.server.js', err);
})
.finally(() => {
tryImportStart();
});
} else {
server.listen({ path, host, port }, () => {
console.log(`Listening on ${path || `http://${host}:${port}`}`);
});
tryImportStart();
}

/** @param {'SIGINT' | 'SIGTERM' | 'IDLE'} reason */
function graceful_shutdown(reason) {
if (shutdown_timeout_id) return;

// If a connection was opened with a keep-alive header close() will wait for the connection to
// time out rather than close it even if it is not handling any requests, so call this first
// @ts-expect-error this was added in 18.2.0 but is not reflected in the types
server.server.closeIdleConnections();

server.server.close((error) => {
// occurs if the server is already closed
if (error) return;

if (shutdown_timeout_id) {
clearTimeout(shutdown_timeout_id);
}
if (idle_timeout_id) {
clearTimeout(idle_timeout_id);
}

// @ts-expect-error custom events cannot be typed
process.emit('sveltekit:shutdown', reason);
function tryImportStart() {
import('./start.js').catch((err) => {
console.error('Failed to import server (start.js)', err);
});

shutdown_timeout_id = setTimeout(
// @ts-expect-error this was added in 18.2.0 but is not reflected in the types
() => server.server.closeAllConnections(),
shutdown_timeout * 1000
);
}

server.server.on(
'request',
/** @param {import('node:http').IncomingMessage} req */
(req) => {
requests++;

if (socket_activation && idle_timeout_id) {
idle_timeout_id = clearTimeout(idle_timeout_id);
}

req.on('close', () => {
requests--;

if (shutdown_timeout_id) {
// close connections as soon as they become idle, so they don't accept new requests
// @ts-expect-error this was added in 18.2.0 but is not reflected in the types
server.server.closeIdleConnections();
}
if (requests === 0 && socket_activation && idle_timeout) {
idle_timeout_id = setTimeout(() => graceful_shutdown('IDLE'), idle_timeout * 1000);
}
});
}
);

process.on('SIGTERM', graceful_shutdown);
process.on('SIGINT', graceful_shutdown);

export { server };
105 changes: 105 additions & 0 deletions packages/adapter-node/src/start.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import process from 'node:process';
import { handler } from 'HANDLER';
import { env } from 'ENV';
import polka from 'polka';

export const path = env('SOCKET_PATH', false);
export const host = env('HOST', '0.0.0.0');
export const port = env('PORT', !path && '3000');

const shutdown_timeout = parseInt(env('SHUTDOWN_TIMEOUT', '30'));
const idle_timeout = parseInt(env('IDLE_TIMEOUT', '0'));
const listen_pid = parseInt(env('LISTEN_PID', '0'));
const listen_fds = parseInt(env('LISTEN_FDS', '0'));
// https://www.freedesktop.org/software/systemd/man/latest/sd_listen_fds.html
const SD_LISTEN_FDS_START = 3;

if (listen_pid !== 0 && listen_pid !== process.pid) {
throw new Error(`received LISTEN_PID ${listen_pid} but current process id is ${process.pid}`);
}
if (listen_fds > 1) {
throw new Error(
`only one socket is allowed for socket activation, but LISTEN_FDS was set to ${listen_fds}`
);
}

const socket_activation = listen_pid === process.pid && listen_fds === 1;

let requests = 0;
/** @type {NodeJS.Timeout | void} */
let shutdown_timeout_id;
/** @type {NodeJS.Timeout | void} */
let idle_timeout_id;

const server = polka().use(handler);

if (socket_activation) {
server.listen({ fd: SD_LISTEN_FDS_START }, () => {
console.log(`Listening on file descriptor ${SD_LISTEN_FDS_START}`);
});
} else {
server.listen({ path, host, port }, () => {
console.log(`Listening on ${path || `http://${host}:${port}`}`);
});
}

/** @param {'SIGINT' | 'SIGTERM' | 'IDLE'} reason */
function graceful_shutdown(reason) {
if (shutdown_timeout_id) return;

// If a connection was opened with a keep-alive header close() will wait for the connection to
// time out rather than close it even if it is not handling any requests, so call this first
// @ts-expect-error this was added in 18.2.0 but is not reflected in the types
server.server.closeIdleConnections();

server.server.close((error) => {
// occurs if the server is already closed
if (error) return;

if (shutdown_timeout_id) {
clearTimeout(shutdown_timeout_id);
}
if (idle_timeout_id) {
clearTimeout(idle_timeout_id);
}

// @ts-expect-error custom events cannot be typed
process.emit('sveltekit:shutdown', reason);
});

shutdown_timeout_id = setTimeout(
// @ts-expect-error this was added in 18.2.0 but is not reflected in the types
() => server.server.closeAllConnections(),
shutdown_timeout * 1000
);
}

server.server.on(
'request',
/** @param {import('node:http').IncomingMessage} req */
(req) => {
requests++;

if (socket_activation && idle_timeout_id) {
idle_timeout_id = clearTimeout(idle_timeout_id);
}

req.on('close', () => {
requests--;

if (shutdown_timeout_id) {
// close connections as soon as they become idle, so they don't accept new requests
// @ts-expect-error this was added in 18.2.0 but is not reflected in the types
server.server.closeIdleConnections();
}
if (requests === 0 && socket_activation && idle_timeout) {
idle_timeout_id = setTimeout(() => graceful_shutdown('IDLE'), idle_timeout * 1000);
}
});
}
);

process.on('SIGTERM', graceful_shutdown);
process.on('SIGINT', graceful_shutdown);

export { server };
5 changes: 5 additions & 0 deletions packages/kit/src/exports/vite/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,11 @@ Tips:
const name = posixify(path.join('entries/matchers', key));
input[name] = path.resolve(file);
});

const instrument_server = resolve_entry('src/instrument.server');
if (instrument_server) {
input['instrument.server'] = instrument_server;
}
} else if (svelte_config.kit.output.bundleStrategy !== 'split') {
input['bundle'] = `${runtime_directory}/client/bundle.js`;
} else {
Expand Down
4 changes: 2 additions & 2 deletions playgrounds/basic/svelte.config.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import adapter from '@sveltejs/adapter-auto';
import adapter from '@sveltejs/adapter-node';

/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
adapter: adapter()
adapter: adapter({})
}
};

Expand Down
Loading