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

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