2024-08-18 15:33:56 +02:00
|
|
|
import { log, timedExecution, requestIdHeader } from '$lib';
|
2024-08-17 15:38:12 +02:00
|
|
|
import { validate, v7 as uuidv7 } from 'uuid';
|
2024-08-17 16:49:38 +02:00
|
|
|
import type { Handle } from '@sveltejs/kit';
|
2024-08-17 15:38:12 +02:00
|
|
|
|
2024-08-17 16:49:38 +02:00
|
|
|
export const handle: Handle = async ({ event, resolve }) => {
|
|
|
|
// use incoming requestId, if it is a valid uuid, else generate one
|
2024-08-17 15:38:12 +02:00
|
|
|
const reqIdFromRequest = event.request.headers.get(requestIdHeader);
|
|
|
|
const { requestId, fromRequest } =
|
|
|
|
reqIdFromRequest && validate(reqIdFromRequest)
|
|
|
|
? { requestId: reqIdFromRequest, fromRequest: true }
|
|
|
|
: { requestId: uuidv7(), fromRequest: false };
|
|
|
|
|
2024-08-17 15:54:33 +02:00
|
|
|
const context = {
|
2024-08-17 15:38:12 +02:00
|
|
|
requestId,
|
|
|
|
route: event.route.id,
|
|
|
|
method: event.request.method,
|
|
|
|
userAgent: event.request.headers.get('user-agent'),
|
2024-08-17 15:45:52 +02:00
|
|
|
clientIP: event.getClientAddress(),
|
2024-08-17 15:38:12 +02:00
|
|
|
};
|
|
|
|
if (fromRequest) {
|
2024-08-17 16:49:38 +02:00
|
|
|
log.trace(context, 'using incoming request-id');
|
2024-08-17 15:38:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// make requestId available to handlers
|
|
|
|
event.locals.requestId = requestId;
|
|
|
|
|
|
|
|
const { executionTime, result: response } = await timedExecution(async () => {
|
|
|
|
return await resolve(event);
|
|
|
|
});
|
|
|
|
response.headers.set(requestIdHeader, requestId);
|
|
|
|
|
|
|
|
log.info(
|
|
|
|
{
|
|
|
|
executionTime: `${executionTime}ms`,
|
|
|
|
status: response.status,
|
|
|
|
size: response.headers.get('content-length'),
|
2024-08-17 15:45:52 +02:00
|
|
|
...context,
|
2024-08-17 15:38:12 +02:00
|
|
|
},
|
|
|
|
'finished request'
|
|
|
|
);
|
|
|
|
|
|
|
|
return response;
|
2024-08-17 16:49:38 +02:00
|
|
|
};
|