-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
179 lines (164 loc) · 5.05 KB
/
server.ts
File metadata and controls
179 lines (164 loc) · 5.05 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
import puppeteer from "npm:puppeteer-core";
import { getParams } from "./params.ts";
import { closeBrowser, getBrowser } from "./browser.ts";
import { ServerTiming } from "./server-timing.ts";
const PORT = Number(Deno.env.get("PORT") ?? 3000);
// Allow manual shutdown (Ctrl-C) even if puppeteer installs its own signal handlers.
const shutdownController = new AbortController();
let lastLaunch = 0;
let pagesServed = 0;
const MAX_BROWSER_AGE_MS = 10 * 60 * 1000; // recycle every 10 minutes
const MAX_PAGES = 500; // or after N pages to avoid leaks
// Graceful shutdown handling. In Deno Deploy signals may differ; locally SIGINT works.
function setupSignalHandlers() {
const handler = () => {
console.log(`\nReceived termination signal, shutting down...`);
try { shutdownController.abort(); } catch { /* ignore */ }
try { closeBrowser(); } catch { /* ignore */ }
};
// Best-effort: if permissions allow
try {
Deno.addSignalListener("SIGINT", handler);
} catch { /* ignore if signals not permitted */ }
try {
Deno.addSignalListener("SIGTERM", handler);
} catch { /* ignore if signals not permitted */ }
}
setupSignalHandlers();
async function headReachable(url: string, ms = 8_000): Promise<boolean> {
const ac = new AbortController();
const t = setTimeout(() => ac.abort(), ms);
try {
const r = await fetch(url, { method: "HEAD", signal: ac.signal });
return r.ok || (r.status >= 300 && r.status < 400);
} catch {
return false;
} finally {
clearTimeout(t);
}
}
async function performChromiumCheck(): Promise<Response> {
try {
const b = await getBrowser();
if (!b || !b.connected) return new Response("not ok", { status: 503 });
return new Response("ok");
} catch {
return new Response("not ok", { status: 503 });
}
}
async function getBrowserWithRecycling(
dumpio = false,
fontRenderHinting = "medium",
): Promise<puppeteer.Browser> {
if (
pagesServed >= MAX_PAGES ||
(Date.now() - lastLaunch) > MAX_BROWSER_AGE_MS
) {
closeBrowser();
lastLaunch = Date.now();
pagesServed = 0;
}
const browser = await getBrowser(
dumpio,
fontRenderHinting,
);
return browser;
}
Deno.serve({ port: PORT, signal: shutdownController.signal }, async (req) => {
console.log(`Request: ${req.method} ${req.url}`);
const { pathname, searchParams } = new URL(req.url);
if (pathname === "/healthz") return await performChromiumCheck();
if (pathname !== "/pdf") {
return new Response("Not found", { status: 404 });
}
const timing = new ServerTiming<"start" | "params" | "head" | "browser" | "page" | "emulate" | "goto" | "pdf" | "total">();
timing.start("start");
timing.start("total");
timing.start("params");
const params = getParams(searchParams);
timing.stop("params");
if (!params.disableHeadCheck) {
timing.start("head");
const reachable = await headReachable(params.url);
timing.stop("head");
if (!reachable) {
timing.stop("total");
const headers = new Headers({
"Content-Type": "application/json",
"Server-Timing": timing.toString()
});
return new Response(
JSON.stringify({ error: "Target URL not reachable" }),
{
status: 502,
headers,
},
);
}
}
let page:
| Awaited<
ReturnType<Awaited<ReturnType<typeof puppeteer.launch>>["newPage"]>
>
| null = null;
try {
timing.start("browser");
const browser = await getBrowserWithRecycling(
params.dumpio,
params.fontRenderHinting,
);
timing.stop("browser");
timing.start("page");
page = await browser.newPage();
timing.stop("page");
pagesServed++;
timing.start("emulate");
await page.emulateMediaType(params.media);
timing.stop("emulate");
timing.start("goto");
await page.goto(params.url, {
waitUntil: params.wait,
timeout: 30_000, // Set a timeout for page loading
});
timing.stop("goto");
timing.start("pdf");
const pdf = await page.pdf({
format: params.format,
margin: {
top: params.marginTop,
right: params.marginRight,
bottom: params.marginBottom,
left: params.marginLeft,
},
printBackground: params.printBackground,
displayHeaderFooter: params.includeHeaderFooter,
});
timing.stop("pdf");
timing.stop("total");
const headers = new Headers({
"X-Content-Type-Options": "nosniff",
"Content-Type": "application/pdf",
"Content-Disposition": 'inline; filename="page.pdf"',
"Cache-Control": "no-store",
"Server-Timing": timing.toString(),
});
return new Response(pdf, { headers });
} catch (err) {
console.error(err);
timing.stop("total");
const headers = new Headers({
"Content-Type": "application/json",
"Server-Timing": timing.toString(),
});
return new Response(JSON.stringify({ error: "Failed to render PDF" }), {
status: 500,
headers,
});
} finally {
if (page) {
try {
await page.close();
} catch { /* ignore */ }
}
}
});