diff --git a/CLAUDE.md b/CLAUDE.md index e3c57c3..0d7ffae 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,8 +2,9 @@ FastAPI backend (`src/databases_ui`) serving a React/TypeScript console (`frontend/`), and the Jobs' runner (`runner.py`) in the same image, with a Helm chart (`charts/databases-ui`). State lives in -Kubernetes (Database resources, Jobs, RBAC) and Blob Storage (snapshots and their shares, the audit -log); the server stores nothing. +Kubernetes (Database resources, Jobs, RBAC) and Blob Storage (snapshots and their shares, scripts, +the audit log); the server stores nothing. External databases (not CloudNativePG) are the +catalog's `external` entries; scripts are `sql.py` (what may run) and `runner.script`. ## Things that fail silently @@ -33,6 +34,19 @@ log); the server stores nothing. postponed annotations turn them into strings and FastAPI answers 422 everywhere. - **The page may hold no inline script or style.** The CSP blocks it and the page renders blank; CI greps `frontend/dist/index.html` for it. +- **The admission policy pins an external database's host, port, TLS mode and password Secret + from the rendered catalog** (`templates/jobpolicy.yaml`). A catalog in `existingConfigMap` isn't + rendered, so its external databases' Jobs are refused; a new Job variable that names another + host or Secret needs the policy changed in the same change. +- **A script's output reaches the server through the pod's termination message**, which Kubernetes + caps at 4096 bytes. `runner.termination_message` trims the output, never the JSON; writing it any + other way truncates mid-string and the server shows the raw text as the failure reason. +- **A script travels in the Job (`DBUI_SCRIPT`), and a single environment variable is capped near + 128 kB by Linux** (`MAX_ARG_STRLEN`), so `sql.MAX_BYTES` stays at 100 kB. Moving the script to a + volume means the admission policy's volume rule changes too. +- **`sql.problems` is the only thing between a script and psql's backslash commands** (`\!` runs a + shell in the Job's pod). Keep it a lexer: quoted strings, dollar quotes, comments and BEGIN + ATOMIC bodies must be skipped, or ordinary function bodies get refused. - **The image name follows the repository name** (`ghcr.io/magmamoose/databases-ui`). The chart's default image is that name, and the Jobs run the same image; a rename means a chart change in the same PR. diff --git a/README.md b/README.md index 2615457..b8314d3 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,16 @@ # databases-ui Let app teams snapshot, restore and clone their own PostgreSQL databases on -[CloudNativePG](https://cloudnative-pg.io/), without asking the platform team. People sign in with -Entra ID and see the databases of the namespaces Kubernetes lets them into; every action runs as a -Kubernetes Job next to the database. - -- **Access is Kubernetes RBAC.** A `Database` resource names its app's namespace in a label. Who - may see it, snapshot it or restore it is what the API server says that person may do in that - namespace, asked with a SubjectAccessReview: `view` sees, `edit` snapshots and restores, `admin` - restores production. There is no second list of who may do what. +[CloudNativePG](https://cloudnative-pg.io/), and run their migration scripts on them or on any other +PostgreSQL, without asking the platform team. People sign in with Entra ID and see the databases of +the namespaces Kubernetes lets them into; every action runs as a Kubernetes Job next to the +database. + +- **Access is Kubernetes RBAC.** A `Database` resource names its app's namespace in a label (an + external database, in the catalog). Who may see it, snapshot it, restore it or run a script on it + is what the API server says that person may do in that namespace, asked with a + SubjectAccessReview: `view` sees, `edit` snapshots, restores and runs scripts, `admin` restores + and runs scripts in production. There is no second list of who may do what. - **Snapshots on demand.** `pg_dump` in the custom format, streamed straight into Azure Blob Storage with who took it and why. Nothing touches a disk, and nothing leaves the cluster. - **Restore in place or into a copy, exactly.** In one transaction, everything the database's owner @@ -18,8 +20,14 @@ Kubernetes Job next to the database. by CloudNativePG. - **Clone across environments, once shared.** Someone who may snapshot a database in acc shares a snapshot with a namespace in dev; whoever may restore there can then clone it. -- **Production is careful.** A restore in a production environment waits for a second person, and - snapshots taken there can't be downloaded. +- **Scripts, checked or run.** Paste or open a `.sql` file: it runs as the database's owner in one + transaction. A check runs it, shows what it said and rolls back; a run commits, after a snapshot + if asked. One failing statement, or a lock it can't get within 15 seconds, changes nothing. +- **Any PostgreSQL.** A server outside CloudNativePG goes in the catalog with its host, a login and + that login's password Secret: it is listed, snapshotted and scripted like the others. +- **Production is careful.** A restore or a script in a production environment waits for a second + person, who reads the script before approving it; snapshots taken there can't be downloaded, + and a script's output there names its statements but shows no rows. - **Database users**: the owner roles of the databases you see, and the Secrets with their passwords. - **An audit log** of who asked for what, who approved it and how it ended, per environment. @@ -135,6 +143,61 @@ Without the label, a database belongs to its own namespace (`database`): only wh usually the platform team, sees it. Without the annotation, a restore in place scales nothing; the owner's other sessions are still ended first. +## External databases + +A PostgreSQL server that isn't a CloudNativePG `Database` (a VM, a managed service, another +operator's cluster) goes under its environment's `external` in the catalog: + +```yaml +environments: + - name: acc + storage: + url: https://.blob.core.windows.net/acc-snapshots + external: + - name: billing # what this app calls it, unique in the environment + namespace: acc-billing # whose people may act on it; empty: the environment's own + host: billing-db.example.internal + port: 5432 # the default + database: billing # the database on that server + user: billing_owner # the login the Jobs use + passwordSecret: billing-db # a Secret in the environment's namespace, key `password` + caSecret: billing-db-ca # its `ca.crt` verifies the server + tls: verify-full # the default; or require, or disable +``` + +- **The login is what a script can do.** Give the Jobs the schema's owner, as migration scripts + need, not a superuser: a superuser's script can do anything to the server. +- **`verify-full` without a `caSecret`** checks the certificate against the image's public roots + (`sslrootcert=system`), for a server with a public certificate. `require` encrypts without + checking who answers; `disable` is for a server without TLS on a network you trust. +- **No restores.** A restore drops everything its login owns first, which on a server this app + doesn't manage could be anything. Its snapshots are ordinary `pg_dump` archives: download one + outside production, or restore it by hand. +- **The Jobs must reach it.** If the namespace's NetworkPolicies limit egress, admit the Jobs' pods + (`app.kubernetes.io/component: job`) to the server's address and port. The admission policy + admits exactly the catalog's host, port, TLS mode and password Secret, so the catalog has to be + in the chart's values (`catalog.content` or `catalog.text`). + +## What a script does + +- **One transaction, every statement or none.** `psql` runs `BEGIN`, `SET LOCAL lock_timeout = + '15s'`, the script with `ON_ERROR_STOP`, then `COMMIT` (run) or `ROLLBACK` (check). At the first + error psql stops before either and PostgreSQL rolls everything back, so a check shows exactly + what a run would do. +- **No BEGIN, COMMIT or psql commands.** A script that opens or ends a transaction of its own, or + holds a backslash command (`\!`, `\connect`, `\o`), is refused before a Job exists, with the + line. Statements that can't run in a transaction (`CREATE INDEX CONCURRENTLY`, `VACUUM`) fail. +- **A lock it can't get within 15 seconds fails the script**, rather than queueing the app's own + queries behind an `ALTER TABLE` that waits for a long one. +- **A snapshot first, when asked.** A run can take a snapshot before it starts; if the snapshot + fails, the script doesn't run. +- **What it said.** The last lines of psql's output (statement tags, notices, errors with the + script's line numbers, and rows outside production) show under Activity. The script itself is + kept beside the snapshots (`scripts//.sql`) and in the Job, with its sha256 in the + audit log. +- **In production, a second person reads it first.** The request waits, suspended; whoever approves + sees the script the Job holds, which can't change after it is created. + ## What a restore does - **One transaction, the snapshot exactly.** `psql` runs `BEGIN`, `DROP OWNED BY CURRENT_USER`, then @@ -257,9 +320,13 @@ and a Job's work. the reviews ask about nobody and refuse everything. - **No passwords in the server.** It reads no Secret; a Job's pod gets the owner's password from the kubelet, and the admission policy keeps the server's Jobs to what it builds. -- **A production restore takes two people.** It is created suspended and starts only when someone - else who may restore there approves it; a Job's pod template can't change after creation, so - what runs is what was asked for. Unapproved requests expire after a day. +- **A production restore or script takes two people.** It is created suspended and starts only when + someone else who may restore (or run scripts) there approves it; a Job's pod template can't + change after creation, so what runs is what was asked for. Unapproved requests expire after a + day. +- **A script runs as the database's owner, never as a superuser the app chose.** For an external + database the catalog names the login, and the admission policy holds a script Job to that host, + port, TLS mode and password Secret. - **Data leaves an environment only when someone who may snapshot it says so**: a share names one namespace in one environment, and is in the audit log. Downloads, outside production only, stream through the server and are recorded too. diff --git a/charts/databases-ui/Chart.yaml b/charts/databases-ui/Chart.yaml index 9609bbc..e83c8a7 100644 --- a/charts/databases-ui/Chart.yaml +++ b/charts/databases-ui/Chart.yaml @@ -1,6 +1,6 @@ apiVersion: v2 name: databases-ui -description: Let app teams snapshot, restore and clone their own PostgreSQL databases on CloudNativePG, with Entra ID sign-in, Kubernetes Jobs and Azure Blob Storage. +description: Let app teams snapshot, restore and clone their own PostgreSQL databases on CloudNativePG, and run migration scripts on them or any other PostgreSQL, with Entra ID sign-in, Kubernetes Jobs and Azure Blob Storage. type: application # version is the CHART version and appVersion the application version. The release @@ -33,4 +33,6 @@ annotations: url: https://github.com/MagmaMoose/databases-ui artifacthub.io/changes: | - kind: added - description: First release. + description: Scripts, checked (rolled back) or run (committed, after a snapshot if asked), with a second person in production. + - kind: added + description: External databases, any PostgreSQL the catalog names, for snapshots and scripts. diff --git a/charts/databases-ui/ci/default-values.yaml b/charts/databases-ui/ci/default-values.yaml index c112995..5759499 100644 --- a/charts/databases-ui/ci/default-values.yaml +++ b/charts/databases-ui/ci/default-values.yaml @@ -16,6 +16,21 @@ catalog: storage: url: https://examplesnapshots.blob.core.windows.net/dev cloneFrom: [acc] + external: + - name: ledger + namespace: dev-ledger + host: ledger-db.example.internal + database: ledger + user: ledger_owner + passwordSecret: ledger-db + caSecret: ledger-db-ca + - name: archive + host: 10.20.30.40 + port: 6432 + database: archive + user: archive_owner + passwordSecret: archive-db + tls: require - name: acc kubernetes: none storage: diff --git a/charts/databases-ui/templates/jobpolicy.yaml b/charts/databases-ui/templates/jobpolicy.yaml index 47573f9..8d485ac 100644 --- a/charts/databases-ui/templates/jobpolicy.yaml +++ b/charts/databases-ui/templates/jobpolicy.yaml @@ -1,12 +1,18 @@ {{- if .Values.jobPolicy.enabled }} {{- $urls := list }} +{{- $servers := list }} {{- range (default list (fromYaml (include "databases-ui.catalogContent" .)).environments) }} {{- $urls = append $urls (printf "%q" (trimSuffix "/" .storage.url)) }} +{{- range (default list .external) }} +{{- $servers = append $servers . }} +{{- end }} {{- end }} # Creating Jobs in a namespace is, to Kubernetes, reading every Secret there. This keeps the Jobs # this app creates to what it builds itself: its own image as `job`, one owner's password (never # a superuser's), the server's CA certificate and no other Secret, TLS to a database in the Job's -# own namespace, and the catalog's storage. +# own namespace or an external database exactly as the catalog has it (host, port, TLS and its +# own password Secret), and the catalog's storage. External databases are known here only when +# the catalog is in the values (catalog.content or catalog.text), not catalog.existingConfigMap. apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: @@ -55,9 +61,16 @@ spec: ))) message: databases-ui Jobs read one owner's password from its Secret, never a superuser's - expression: >- - variables.env.exists(e, e.name == "PGSSLMODE" && e.value == "verify-full") - && variables.env.all(e, e.name != "PGHOST" || (has(e.value) && e.value.matches("^[a-z0-9-]+-rw[.]" + request.namespace + "[.]svc$"))) - message: databases-ui Jobs connect over verified TLS to a database in their own namespace + variables.env.filter(e, e.name == "PGHOST").size() == 1 && variables.env.exists(e, e.name == "PGHOST" && has(e.value) && ( + (e.value.matches("^[a-z0-9-]+-rw[.]" + request.namespace + "[.]svc$") && variables.env.exists(m, m.name == "PGSSLMODE" && m.value == "verify-full")) + {{- range $servers }} + || (e.value == {{ .host | quote }} + && variables.env.exists(m, m.name == "PGSSLMODE" && m.value == {{ default "verify-full" .tls | quote }}) + && variables.env.exists(m, m.name == "PGPORT" && m.value == {{ default 5432 .port | toString | quote }}) + && variables.env.exists(m, m.name == "PGPASSWORD" && has(m.valueFrom) && has(m.valueFrom.secretKeyRef) && m.valueFrom.secretKeyRef.name == {{ .passwordSecret | quote }})) + {{- end }} + )) + message: databases-ui Jobs connect over verified TLS to a database in their own namespace, or to an external database exactly as the catalog has it {{- if $urls }} - expression: >- variables.env.all(e, !(e.name in ["DBUI_BLOB_URL", "DBUI_AUDIT_URL"]) || (has(e.value) && e.value in [{{ join ", " $urls }}])) diff --git a/charts/databases-ui/values.yaml b/charts/databases-ui/values.yaml index ba15569..5f761f3 100644 --- a/charts/databases-ui/values.yaml +++ b/charts/databases-ui/values.yaml @@ -58,7 +58,8 @@ config: # The environments (see the README). Rendered into a ConfigMap from `content`, a map here, or from # `text`, the file as it is (--set-file catalog.text=catalog.yaml); or read from your own ConfigMap -# in the release namespace. +# in the release namespace. An environment's `external` databases need content or text: the Jobs' +# admission policy admits their hosts from the rendered catalog, and refuses them otherwise. catalog: existingConfigMap: "" key: catalog.yaml diff --git a/examples/catalog.yaml b/examples/catalog.yaml index 5120930..7b02f40 100644 --- a/examples/catalog.yaml +++ b/examples/catalog.yaml @@ -8,6 +8,17 @@ environments: url: https://examplesnapshots.blob.core.windows.net/dev # Snapshots tst and acc share with a namespace here can be cloned into it. cloneFrom: [tst, acc] + # PostgreSQL servers outside CloudNativePG: snapshots and scripts here, restores elsewhere. + # The Jobs log in as user, with the password in passwordSecret (key password) in this + # environment's namespace: the schema's owner, not a superuser. + external: + - name: billing + namespace: dev-billing + host: billing-db.example.internal + database: billing + user: billing_owner + passwordSecret: billing-db + caSecret: billing-db-ca - name: tst kubernetes: none storage: diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index c15c2ce..d8453ac 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -89,7 +89,7 @@ export function App() {

Databases UI

-

{state === "ended" ? "Your session has ended." : "Sign in with your work account to snapshot, restore and clone the databases of your namespaces."}

+

{state === "ended" ? "Your session has ended." : "Sign in with your work account to snapshot, restore and clone the databases of your namespaces, and run scripts on them."}

{authError && (

{authError} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index c84c54b..2b12a29 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -18,18 +18,23 @@ export type Me = { export type Database = { name: string; + // cloudnativepg: a Database resource. external: a server the catalog names. + kind: "cloudnativepg" | "external"; namespace: string; owner: string; owner_secret: string; ready: boolean; message: string; + server: { host: string; port: number; database: string; tls: string } | null; workloads: string[]; copy: { name: string; ready: boolean } | null; can_snapshot: boolean; can_restore: boolean; + can_script: boolean; }; -export type User = { name: string; managed: boolean; login: boolean; secret: string; databases: string[]; namespaces: string[] }; +// `server` is host:port/database for an external database's login, empty for a managed role. +export type User = { name: string; managed: boolean; login: boolean; secret: string; databases: string[]; namespaces: string[]; server: string }; export type Snapshot = { environment: string; @@ -47,7 +52,7 @@ export type JobState = "waiting" | "starting" | "running" | "succeeded" | "faile export type Job = { name: string; - action: "snapshot" | "restore"; + action: "snapshot" | "restore" | "script"; database: string; namespace: string; state: JobState; @@ -63,17 +68,24 @@ export type Job = { into: "" | "database" | "copy"; target_database: string; approval: string; + // A script's: check or run, its id, its sha256 and the script itself, as the Job holds it. + mode: "" | "check" | "run"; + script: string; + script_sha256: string; + script_text: string; started: string; finished: string; - result: { result?: string; bytes?: number; seconds?: number; reason?: string }; + result: { result?: string; bytes?: number; seconds?: number; reason?: string; mode?: string; output?: string }; can_approve: boolean; can_decline: boolean; }; -export type AuditEntry = { at: string; environment: string; actor: string; action: string; database?: string; namespace?: string; job?: string; snapshot?: string; target?: string; detail?: string }; +export type AuditEntry = { at: string; environment: string; actor: string; action: string; database?: string; namespace?: string; job?: string; snapshot?: string; script?: string; target?: string; detail?: string }; export type RestoreRequest = { source_environment: string; source_database: string; snapshot: string; into: "database" | "copy"; reason: string }; +export type ScriptRequest = { script: string; mode: "check" | "run"; reason: string; snapshot: boolean }; + export class ApiError extends Error { constructor( readonly status: number, @@ -128,6 +140,7 @@ export const api = { snapshots: (e: string, d: string) => request<{ snapshots: Snapshot[] }>("GET", `${db(e, d)}/snapshots`).then((r) => r.snapshots), snapshot: (e: string, d: string, note: string) => request("POST", `${db(e, d)}/snapshots`, { note }), restore: (e: string, d: string, body: RestoreRequest) => request("POST", `${db(e, d)}/restore`, body), + script: (e: string, d: string, body: ScriptRequest) => request("POST", `${db(e, d)}/scripts`, body), shared: (e: string, d: string) => request<{ snapshots: Snapshot[] }>("GET", `${db(e, d)}/shared`).then((r) => r.snapshots), share: (e: string, d: string, id: string, target: { environment: string; namespace: string }) => request("POST", `${db(e, d)}/snapshots/${encodeURIComponent(id)}/share`, target), diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 19ce240..159d768 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -578,6 +578,11 @@ input[aria-invalid="true"] { margin: 4px -20px -18px; } +/* A footer beside the body, not inside it, sits at the dialog's edge as it is. */ +.form > .dialog-footer { + margin: 0; +} + .form { display: grid; gap: 14px; @@ -861,3 +866,72 @@ tr.muted td { flex: 1; text-align: left; } + +/* Scripts: the dialog's editor, and what a script said, under Activity. */ +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +.label-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.file-button { + cursor: pointer; +} + +.file-button:focus-within { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +textarea.script { + min-height: 180px; + font-size: 13px; + line-height: 1.5; + tab-size: 4; +} + +.form .check { + display: flex; + align-items: center; + gap: 8px; +} + +.form .check input { + width: auto; + min-height: 0; +} + +.script-details { + margin-top: 6px; +} + +.script-details summary { + cursor: pointer; + color: var(--accent); + font-size: 12px; +} + +.output { + margin: 6px 0 0; + padding: 10px 12px; + max-height: 320px; + overflow: auto; + white-space: pre-wrap; + overflow-wrap: anywhere; + font-family: var(--mono); + font-size: 12px; + line-height: 1.5; + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: var(--radius); +} diff --git a/frontend/src/views/Activity.tsx b/frontend/src/views/Activity.tsx index 7cb44f3..0461a9b 100644 --- a/frontend/src/views/Activity.tsx +++ b/frontend/src/views/Activity.tsx @@ -7,6 +7,7 @@ import { bytes, duration, when } from "../format"; function what(job: Job, env: string): string { if (job.action === "snapshot") return "Snapshot"; + if (job.action === "script") return job.mode === "check" ? "Check a script" : job.snapshot ? "Run a script, after a snapshot" : "Run a script"; const from = job.source_environment && job.source_environment !== env ? `Clone from ${job.source_environment}/${job.source_database}` : "Restore"; return job.into === "copy" ? `${from} into ${job.target_database}` : from; } @@ -43,7 +44,7 @@ export function Activity({ env }: { env: Environment }) { <>

Activity in {env.name}

-

Snapshots and restores of the last week. {env.production && "A restore here starts once a second person approves it."}

+

Snapshots, restores and scripts of the last week. {env.production && "A restore or a script here starts once a second person approves it."}

+ {j.script_text && ( + // Open while it waits: whoever approves it reads what will run. +
+ The script{j.script_sha256 && · sha256 {j.script_sha256.slice(0, 12)}} +
{j.script_text}
+
+ )} {j.database} @@ -87,7 +95,7 @@ export function Activity({ env }: { env: Environment }) { {(j.can_approve || j.can_decline) && (
{j.can_approve && ( - )} @@ -101,12 +109,25 @@ export function Activity({ env }: { env: Environment }) { {j.result.result === "succeeded" ? ( - <> - {bytes(j.result.bytes)} in {duration(j.result.seconds)} - + j.action === "script" ? ( + <> + {j.result.mode === "check" ? "Checked, rolled back" : "Committed"} in {duration(j.result.seconds)} + {j.result.bytes ? `, after a snapshot of ${bytes(j.result.bytes)}` : ""} + + ) : ( + <> + {bytes(j.result.bytes)} in {duration(j.result.seconds)} + + ) ) : ( j.result.reason && {j.result.reason} )} + {j.result.output && ( +
+ Output +
{j.result.output}
+
+ )} ))} @@ -115,7 +136,7 @@ export function Activity({ env }: { env: Environment }) { )} {declining && (

{db.name}

- {env.name} · namespace {db.namespace} · owned by {db.owner} + {env.name} · namespace {db.namespace} · {db.server ? "as" : "owned by"} {db.owner} {db.owner_secret && ( <> {" "} (password in Secret {db.owner_secret}) )} + {db.server && ( + <> + {" "} + · external, {`${db.server.host}:${db.server.port}/${db.server.database}`} + + )}

- {(db.can_snapshot || db.can_restore) && ( + {(db.can_snapshot || db.can_restore || db.can_script) && (
{db.can_snapshot && ( )} + {db.can_script && ( + + )} {db.can_restore && (
{!db.ready &&

CloudNativePG has not applied this database: {db.message || "no reason given"}.

} + {db.server && ( +

+ An external database: snapshots and scripts run here as {db.owner}. Restoring one of its snapshots happens outside this app. +

+ )} {db.copy && (

A copy, {db.copy.name}, holds a restored snapshot{db.copy.ready ? "" : " (being created)"}.{" "} @@ -146,6 +162,18 @@ export function DatabaseView({ env, name }: { env: Environment; name: string }) }} /> )} + {dialog?.kind === "script" && ( + setDialog(null)} + onDone={(waiting, mode) => { + setDialog(null); + notify(waiting ? "The script waits for a second person to approve it." : mode === "check" ? "Checking the script; its output shows under Activity." : "The script is running; its output shows under Activity."); + go(`/${env.name}/activity`); + }} + /> + )} {dialog?.kind === "restore" && ( void; onDone: (waiting: boolean, mode: "check" | "run") => void }) { + const [script, setScript] = useState(""); + const [mode, setMode] = useState<"check" | "run">("check"); + const [snapshot, setSnapshot] = useState(true); + const [reason, setReason] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const ready = script.trim() !== "" && reason.trim().length >= 3; + + async function load(file: File | undefined) { + if (!file) return; + if (file.size > 100_000) { + setError(`${file.name} is over 100 kB; split it.`); + return; + } + setError(""); + setScript(await file.text()); + } + + async function submit(e: FormEvent) { + e.preventDefault(); + setBusy(true); + setError(""); + try { + const job = await api.script(env.name, db.name, { script, mode, reason: reason.trim(), snapshot: mode === "run" && snapshot }); + onDone(job.state === "waiting", mode); + } catch (err) { + setError(message(err)); + setBusy(false); + } + } + + return ( +

+
void submit(e)}> +
+
+
+ + +
+