Repository navigation
Expand file tree
/
Copy pathserver.mjs
More file actions
239 lines (214 loc) · 7.18 KB
/
Copy pathserver.mjs
File metadata and controls
239 lines (214 loc) · 7.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import { createServer } from "http";
import sirv from "sirv";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import { createReadStream, existsSync, statSync } from "fs";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const PORT = process.env.PORT || 4321;
const HOST = process.env.HOST || "0.0.0.0";
const CLIENT_DIR = join(__dirname, "dist");
const SHUTDOWN_DEADLINE_MS = 25_000;
const CONTENT_TYPES = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".mjs": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".xml": "application/xml; charset=utf-8",
".svg": "image/svg+xml",
".txt": "text/plain; charset=utf-8",
".webp": "image/webp",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".ico": "image/x-icon",
".avif": "image/avif",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".eot": "application/vnd.ms-fontobject",
".otf": "font/otf",
".pdf": "application/pdf",
".zip": "application/zip",
".doc": "application/msword",
".docx":
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".xls": "application/vnd.ms-excel",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".ppt": "application/vnd.ms-powerpoint",
".pptx":
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
".webmanifest": "application/manifest+json",
".map": "application/json",
".pf_fragment": "application/octet-stream",
".pf_index": "application/octet-stream",
".pf_meta": "application/octet-stream",
".pagefind": "application/octet-stream",
};
const COMPRESSIBLE_EXTENSIONS = /\.(html|css|js|mjs|json|xml|svg|txt|map)$/;
// File extensions that should trigger download instead of display
const DOWNLOAD_EXTENSIONS = /\.(docx?|xlsx?|pptx?|zip)$/i;
// Static file server for pre-rendered pages and assets
const staticServer = sirv(CLIENT_DIR, {
maxAge: 31536000,
immutable: true,
gzip: true,
brotli: true,
etag: true,
dotfiles: false,
extensions: ["html"], // Auto-append .html for clean URLs
single: false, // Don't serve index.html for all routes (SPA mode)
setHeaders: (res, pathname) => {
if (pathname.includes("/_astro/")) {
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
} else if (pathname.match(/\.(html)$/)) {
res.setHeader("Cache-Control", "public, max-age=0, must-revalidate");
}
// Force download for Office documents and archives
if (DOWNLOAD_EXTENSIONS.test(pathname)) {
const filename = pathname.split("/").pop();
res.setHeader(
"Content-Disposition",
`attachment; filename="${filename}"`,
);
}
},
});
function getContentType(url) {
const ext = url.match(/\.[^.]+$/)?.[0]?.toLowerCase() || "";
return CONTENT_TYPES[ext] || "application/octet-stream";
}
function isCompressible(url) {
return COMPRESSIBLE_EXTENSIONS.test(url);
}
// Serve pre-compressed files (.gz, .br) for text-based content
function serveCompressed(req, res, next) {
if (req.method !== "GET" && req.method !== "HEAD") {
return next();
}
let url = req.url.split("?")[0];
if (url.endsWith("/")) {
url += "index.html";
}
if (!isCompressible(url)) {
return next();
}
const acceptEncoding = req.headers["accept-encoding"] || "";
const filePath = join(CLIENT_DIR, url);
// Try brotli first (better compression ratio)
if (acceptEncoding.includes("br")) {
const brPath = filePath + ".br";
if (existsSync(brPath)) {
const stat = statSync(brPath);
res.writeHead(200, {
"Content-Type": getContentType(url),
"Content-Encoding": "br",
"Content-Length": stat.size,
Vary: "Accept-Encoding",
"Cache-Control": url.includes("/_astro/")
? "public, max-age=31536000, immutable"
: "public, max-age=0, must-revalidate",
});
if (req.method === "HEAD") {
res.end();
} else {
createReadStream(brPath).pipe(res);
}
return;
}
}
// Fallback to gzip (widely supported)
if (acceptEncoding.includes("gzip")) {
const gzPath = filePath + ".gz";
if (existsSync(gzPath)) {
const stat = statSync(gzPath);
res.writeHead(200, {
"Content-Type": getContentType(url),
"Content-Encoding": "gzip",
"Content-Length": stat.size,
Vary: "Accept-Encoding",
"Cache-Control": url.includes("/_astro/")
? "public, max-age=31536000, immutable"
: "public, max-age=0, must-revalidate",
});
if (req.method === "HEAD") {
res.end();
} else {
createReadStream(gzPath).pipe(res);
}
return;
}
}
next();
}
// Fallback for unmatched routes: serve the pre-rendered 404 page.
function serveNotFound(req, res) {
const notFoundPath = join(CLIENT_DIR, "404.html");
if (existsSync(notFoundPath)) {
const stat = statSync(notFoundPath);
res.writeHead(404, {
"Content-Type": "text/html; charset=utf-8",
"Content-Length": stat.size,
});
if (req.method === "HEAD") {
res.end();
} else {
createReadStream(notFoundPath).pipe(res);
}
return;
}
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Not Found");
}
const server = createServer((req, res) => {
if (process.env.NODE_ENV !== "production") {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
}
const url = req.url.split("?")[0];
// Health check endpoints for Kubernetes probes
if (url === "/healthz" || url === "/livez" || url === "/readyz") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("OK");
return;
}
// Middleware order: compressed files → static files → 404 page
serveCompressed(req, res, () => {
staticServer(req, res, () => {
serveNotFound(req, res);
});
});
});
server.keepAliveTimeout = 75_000;
server.headersTimeout = 76_000;
server.on("error", (err) => {
console.error("Server error:", err);
});
let shuttingDown = false;
process.on("SIGTERM", () => {
if (shuttingDown) return;
shuttingDown = true;
console.log("SIGTERM received, shutting down gracefully...");
server.close(() => {
console.log("Server closed");
process.exit(0);
});
server.closeIdleConnections();
setTimeout(() => {
console.log("Shutdown deadline reached, closing remaining connections");
server.closeAllConnections();
process.exit(0);
}, SHUTDOWN_DEADLINE_MS).unref();
});
server.listen(PORT, HOST, () => {
console.log(`
╔════════════════════════════════════════════════════════════╗
║ Server running
║
║ ✅ Pre-compressed files (.gz, .br) enabled
║ ✅ Static file server (images, fonts, etc.) enabled
║ ✅ Static 404 page for unknown routes
╚════════════════════════════════════════════════════════════╝
`);
});