Hub 2.8.0: an install's .env on its page, changed with a restart
- Settings (.env) panel on an Events or Accounts install: reads the .env through an env-read job (addresses first; secrets only as set or not), and changes plain values with an env-set job (restart, or rebuild for the frontend's file; the server puts the file back if the site doesn't start). After a change the file is read again. One change per install at a time. - Contracts 1.12.0 vendored (env jobs need agent 1.3.0). - env-read / env-set in the Jobs type filter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -18,7 +18,7 @@ const FILTERS = [
|
||||
{ key: "cancelled", label: "Cancelled" },
|
||||
];
|
||||
|
||||
const TYPES = ["", "install", "add-product", "deploy", "adopt", "adopt-undo", "export", "uninstall", "purge", "seed-demo", "restart", "status", "check-ports", "update-agent"];
|
||||
const TYPES = ["", "install", "add-product", "deploy", "adopt", "adopt-undo", "export", "uninstall", "purge", "seed-demo", "env-read", "env-set", "restart", "status", "check-ports", "update-agent"];
|
||||
const PRODUCTS = [{ key: "", label: "Every product" }, { key: "events", label: "Cross Events" }, { key: "accounts", label: "Accounts" }];
|
||||
|
||||
/** Every job sent to a server's agent, newest first, a page at a time (§11: the full report is on each job). */
|
||||
|
||||
@@ -10,6 +10,7 @@ import { PRODUCT_NAMES } from "@/lib/products";
|
||||
import type { Release } from "@/lib/types";
|
||||
import { Loading, Message, PageTitle, Pager } from "@/components/ui";
|
||||
import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job, type ServerSummary } from "@/components/servers";
|
||||
import { EnvPanel } from "@/components/EnvPanel";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
type Detail = {
|
||||
@@ -164,6 +165,9 @@ export default function DeploymentPage() {
|
||||
</form>
|
||||
)}
|
||||
|
||||
{/* Hub 2.8.0: the install's .env, and changing it with a restart. */}
|
||||
{["events", "accounts"].includes(x.product) && ["live", "waiting_for_proxy"].includes(x.status) && <EnvPanel deploymentId={x.id} product={x.product} />}
|
||||
|
||||
{x.product === "events" && ["live", "waiting_for_proxy"].includes(x.status) && (
|
||||
<div className="card space-y-3">
|
||||
<h2 className="font-medium">Demo site</h2>
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { ago, fmtDate } from "@/lib/format";
|
||||
import { Message } from "@/components/ui";
|
||||
|
||||
/**
|
||||
* An install's .env (Hub 2.8.0, agent 1.3.0): what's in it (secrets only as set or not), changing
|
||||
* plain values, then a restart (or a rebuild for the frontend's file). The server keeps a copy of
|
||||
* the file and puts it back when the site doesn't start again with the new values.
|
||||
*/
|
||||
|
||||
type Variable = { name: string; value: string | null; secret: boolean; set: boolean; layer: string | null; description: string | null; editable: boolean };
|
||||
type EnvFile = { file: string; exists: boolean; variables: Variable[] };
|
||||
type EnvState = {
|
||||
supported: boolean;
|
||||
minAgent: string;
|
||||
env: { product: string; files: EnvFile[]; readAt: string } | null;
|
||||
readJobId: string | null;
|
||||
pending: { id: string; type: "env-read" | "env-set"; status: string; createdAt: string }[];
|
||||
lastSet: { id: string; status: string; message: string | null; finishedAt: string | null; args: { file: string; set: Record<string, string>; unset: string[] } } | null;
|
||||
};
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
|
||||
/** The addresses, shown first: what people most often need to check or fix. */
|
||||
const ADDRESSES: Record<string, string[]> = {
|
||||
events: ["FRONTEND_URL", "APP_BASE_URL", "BACKEND_URL", "NEXT_PUBLIC_API_URL"],
|
||||
accounts: ["ACCOUNTS_URL", "ACCOUNTS_API_URL"],
|
||||
};
|
||||
const NAME = /^[A-Z][A-Z0-9_]*$/;
|
||||
const SECRET = /(SECRET|PASS|TOKEN|PRIVATE|CREDENTIAL|_KEY$|_DSN$|DATABASE_URL|ADMIN_URL)/;
|
||||
|
||||
const FILE_NOTE: Record<string, string> = {
|
||||
"backend/.env": "The backend reads it when it starts: saving restarts it (unless you untick it).",
|
||||
"frontend/.env.production": "Next.js builds these values in: saving rebuilds the frontend (a few minutes), then restarts it.",
|
||||
};
|
||||
|
||||
export function EnvPanel({ deploymentId, product }: { deploymentId: string; product: string }) {
|
||||
const [state, setState] = useState<EnvState | null>(null);
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
// Edits per file: changed values, names to remove, and new variables.
|
||||
const [edits, setEdits] = useState<Record<string, Record<string, string>>>({});
|
||||
const [removed, setRemoved] = useState<Record<string, string[]>>({});
|
||||
const [added, setAdded] = useState<Record<string, { name: string; value: string }>>({});
|
||||
const [restart, setRestart] = useState(true);
|
||||
const [showAll, setShowAll] = useState(false);
|
||||
|
||||
const load = useCallback(() => api<EnvState>(`/api/admin/deployments/${deploymentId}/env`).then(setState).catch(e => setMsg({ type: "err", text: errorText(e) })), [deploymentId]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
// While the agent has a job of ours, look again every few seconds.
|
||||
const waiting = !!state?.pending.length;
|
||||
useEffect(() => {
|
||||
if (!waiting) return;
|
||||
const t = setInterval(load, 4000);
|
||||
return () => clearInterval(t);
|
||||
}, [waiting, load]);
|
||||
|
||||
const run = async (fn: () => Promise<void>) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setMsg(null);
|
||||
try { await fn(); } catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
|
||||
};
|
||||
|
||||
const read = () => run(async () => {
|
||||
await api(`/api/admin/deployments/${deploymentId}/env/read`, { method: "POST" });
|
||||
setMsg({ type: "ok", text: "Asked the agent: the values show here within a minute." });
|
||||
await load();
|
||||
});
|
||||
|
||||
const changesFor = (file: string) => {
|
||||
const set: Record<string, string> = { ...(edits[file] || {}) };
|
||||
const a = added[file];
|
||||
if (a?.name.trim()) set[a.name.trim()] = a.value;
|
||||
return { set, unset: removed[file] || [] };
|
||||
};
|
||||
|
||||
const save = (file: string) => run(async () => {
|
||||
const { set, unset } = changesFor(file);
|
||||
const names = [...Object.keys(set), ...unset];
|
||||
if (!names.length) return;
|
||||
const bad = names.find(n => !NAME.test(n));
|
||||
if (bad) throw new Error(`${bad} isn't a variable name (A-Z, 0-9 and _, starting with a letter).`);
|
||||
const secret = names.find(n => SECRET.test(n));
|
||||
if (secret) throw new Error(`${secret} looks like a secret: change it on the server, not from the Hub.`);
|
||||
const rebuild = file.startsWith("frontend/");
|
||||
const lines = [...Object.entries(set).map(([k, v]) => ` ${k}=${v}`), ...unset.map(n => ` remove ${n}`)].join("\n");
|
||||
const then = rebuild ? "The frontend is then rebuilt and restarted (the site is slow or unavailable for a few minutes)." : restart ? "The backend is then restarted (a few seconds)." : "Nothing is restarted: the new values apply at the next restart.";
|
||||
if (!window.confirm(`Change ${file} on the server?\n\n${lines}\n\n${then} If it doesn't start again, the file is put back as it was.`)) return;
|
||||
await api(`/api/admin/deployments/${deploymentId}/env`, { method: "POST", body: { file, set, unset, restart: rebuild || restart } });
|
||||
setEdits(e => ({ ...e, [file]: {} }));
|
||||
setRemoved(r => ({ ...r, [file]: [] }));
|
||||
setAdded(a => ({ ...a, [file]: { name: "", value: "" } }));
|
||||
setMsg({ type: "ok", text: "Queued: the agent changes the file at its next poll. This panel updates when it's done." });
|
||||
await load();
|
||||
});
|
||||
|
||||
const addresses = useMemo(() => {
|
||||
const names = ADDRESSES[product] || [];
|
||||
const out: { file: string; v: Variable }[] = [];
|
||||
for (const f of state?.env?.files || []) for (const v of f.variables) if (names.includes(v.name)) out.push({ file: f.file, v });
|
||||
return out;
|
||||
}, [state, product]);
|
||||
|
||||
if (!state) return <div className="card"><h2 className="font-medium">Settings (.env)</h2>{msg ? <div className="mt-2"><Message msg={msg} /></div> : <p className="mt-2 text-sm text-slate-400">Loading…</p>}</div>;
|
||||
if (!state.supported) return null;
|
||||
|
||||
const pendingRead = state.pending.find(p => p.type === "env-read");
|
||||
const pendingSet = state.pending.find(p => p.type === "env-set");
|
||||
|
||||
return (
|
||||
<div className="card space-y-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="font-medium">Settings (.env)</h2>
|
||||
<p className="mt-1 text-sm text-slate-500">
|
||||
The values in this install's .env files on the server. Secrets (passwords, keys, the database) are never sent to the Hub: only whether they're set.
|
||||
Needs agent {state.minAgent} or later.
|
||||
</p>
|
||||
</div>
|
||||
<button className="btn-secondary" disabled={busy || !!pendingRead} onClick={read}>{pendingRead ? "Reading…" : state.env ? "Read again" : "Read from the server"}</button>
|
||||
</div>
|
||||
<Message msg={msg} />
|
||||
|
||||
{pendingSet && <p className="rounded-lg border border-indigo-200 bg-indigo-50 p-3 text-sm text-indigo-900">A change is {pendingSet.status === "delivered" ? "being made on the server now" : "waiting for the agent"} (<Link className="underline" href={`/jobs/${pendingSet.id}`}>job</Link>).</p>}
|
||||
{state.lastSet && !pendingSet && state.lastSet.status !== "succeeded" && (
|
||||
<p className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
|
||||
The last change ({fmtDate(state.lastSet.finishedAt)}) {state.lastSet.status === "rolled_back" ? "was put back: the site didn't start with it" : `didn't go through (${state.lastSet.status.replace(/_/g, " ")})`}.
|
||||
{state.lastSet.message ? ` ${state.lastSet.message}` : ""} <Link className="underline" href={`/jobs/${state.lastSet.id}`}>See the job</Link>.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!state.env && !pendingRead && <p className="text-sm text-slate-500">Not read yet. “Read from the server” asks the agent for them.</p>}
|
||||
|
||||
{state.env && (
|
||||
<>
|
||||
<p className="text-xs text-slate-500">Read {ago(state.env.readAt)} ({fmtDate(state.env.readAt)}){state.readJobId && <> · <Link className="underline" href={`/jobs/${state.readJobId}`}>job</Link></>}.</p>
|
||||
|
||||
{!!addresses.length && (
|
||||
<div className="rounded-lg border border-slate-200 bg-slate-50 p-3">
|
||||
<h3 className="text-sm font-medium">Addresses</h3>
|
||||
<dl className="mt-2 grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[max-content_1fr]">
|
||||
{addresses.map(({ file, v }) => (
|
||||
<React.Fragment key={`${file}:${v.name}`}>
|
||||
<dt className="font-mono text-xs text-slate-600">{v.name}<span className="ml-1 text-slate-400">({file.split("/")[0]})</span></dt>
|
||||
<dd className="break-all font-mono text-xs">{v.set ? v.value : <span className="text-amber-700">not set</span>}</dd>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</dl>
|
||||
<p className="mt-2 text-xs text-slate-500">Change them in the files below. The site's address on the Hub ({product}) and in FastPanel doesn't change with them.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={showAll} onChange={e => setShowAll(e.target.checked)} /> Also show variables the file doesn't have yet (from the release's template)</label>
|
||||
|
||||
{state.env.files.map(f => {
|
||||
const fileEdits = edits[f.file] || {};
|
||||
const fileRemoved = removed[f.file] || [];
|
||||
const a = added[f.file] || { name: "", value: "" };
|
||||
const { set, unset } = changesFor(f.file);
|
||||
const count = Object.keys(set).length + unset.length;
|
||||
const rebuild = f.file.startsWith("frontend/");
|
||||
const rows = f.variables.filter(v => showAll || v.set || v.name in fileEdits);
|
||||
return (
|
||||
<form key={f.file} className="space-y-2" onSubmit={e => { e.preventDefault(); save(f.file); }}>
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<h3 className="font-mono text-sm font-medium">{f.file}{!f.exists && <span className="ml-2 font-sans text-xs text-amber-700">missing on the server</span>}</h3>
|
||||
<span className="text-xs text-slate-500">{FILE_NOTE[f.file]}</span>
|
||||
</div>
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full text-sm">
|
||||
<thead><tr className="bg-slate-50 text-left text-xs text-slate-500"><th className="px-3 py-1.5">Name</th><th className="px-3 py-1.5">Value</th><th className="px-3 py-1.5"><span className="sr-only">Remove</span></th></tr></thead>
|
||||
<tbody>
|
||||
{rows.map(v => {
|
||||
const isRemoved = fileRemoved.includes(v.name);
|
||||
const value = v.name in fileEdits ? fileEdits[v.name] : (v.value ?? "");
|
||||
const changed = v.name in fileEdits && fileEdits[v.name] !== (v.value ?? "");
|
||||
return (
|
||||
<tr key={v.name} className={`border-t align-top ${isRemoved ? "opacity-50" : ""}`}>
|
||||
<td className="px-3 py-1.5">
|
||||
<div className="font-mono text-xs">{v.name}</div>
|
||||
{(v.description || v.layer) && <div className="text-[11px] text-slate-400">{[v.layer, v.description].filter(Boolean).join(" · ")}</div>}
|
||||
</td>
|
||||
<td className="w-full px-3 py-1.5">
|
||||
{v.secret ? (
|
||||
<span className="text-xs text-slate-500">{v.set ? "•••••••• (secret, set)" : "secret, not set"}</span>
|
||||
) : v.editable ? (
|
||||
<input className={`input py-1 font-mono text-xs ${changed ? "border-indigo-400 bg-indigo-50" : ""}`} aria-label={v.name} value={value} disabled={isRemoved || !!pendingSet}
|
||||
placeholder={v.set ? "" : "not set"}
|
||||
onChange={e => {
|
||||
const next = e.target.value;
|
||||
setEdits(x => {
|
||||
const fe = { ...(x[f.file] || {}) };
|
||||
if (next === (v.value ?? "")) delete fe[v.name]; else fe[v.name] = next;
|
||||
return { ...x, [f.file]: fe };
|
||||
});
|
||||
}} />
|
||||
) : (
|
||||
<span className="font-mono text-xs text-slate-600">{v.value}<span className="ml-2 font-sans text-[11px] text-slate-400">made by the server</span></span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-1.5 text-right">
|
||||
{v.editable && v.set && (
|
||||
<button type="button" className="text-xs text-slate-500 underline" disabled={!!pendingSet} onClick={() => setRemoved(r => {
|
||||
const list = r[f.file] || [];
|
||||
return { ...r, [f.file]: isRemoved ? list.filter(n => n !== v.name) : [...list, v.name] };
|
||||
})}>{isRemoved ? "keep" : "remove"}</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
<tr className="border-t bg-slate-50/50">
|
||||
<td className="px-3 py-1.5"><input className="input py-1 font-mono text-xs" aria-label={`New variable name in ${f.file}`} placeholder="NEW_NAME" value={a.name} disabled={!!pendingSet}
|
||||
onChange={e => setAdded(x => ({ ...x, [f.file]: { ...a, name: e.target.value.toUpperCase() } }))} /></td>
|
||||
<td className="px-3 py-1.5" colSpan={2}><input className="input py-1 font-mono text-xs" aria-label={`New variable value in ${f.file}`} placeholder="value" value={a.value} disabled={!!pendingSet}
|
||||
onChange={e => setAdded(x => ({ ...x, [f.file]: { ...a, value: e.target.value } }))} /></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button className="btn-primary" disabled={busy || !count || !!pendingSet}>{rebuild ? "Save, rebuild and restart" : restart ? "Save and restart" : "Save"}{count ? ` (${count})` : ""}</button>
|
||||
{!rebuild && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={restart} onChange={e => setRestart(e.target.checked)} /> Restart the backend to apply it</label>}
|
||||
{!!count && <button type="button" className="text-sm text-slate-500 underline" onClick={() => { setEdits(x => ({ ...x, [f.file]: {} })); setRemoved(x => ({ ...x, [f.file]: [] })); setAdded(x => ({ ...x, [f.file]: { name: "", value: "" } })); }}>Undo my changes</button>}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user