Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

250 linesCodeBlameRaw
1/**
2 * The dispatcher for g1t.page: every app deployed by g1t is served here.
3 *
4 * The hostname's first label is the app's script name in the Workers for
5 * Platforms namespace (`web-git-fix-login-acme.g1t.page` is the fix-login
6 * branch's preview of acme's web project), so the app is fetched by name
7 * and runs only for as long as it answers. An app no one visits runs
8 * nothing and costs nothing. Each request it serves is held to
9 * `APP_LIMITS`, so one app cannot spend without bound. The one lookup is for an address an app
10 * had before its project moved: `DOMAINS` holds a redirect under the old
11 * hostname for as long as the old name is held, and it is followed before
12 * anything the old script would answer (such as a paused notice).
13 *
14 * Any other hostname is a project's custom domain, reaching here through
15 * Cloudflare for SaaS: the `DOMAINS` KV namespace, written by the
16 * deployments service, names its app, or the hostname it redirects to.
17 *
18 * Kept apart from g1t.sh, so apps share no cookies or origin with the site
19 * people sign in to.
20 */
21
22import {
23 APP_LIMITS,
24 DOMAIN,
25 FALLBACK,
26 REQUEST_ID_HEADER,
27 REQUEST_MARK,
28 overLimits,
29 parseEntry,
30 redirectTo,
31 route,
32 traceFor,
33 type AppTelemetry,
34 type DomainEntry,
35} from "./route.ts";
36
37type Env = {
38 APPS: DispatchNamespace;
39 /** Custom hostname, or an app's old g1t.page hostname, to `{ script, redirect }`. */
40 DOMAINS?: KVNamespace;
41};
42
43/** How long a custom hostname's entry is kept in this isolate and at the edge. */
44const ENTRY_TTL_MS = 60 * 1000;
45const entries = new Map<string, { at: number; entry: DomainEntry | null }>();
46
47function page(status: number, title: string, body: string, site = DOMAIN): Response {
48 const html = `<!doctype html>
49<html lang="en">
50<head>
51<meta charset="utf-8">
52<meta name="viewport" content="width=device-width, initial-scale=1">
53<meta name="robots" content="noindex">
54<title>${escape(title)} · ${escape(site)}</title>
55<style>
56 :root { color-scheme: dark; --bg: #121214; --fg: #ececf1; --muted: #9a9aa6; --accent: #b4a7f5; }
57 body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: var(--bg); color: var(--fg);
58 font: 16px/1.6 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; padding: 0 16px; }
59 main { max-width: 32rem; }
60 h1 { font-size: 1.5rem; margin: 0 0 .5rem; letter-spacing: -.01em; }
61 p { color: var(--muted); margin: .5rem 0; }
62 a { color: var(--accent); }
63 code { font: .9em ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--fg); }
64</style>
65</head>
66<body><main><h1>${escape(title)}</h1>${body}</main></body>
67</html>`;
68 return new Response(html, {
69 status,
70 headers: { "content-type": "text/html; charset=utf-8", "x-robots-tag": "noindex", "cache-control": "no-store" },
71 });
72}
73
74function escape(text: string): string {
75 return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
76}
77
78/** A custom hostname's entry: from this isolate, else KV (cached at the edge too). */
79async function lookup(env: Env, hostname: string): Promise<DomainEntry | null> {
80 const cached = entries.get(hostname);
81 if (cached && Date.now() - cached.at < ENTRY_TTL_MS) return cached.entry;
82 const value = env.DOMAINS ? await env.DOMAINS.get(hostname, { type: "json", cacheTtl: ENTRY_TTL_MS / 1000 }) : null;
83 const entry = parseEntry(value);
84 entries.set(hostname, { at: Date.now(), entry });
85 if (entries.size > 5000) entries.delete(entries.keys().next().value!);
86 return entry;
87}
88
89/**
90 * Runs the app `script` for the request; `shown` is the address named in
91 * its error pages. Each request gets an id and a trace, handed to the app
92 * (`x-g1t-request-id`, `traceparent`), and one line naming them, the app
93 * and its project (`telemetry`), which observability reads from this
94 * Worker's tail events and files with what the app's own tell it.
95 */
96async function dispatch(env: Env, request: Request, script: string, shown: string, missing: () => Response, telemetry: AppTelemetry | null): Promise<Response> {
97 const { id, trace, traceparent } = traceFor(request.headers.get("traceparent"));
98 console.log(REQUEST_MARK, { id, script, trace_id: trace, app: telemetry });
99 const headers = new Headers(request.headers);
100 headers.set(REQUEST_ID_HEADER, id);
101 headers.set("traceparent", traceparent);
102 request = new Request(request, { headers });
103 let app: Fetcher;
104 try {
105 app = env.APPS.get(script, {}, { limits: APP_LIMITS });
106 } catch {
107 return missing();
108 }
109 try {
110 return await app.fetch(request);
111 } catch (error) {
112 if (/worker not found|script not found|does not exist/i.test(String(error))) return missing();
113 if (overLimits(error)) {
114 return page(
115 503,
116 "The app went over its limits",
117 `<p>The app at <code>${escape(shown)}</code> used more than ${APP_LIMITS.cpuMs} ms of CPU time, or made more than ${APP_LIMITS.subRequests} requests of its own, answering this request.</p>`,
118 shown,
119 );
120 }
121 return page(502, "The app failed", `<p>The app at <code>${escape(shown)}</code> threw an error before it could answer.</p>`, shown);
122 }
123}
124
125export default {
126 async fetch(request: Request, env: Env): Promise<Response> {
127 const host = new URL(request.url).hostname;
128 const where = route(host);
129 switch (where.kind) {
130 case "home":
131 return page(
132 200,
133 "g1t.page",
134 `<p>Apps deployed by <a href="https://g1t.sh">g1t</a>: every pull request's preview, and each repository's production.</p>
135 <p><a href="https://docs.g1t.sh/guides/deployments/">How deployments work</a></p>`,
136 );
137 case "fallback":
138 return page(
139 200,
140 "Custom domains on g1t",
141 `<p>Point a custom domain here, with a CNAME to <code>${FALLBACK}</code>, to serve a project's production on it. Add the domain first, under the project's Settings, Deployments, on g1t.</p>
142 <p><a href="https://docs.g1t.sh/guides/deployments/#custom-domains">How custom domains work</a></p>`,
143 );
144 case "invalid":
145 return page(404, "Nothing here", "<p>This is not the address of an app on g1t.page.</p>");
146 case "custom":
147 return custom(request, env, where.hostname);
148 case "app": {
149 const label = where.label;
150 // An address the app had before its project moved (its workspace or
151 // repository was renamed or transferred) redirects to where it is
152 // now, whatever the app it named answers, paused or not.
153 const { moved, telemetry } = await appRedirect(request, env, label);
154 if (moved) return moved;
155 let response = await dispatch(env, request, label, `${label}.${DOMAIN}`, () => missing(label), telemetry);
156 // Previews are for the people reviewing a change, not search engines.
157 if (isPreview(label)) {
158 response = new Response(response.body, response);
159 response.headers.set("x-robots-tag", "noindex");
160 }
161 return response;
162 }
163 }
164 },
165} satisfies ExportedHandler<Env>;
166
167/**
168 * The redirect for an app's old address, if the deployments service left
169 * one (in `DOMAINS`, under the old hostname, as `{ script, redirect }`),
170 * else null. A lookup that fails serves the app as it is rather than an
171 * error.
172 */
173async function appRedirect(request: Request, env: Env, label: string): Promise<{ moved: Response | null; telemetry: AppTelemetry | null }> {
174 const hostname = `${label}.${DOMAIN}`;
175 let entry: DomainEntry | null;
176 try {
177 entry = await lookup(env, hostname);
178 } catch (error) {
179 console.error("could not read redirect", label, error);
180 return { moved: null, telemetry: null };
181 }
182 // Otherwise the entry is the app's own: what its requests are filed under.
183 if (!entry?.redirect || entry.redirect === hostname) return { moved: null, telemetry: entry?.telemetry ?? null };
184 const moved = new Response(null, {
185 status: 301,
186 headers: {
187 location: redirectTo(request.url, entry.redirect),
188 "x-robots-tag": "noindex",
189 "cache-control": "public, max-age=3600",
190 },
191 });
192 return { moved, telemetry: null };
193}
194
195/** A custom domain: its app, or a 308 to the hostname it is paired with. */
196async function custom(request: Request, env: Env, hostname: string): Promise<Response> {
197 let entry: DomainEntry | null;
198 try {
199 entry = await lookup(env, hostname);
200 } catch (error) {
201 console.error("could not read domain", hostname, error);
202 return page(503, "Try again in a moment", `<p><code>${escape(hostname)}</code> could not be looked up just now.</p>`, hostname);
203 }
204 if (!entry) {
205 return page(
206 404,
207 "This domain is not set up",
208 `<p><code>${escape(hostname)}</code> points at g1t, but no project serves it. Its owner adds it under the project's Settings, Deployments, on <a href="https://g1t.sh">g1t</a>.</p>`,
209 hostname,
210 );
211 }
212 if (entry.redirect && entry.redirect !== hostname) {
213 return new Response(null, {
214 status: 308,
215 headers: { location: redirectTo(request.url, entry.redirect), "cache-control": "public, max-age=300" },
216 });
217 }
218 // The app's own entry names its project, for observability.
219 const own = await lookup(env, `${entry.script}.${DOMAIN}`).catch(() => null);
220 return dispatch(
221 env,
222 request,
223 entry.script,
224 hostname,
225 () =>
226 page(
227 404,
228 "Nothing deployed here yet",
229 `<p><code>${escape(hostname)}</code> serves a project's production, and it is not up. Deploying the project brings it here.</p>`,
230 hostname,
231 ),
232 own?.redirect ? null : (own?.telemetry ?? null),
233 );
234}
235
236/** A branch's preview: `<project>-git-<branch>-<workspace>`. */
237function isPreview(label: string): boolean {
238 return label.includes("-git-");
239}
240
241function missing(label: string): Response {
242 const preview = isPreview(label);
243 return page(
244 404,
245 preview ? "This preview is not up" : "Nothing deployed here",
246 preview
247 ? `<p>A preview comes down when its pull request is closed or merged, or after its project's idle days without a visit. Pushing to the branch, or redeploying it from the project's Deployments page, brings it back.</p>`
248 : `<p>No app is deployed at <code>${escape(label)}.${DOMAIN}</code>. Deployments are turned on per project, from its Settings on g1t.</p>`,
249 );
250}