Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
Blame · Line-by-line history

admin-deploys-page.tsx

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

admin-deploys-page.tsxBlame297 lines · 1 contributor
f764c07Claude1/**
2 * Block N3 — Platform deploy timeline page + JSON feed.
3 *
4 * GET /admin/deploys — site-admin HTML timeline (last 50 deploys)
5 * GET /admin/deploys/latest.json — `{ latest, asOf }` JSON. Polled by the
6 * layout status pill on every page; SSE
7 * pushes follow via `platform:deploys`.
8 *
9 * The companion POST /admin/deploys/trigger lives in `src/routes/admin-deploys.tsx`
10 * (Block N4 — pre-existing locked file) — we MUST NOT extend that file, so
11 * these GET routes ship as a sibling. Both mount on the same Hono `/` so the
12 * URLs land where the spec expects.
13 *
14 * Backed by `platform_deploys` (drizzle/0046_platform_deploys.sql,
15 * src/db/schema-deploys.ts). Populated by
16 * `POST /api/events/deploy/{started,finished}` in `src/routes/events.ts`,
17 * which the `.github/workflows/hetzner-deploy.yml` workflow calls as it runs.
18 */
19
20import { Hono } from "hono";
21import { desc } from "drizzle-orm";
22import { db } from "../db";
23import { platformDeploys } from "../db/schema-deploys";
24import { Layout } from "../views/layout";
25import { softAuth } from "../middleware/auth";
26import type { AuthEnv } from "../middleware/auth";
27import { isSiteAdmin } from "../lib/admin";
28
29const page = new Hono<AuthEnv>();
30page.use("*", softAuth);
31
32// ---------------------------------------------------------------------------
33// Helpers — exposed via `__test` so unit tests can hammer the format edges
34// without setting up the full Hono request pipeline.
35// ---------------------------------------------------------------------------
36
37/**
38 * Render a relative time like "just now", "12s ago", "3m ago", "2h ago",
39 * "3d ago". Stable for any past Date; clamps negative deltas to "just now"
40 * so a slight clock skew doesn't print "-2s".
41 */
42export function relativeTime(from: Date, now: Date = new Date()): string {
43 const ms = now.getTime() - from.getTime();
44 if (ms < 5_000) return "just now";
45 const s = Math.floor(ms / 1_000);
46 if (s < 60) return `${s}s ago`;
47 const m = Math.floor(s / 60);
48 if (m < 60) return `${m}m ago`;
49 const h = Math.floor(m / 60);
50 if (h < 24) return `${h}h ago`;
51 const d = Math.floor(h / 24);
52 return `${d}d ago`;
53}
54
55/** Short SHA — first 7 hex chars, lowercased. */
56export function shortSha(sha: string): string {
57 return (sha || "").slice(0, 7).toLowerCase();
58}
59
60/** Format duration_ms into "12s" / "1m 14s" / "—". */
61export function formatDuration(ms: number | null | undefined): string {
62 if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) return "—";
63 const s = Math.round(ms / 1000);
64 if (s < 60) return `${s}s`;
65 const m = Math.floor(s / 60);
66 const rem = s - m * 60;
67 return rem === 0 ? `${m}m` : `${m}m ${rem}s`;
68}
69
70interface DeployRow {
71 id: string;
72 runId: string;
73 sha: string;
74 source: string;
75 status: string;
76 startedAt: Date;
77 finishedAt: Date | null;
78 durationMs: number | null;
79 error: string | null;
80}
81
82async function fetchLatest(limit = 50): Promise<DeployRow[]> {
83 try {
84 const rows = await db
85 .select({
86 id: platformDeploys.id,
87 runId: platformDeploys.runId,
88 sha: platformDeploys.sha,
89 source: platformDeploys.source,
90 status: platformDeploys.status,
91 startedAt: platformDeploys.startedAt,
92 finishedAt: platformDeploys.finishedAt,
93 durationMs: platformDeploys.durationMs,
94 error: platformDeploys.error,
95 })
96 .from(platformDeploys)
97 .orderBy(desc(platformDeploys.startedAt))
98 .limit(limit);
99 return rows as DeployRow[];
100 } catch (err) {
101 console.error("[admin-deploys-page] fetchLatest failed:", err);
102 return [];
103 }
104}
105
106function serialise(row: DeployRow): Record<string, unknown> {
107 return {
108 id: row.id,
109 run_id: row.runId,
110 sha: row.sha,
111 source: row.source,
112 status: row.status,
113 started_at: row.startedAt.toISOString(),
114 finished_at: row.finishedAt ? row.finishedAt.toISOString() : null,
115 duration_ms: row.durationMs,
116 error: row.error,
117 };
118}
119
120// ---------------------------------------------------------------------------
121// Gate — both routes refuse anyone who isn't a site admin. The JSON variant
122// returns 401/403 JSON so the layout pill can `fetch()` it safely on every
123// page and silently disappear for non-admins.
124// ---------------------------------------------------------------------------
125
126async function gate(
127 c: any,
128 asJson: boolean
129): Promise<{ user: any } | Response> {
130 const user = c.get("user");
131 if (!user) {
132 return asJson
133 ? c.json({ ok: false, error: "Unauthorized" }, 401)
134 : c.redirect("/login?next=/admin/deploys");
135 }
136 if (!(await isSiteAdmin(user.id))) {
137 return asJson
138 ? c.json({ ok: false, error: "Forbidden" }, 403)
139 : c.html(
140 <Layout title="Forbidden" user={user}>
141 <div class="empty-state">
142 <h2>403 — Not a site admin</h2>
143 <p>You don't have permission to view this page.</p>
144 </div>
145 </Layout>,
146 403
147 );
148 }
149 return { user };
150}
151
152// ---------------------------------------------------------------------------
153// Routes
154// ---------------------------------------------------------------------------
155
156page.get("/admin/deploys/latest.json", async (c) => {
157 const g = await gate(c, true);
158 if (g instanceof Response) return g;
159 const rows = await fetchLatest(1);
160 return c.json({
161 ok: true,
162 latest: rows[0] ? serialise(rows[0]) : null,
163 asOf: new Date().toISOString(),
164 });
165});
166
167page.get("/admin/deploys", async (c) => {
168 const g = await gate(c, false);
169 if (g instanceof Response) return g;
170 const { user } = g;
171 const rows = await fetchLatest(50);
172 const lastSuccess = rows.find((r) => r.status === "succeeded") || null;
173 const repo = process.env.GITHUB_REPOSITORY || "ccantynz/Gluecron.com";
174
175 return c.html(
176 <Layout title="Deploys — admin" user={user}>
177 <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:18px">
178 <h2 style="margin:0">Platform deploys</h2>
179 <form
180 method="post"
181 action="/admin/deploys/trigger"
182 style="margin:0"
183 >
184 <button type="submit" class="btn btn-sm btn-primary">
185 Trigger deploy
186 </button>
187 </form>
188 </div>
189
190 <div style="background:var(--bg-elevated);border:1px solid var(--border);border-radius:8px;padding:14px 16px;margin-bottom:18px">
191 {lastSuccess ? (
192 <div>
193 <div style="font-size:12px;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.06em">
194 Last successful deploy
195 </div>
196 <div style="margin-top:4px;font-size:14px">
197 <code class="meta-mono">{shortSha(lastSuccess.sha)}</code>
198 {" · "}
199 <span title={lastSuccess.startedAt.toISOString()}>
200 {relativeTime(lastSuccess.startedAt)}
201 </span>
202 {" · "}
203 <span>{formatDuration(lastSuccess.durationMs)}</span>
204 {" · "}
205 <span>{lastSuccess.source}</span>
206 </div>
207 </div>
208 ) : (
209 <div style="color:var(--text-muted);font-size:14px">
210 No successful deploys recorded yet.
211 </div>
212 )}
213 </div>
214
215 <table style="width:100%;border-collapse:collapse;font-size:13px">
216 <thead>
217 <tr style="text-align:left;color:var(--text-muted);border-bottom:1px solid var(--border)">
218 <th style="padding:8px 6px;width:90px">Status</th>
219 <th style="padding:8px 6px">SHA</th>
220 <th style="padding:8px 6px">Source</th>
221 <th style="padding:8px 6px">Started</th>
222 <th style="padding:8px 6px">Duration</th>
223 <th style="padding:8px 6px">Error</th>
224 </tr>
225 </thead>
226 <tbody>
227 {rows.length === 0 && (
228 <tr>
229 <td
230 colspan={6}
231 style="padding:18px 6px;color:var(--text-muted);text-align:center"
232 >
233 No deploys recorded yet — they'll appear here when the next
234 push to <code>main</code> runs hetzner-deploy.yml.
235 </td>
236 </tr>
237 )}
238 {rows.map((row) => (
239 <tr style="border-bottom:1px solid var(--border)">
240 <td style="padding:8px 6px">
241 <span
242 title={row.status}
243 aria-label={row.status}
244 style={`display:inline-block;width:10px;height:10px;border-radius:50%;background:${
245 row.status === "succeeded"
246 ? "#34d399"
247 : row.status === "failed"
248 ? "#f87171"
249 : "#fbbf24"
250 }`}
251 />
252 <span style="margin-left:8px">{row.status}</span>
253 </td>
254 <td style="padding:8px 6px">
255 <code class="meta-mono">{shortSha(row.sha)}</code>
256 </td>
257 <td style="padding:8px 6px">{row.source}</td>
258 <td
259 style="padding:8px 6px"
260 title={row.startedAt.toISOString()}
261 >
262 {relativeTime(row.startedAt)}
263 </td>
264 <td style="padding:8px 6px">
265 {formatDuration(row.durationMs)}
266 </td>
267 <td
268 style="padding:8px 6px;color:var(--text-muted);max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
269 title={row.error || ""}
270 >
271 {row.error ? row.error.slice(0, 160) : "—"}
272 </td>
273 </tr>
274 ))}
275 </tbody>
276 </table>
277
278 <p style="margin-top:18px;font-size:12px;color:var(--text-muted)">
279 Manual trigger (CLI shortcut — the button above is wired to the N4
280 POST /admin/deploys/trigger handler):{" "}
281 <code class="meta-mono">
282 gh workflow run hetzner-deploy.yml -R {repo}
283 </code>
284 </p>
285 </Layout>
286 );
287});
288
289export const __test = {
290 relativeTime,
291 shortSha,
292 formatDuration,
293 fetchLatest,
294 serialise,
295};
296
297export default page;