Skip to content

g1t/apps/web/app/routes/repo/deployments.tsx

355 lines15,718 bytesCodeBlame
1import { ExternalLink, Globe, Rocket, RotateCw, Trash2 } from "lucide-react";
2import type { ReactNode } from "react";
3import { Form, Link } from "react-router";
4
5import type { Deployment, FeatureState } from "@g1t/contracts";
6
7import { host, StatusDot } from "../../components/deploy";
8
9import type { Route } from "./+types/deployments";
10import { page } from "../../lib/meta";
11import { ButtonLink, ComputeNote, EmptyState, ErrorText, SubmitButton, TimeAgo } from "../../components/ui";
12import { Hint } from "../../components/ui/hint";
13import { computeNoteFor } from "../../lib/compute.server";
14import { billing, deployments, projects } from "../../lib/services.server";
15import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
16import { refusal, requireRepo } from "../../lib/access.server";
17import { whyNot } from "../../lib/access";
18import { buildError, groupBuilds, type BuildGroup } from "../../lib/deployments";
19
20export function meta({ params, ...args }: Route.MetaArgs) {
21 return page(args, { title: `Deployments · ${params.owner}/${params.repo} · g1t` });
22}
23
24export async function loader({ params, context }: Route.LoaderArgs) {
25 const viewer = getViewer(context);
26 // Anyone who can read the repository: a public one's to anyone, a private one's to people with a role.
27 const { access } = await requireRepo(context, params, "read");
28 const ref = { workspace: params.owner, slug: params.repo };
29 const [settings, list, features, computeNote, project] = await Promise.all([
30 deployments.settings(ref, viewer),
31 deployments.list(ref, viewer),
32 billing.features(params.owner, viewer),
33 // Builds are compute: said before a deploy is refused for it.
34 computeNoteFor(params.owner, "deploy"),
35 projects.get(params.owner, params.repo, viewer).catch(() => null),
36 ]);
37 // Set not to deploy, in General settings: turning them on waits for that to change.
38 const notDeploying = project?.ok ? project.value.deploys === "no" : false;
39 // Deployments come with the g1t plan. Someone outside the workspace does
40 // not see its plans; the page works without, and the deployments service
41 // refuses a deploy the plan does not cover.
42 const plan = features.ok
43 ? (features.value.find((state) => state.plan.feature === "plan" || state.plan.feature === "deployments") ?? null)
44 : null;
45 return { can: access.can, settings: unwrap(settings), ...unwrap(list), plan, computeNote, notDeploying };
46}
47
48export async function action({ request, params, context }: Route.ActionArgs) {
49 assertSameOrigin(request);
50 const user = requireUser(context, request);
51 const form = await request.formData();
52 const ref = { workspace: params.owner, slug: params.repo };
53 const intent = form.get("intent");
54 const branch = form.get("branch") ? String(form.get("branch")) : null;
55 // Deploying is compute (Write); turning deployments on or off is a deployment setting (Admin).
56 const refused = await refusal(context, params, intent === "enable" || intent === "disable" ? "manage_integrations" : "run");
57 if (refused) return { error: refused };
58 if (intent === "redeploy") {
59 const started = await deployments.redeploy(user, ref, branch);
60 return started.ok ? { notice: "Build started." } : { error: started.error.message };
61 }
62 if (intent === "take-down") {
63 const done = await deployments.takeDown(user, ref, branch);
64 return done.ok ? { notice: "Taken down." } : { error: done.error.message };
65 }
66 if (intent === "enable" || intent === "disable") {
67 const saved = await deployments.updateSettings(user, ref, { enabled: intent === "enable" });
68 return saved.ok
69 ? { notice: intent === "enable" ? "Deployments are on. Production is building." : "Deployments are off, and every app is down." }
70 : { error: saved.error.message };
71 }
72 return { error: "Unknown request." };
73}
74
75export default function RepoDeployments({ loaderData, actionData, params }: Route.ComponentProps) {
76 const { settings, deployments: builds, live, plan, can } = loaderData;
77 const base = `/${params.owner}/${params.repo}`;
78 const production = live.find((app) => app.kind === "production");
79 const previews = live.filter((app) => app.kind === "preview");
80
81 return (
82 <div className="mx-auto max-w-5xl">
83 <header className="flex flex-wrap items-start justify-between gap-4">
84 <div>
85 <h1 className="flex items-center gap-2 text-xl font-semibold tracking-tight">
86 <Rocket size={18} className="text-accent" />
87 Deployments
88 </h1>
89 <p className="mt-1 max-w-2xl text-sm text-muted">
90 Every pull request gets a live preview on g1t.page, and the default branch goes to production on each push.
91 Apps run on Cloudflare only while someone visits them.{" "}
92 <a href="https://docs.g1t.sh/guides/deployments/" className="text-fg hover:underline">
93 How it works
94 </a>
95 </p>
96 </div>
97 {settings.enabled && (
98 <a
99 href={settings.primaryDomain ? `https://${settings.primaryDomain}` : settings.productionUrl}
100 className="inline-flex items-center gap-1.5 rounded-md border border-line px-3 py-1.5 font-mono text-xs text-muted hover:border-line-strong hover:text-fg"
101 >
102 <Globe size={13} />
103 {settings.primaryDomain ?? host(settings.productionUrl)}
104 </a>
105 )}
106 </header>
107
108 <div className="mt-4 min-h-6">
109 {actionData && "notice" in actionData && <p className="text-sm text-success">{actionData.notice}</p>}
110 <ErrorText>{actionData && "error" in actionData ? actionData.error : null}</ErrorText>
111 {!actionData && <ComputeNote note={loaderData.computeNote} />}
112 </div>
113
114 {plan != null && !plan.on && !plan.included && live.length === 0 ? (
115 <PlanNeeded plan={plan} owner={params.owner} />
116 ) : !settings.enabled ? (
117 <section className="mt-2 rounded-xl border border-accent/30 bg-accent/5 p-6">
118 <h2 className="font-medium">Deployments are off</h2>
119 <p className="mt-1 max-w-2xl text-sm text-muted">
120 Each project turns deployments on for itself; until then nothing builds or runs. Once on, production goes
121 up at <span className="font-mono text-fg">{host(settings.productionUrl)}</span> and every open pull request
122 gets its own preview. Workers projects (a <code className="font-mono text-fg">wrangler.jsonc</code>) and
123 static sites deploy without configuration.
124 </p>
125 {loaderData.notDeploying ? (
126 <p className="mt-4 max-w-2xl text-sm text-muted">
127 This project is set as one that doesn't deploy, a library or a tool. To deploy it, choose Deploys or Detect
128 automatically in{" "}
129 <Link to={`/${params.owner}/${params.repo}/settings#deploys`} className="text-fg underline underline-offset-4">
130 its settings
131 </Link>{" "}
132 first.
133 </p>
134 ) : (
135 <Form method="post" className="mt-4">
136 <Hint label={whyNot(can, "manage_integrations")} disabled={!can.manage_integrations}>
137 <SubmitButton variant="accent" name="intent" value="enable" pending="Turning on…" disabled={!can.manage_integrations}>
138 <Rocket size={14} />
139 Turn on deployments
140 </SubmitButton>
141 </Hint>
142 </Form>
143 )}
144 </section>
145 ) : (
146 <>
147 <section className="mt-2 grid gap-4 md:grid-cols-2">
148 <LiveCard
149 title="Production"
150 hint="The default branch, on every push."
151 app={production}
152 off={!settings.production}
153 actions={
154 can.run ? <AppActions branch={null} up={!!production} /> : null
155 }
156 />
157 <div className="rounded-xl border border-line bg-surface p-5">
158 <h2 className="text-sm font-medium">Previews</h2>
159 <p className="mt-0.5 text-xs text-faint">
160 {settings.previews
161 ? `One per branch with an open pull request; down when it closes or after ${settings.idleDays} days without a visit.`
162 : "Off for this repository."}
163 </p>
164 {previews.length === 0 ? (
165 <p className="mt-4 text-sm text-muted">No previews are up.</p>
166 ) : (
167 <ul className="mt-3 divide-y divide-line">
168 {previews.map((app) => (
169 <li key={app.url} className="flex items-center gap-3 py-2 text-sm">
170 <span className="shrink-0">
171 <span className="font-medium">{app.branch}</span>
172 {app.number != null && (
173 <Link to={`${base}/pull/${app.number}`} className="ml-1.5 text-xs text-muted hover:underline">
174 #{app.number}
175 </Link>
176 )}
177 </span>
178 <a href={app.url} className="min-w-0 truncate font-mono text-xs text-muted hover:text-fg">
179 {host(app.url)}
180 </a>
181 <span className="ml-auto shrink-0">
182 {can.run && <AppActions branch={app.branch} up compact />}
183 </span>
184 </li>
185 ))}
186 </ul>
187 )}
188 </div>
189 </section>
190
191 <h2 className="mt-10 text-sm font-medium text-muted">Recent builds</h2>
192 <div className="mt-3">
193 {builds.length === 0 ? (
194 <EmptyState title="No builds yet">Push to the default branch or open a pull request.</EmptyState>
195 ) : (
196 <ul className="divide-y divide-line overflow-hidden rounded-xl border border-line">
197 {groupBuilds(builds).map((group) => (
198 <BuildRow key={group.build.id} group={group} base={base} />
199 ))}
200 </ul>
201 )}
202 </div>
203
204 <p className="mt-10 text-sm text-muted">
205 Build command, output directory, idle days, and turning deployments off are under{" "}
206 <Link to={`${base}/settings/deployments`} className="text-fg hover:underline">
207 Settings → Deployments
208 </Link>
209 . Secrets and config for builds and running apps are under{" "}
210 <Link to={`${base}/settings/secrets`} className="text-fg hover:underline">
211 Settings → Secrets and variables
212 </Link>
213 , and production's own domains under{" "}
214 <Link to={`${base}/settings/domains`} className="text-fg hover:underline">
215 Settings → Domains
216 </Link>
217 .
218 </p>
219 </>
220 )}
221 </div>
222 );
223}
224
225function PlanNeeded({ plan, owner }: { plan: FeatureState | null; owner: string }) {
226 return (
227 <section className="mt-2 rounded-xl border border-accent/30 bg-accent/5 p-6">
228 <h2 className="font-medium">Deployments are part of a paid plan</h2>
229 <p className="mt-1 max-w-2xl text-sm text-muted">
230 Turn on Deployments for the {owner} workspace and every project in it can have a preview for each pull
231 request and production on g1t.page.
232 {plan && ` $${(plan.plan.monthlyCents / 100).toFixed(0)} a month, including:`}
233 </p>
234 {plan && (
235 <ul className="mt-3 grid gap-1.5 text-sm text-muted sm:grid-cols-2">
236 {plan.plan.includes.map((line) => (
237 <li key={line} className="flex gap-2">
238 <span className="text-success">✓</span>
239 {line}
240 </li>
241 ))}
242 </ul>
243 )}
244 {plan && <p className="mt-3 text-xs text-faint">{plan.plan.overage}</p>}
245 <div className="mt-4">
246 <ButtonLink variant="accent" to={`/${owner}/-/billing`}>
247 See the plan under Billing
248 </ButtonLink>
249 </div>
250 </section>
251 );
252}
253
254function LiveCard({
255 title,
256 hint,
257 app,
258 off,
259 actions,
260}: {
261 title: string;
262 hint: string;
263 app: { url: string; commit: string; deployedAt: string } | undefined;
264 off: boolean;
265 actions: ReactNode;
266}) {
267 return (
268 <div className="rounded-xl border border-line bg-surface p-5">
269 <h2 className="text-sm font-medium">{title}</h2>
270 <p className="mt-0.5 text-xs text-faint">{off ? "Off for this repository." : hint}</p>
271 {app ? (
272 <>
273 <a href={app.url} className="mt-3 flex items-center gap-1.5 font-mono text-sm text-accent hover:underline">
274 {host(app.url)}
275 <ExternalLink size={12} />
276 </a>
277 <p className="mt-1 text-xs text-faint">
278 <span className="font-mono">{app.commit.slice(0, 8)}</span> · deployed <TimeAgo at={app.deployedAt} />
279 </p>
280 </>
281 ) : (
282 <p className="mt-4 text-sm text-muted">Not up.</p>
283 )}
284 {!off && <div className="mt-4">{actions}</div>}
285 </div>
286 );
287}
288
289function AppActions({ branch, up, compact }: { branch: string | null; up: boolean; compact?: boolean }) {
290 // Which app's buttons say they are working: production has no branch.
291 const app = branch ?? "production";
292 return (
293 <Form method="post" className="flex items-center gap-2">
294 {branch != null && <input type="hidden" name="branch" value={branch} />}
295 <input type="hidden" name="app" value={app} />
296 <Hint label="Build again from the current head">
297 <SubmitButton
298 variant="quiet"
299 name="intent"
300 value="redeploy"
301 match={{ app }}
302 icon={compact}
303 pending="Redeploying…"
304 aria-label={compact ? "Redeploy" : undefined}
305 >
306 <RotateCw size={13} />
307 {!compact && "Redeploy"}
308 </SubmitButton>
309 </Hint>
310 {up && (
311 <Hint label="Take it down now">
312 <SubmitButton
313 variant="quiet"
314 name="intent"
315 value="take-down"
316 match={{ app }}
317 icon={compact}
318 pending="Taking down…"
319 aria-label={compact ? "Take down" : undefined}
320 >
321 <Trash2 size={13} />
322 {!compact && "Take down"}
323 </SubmitButton>
324 </Hint>
325 )}
326 </Form>
327 );
328}
329
330function BuildRow({ group, base }: { group: BuildGroup<Deployment>; base: string }) {
331 const { build, count } = group;
332 const error = buildError(build);
333 return (
334 <li>
335 <Link to={`${base}/deployments/${build.id}`} className="flex items-center gap-4 px-4 py-3 text-sm hover:bg-surface">
336 <span className="w-20 shrink-0">
337 <StatusDot status={build.status} />
338 {/* A run of the same failure is one row: how many, and when the latest was. */}
339 {count > 1 && <span className="mt-0.5 block pl-3 text-xs text-muted">{count} times</span>}
340 </span>
341 <span className="min-w-0 grow">
342 <span className="block truncate font-medium">
343 {build.kind === "production" ? "Production" : `Preview of ${build.branch}`}
344 <span className="ml-2 font-mono text-xs font-normal text-faint">{build.commit.slice(0, 8)}</span>
345 </span>
346 {error && <span className="mt-0.5 line-clamp-2 text-xs text-muted sm:line-clamp-1">{error}</span>}
347 </span>
348 <span className="shrink-0 text-xs text-faint">
349 {count > 1 ? "last " : build.buildSeconds != null && `${build.buildSeconds} s · `}
350 <TimeAgo at={build.createdAt} />
351 </span>
352 </Link>
353 </li>
354 );
355}