From 71dce10e14d9aa09b95e49f8a91caafafc3659b7 Mon Sep 17 00:00:00 2001 From: Xi Xu Date: Fri, 1 Nov 2024 20:31:10 +0800 Subject: [PATCH] Update index.js --- src/index.js | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/src/index.js b/src/index.js index 172e854..07072a3 100644 --- a/src/index.js +++ b/src/index.js @@ -8,7 +8,7 @@ class PerformanceMonitor { * Initializes a new performance monitor */ constructor() { - this.startTime = Date.now(); + this.startTime = performance.now(); this.marks = new Map(); } @@ -17,10 +17,15 @@ class PerformanceMonitor { * @param {string} name - The name of the timing mark */ mark(name) { - if (this.marks.has(name)) { - console.warn(`Mark with name ${name} already exists.`); + try { + if (this.marks.has(name)) { + console.warn(`Mark with name ${name} already exists.`); + return; + } + this.marks.set(name, performance.now() - this.startTime); + } catch (error) { + console.error(`Error setting mark ${name}:`, error); } - this.marks.set(name, Date.now() - this.startTime); } /** @@ -80,21 +85,22 @@ function addSecurityHeaders(headers) { */ async function handleRequest(request, env, ctx) { try { + monitor.mark("start"); const url = new URL(request.url); // Serve homepage for root path if (url.pathname === "/" || url.pathname === "") { + monitor.mark("homepage_redirect"); const HOME_PAGE_URL = "https://xixu-me.github.io/Xget/"; - const requestHeaders = new Headers(request.headers); - - const homePageRequest = new Request(HOME_PAGE_URL, { - method: request.method, - headers: requestHeaders, - body: request.body, - redirect: "manual", - }); - - return fetch(homePageRequest, { redirect: "manual" }); + return fetch( + new Request(HOME_PAGE_URL, { + method: request.method, + headers: new Headers(request.headers), + body: request.body, + redirect: "manual", + }), + { redirect: "manual" } + ); } const monitor = new PerformanceMonitor(); @@ -222,11 +228,14 @@ async function handleRequest(request, env, ctx) { monitor.mark("complete"); return addPerformanceHeaders(finalResponse, monitor); } catch (error) { + monitor.mark("error"); console.error("Error handling request:", error); return new Response(`Internal Server Error: ${error.message}`, { status: 500, headers: addSecurityHeaders(new Headers()), }); + } finally { + monitor.mark("complete"); } }