|
@@ -0,0 +1,391 @@
|
|
|
|
|
+import { useState } from 'react'
|
|
|
|
|
+import { useQuery, useQueryClient } from '@tanstack/react-query'
|
|
|
|
|
+import { useNavigate } from 'react-router-dom'
|
|
|
|
|
+import { FileJson, Wand2, Trash2, AlertTriangle, ShieldAlert, Check } from 'lucide-react'
|
|
|
|
|
+import { api } from '@/api/client'
|
|
|
|
|
+import { JsonEditor } from '@/components/JsonEditor'
|
|
|
|
|
+import { ApiError } from '@/types'
|
|
|
|
|
+import type { SchemaMode, SchemaRowViolation } from '@/types'
|
|
|
|
|
+import { useToastStore } from '@/stores/toastStore'
|
|
|
|
|
+
|
|
|
|
|
+/// The optional per-collection JSON Schema (database 2.16.0+).
|
|
|
|
|
+///
|
|
|
|
|
+/// Three things in here are deliberate rather than incidental:
|
|
|
|
|
+///
|
|
|
|
|
+/// 1. `hasSchema === undefined` means the DATABASE has no schema support at
|
|
|
|
|
+/// all, which is a different statement from "this collection has no
|
|
|
|
|
+/// schema". The panel renders nothing in that case rather than offering a
|
|
|
|
|
+/// control that would answer 501 - but it says so when expanded from the
|
|
|
|
|
+/// collection, instead of silently disappearing.
|
|
|
|
|
+/// 2. Suggest PREFILLS the editor and never applies. The server refuses to
|
|
|
|
|
+/// apply a suggestion too (`applied: false`), because lengths and ranges
|
|
|
|
|
+/// are described rather than enforced, so arming one unseen would create
|
|
|
|
|
+/// something that looks stricter than what it checks.
|
|
|
|
|
+/// 3. A refused enforce shows the violating document ids as LINKS into
|
|
|
|
|
+/// Documents. The Documents page keeps `collection` and `open` in the URL,
|
|
|
|
|
+/// so "which row broke this" is one click rather than a copied id.
|
|
|
|
|
+export function SchemaPanel({
|
|
|
|
|
+ project,
|
|
|
|
|
+ collection,
|
|
|
|
|
+ hasSchema,
|
|
|
|
|
+}: {
|
|
|
|
|
+ project: string
|
|
|
|
|
+ collection: string
|
|
|
|
|
+ /// undefined = this database has no collection schemas (pre-2.16.0)
|
|
|
|
|
+ hasSchema?: boolean
|
|
|
|
|
+}) {
|
|
|
|
|
+ const push = useToastStore((s) => s.push)
|
|
|
|
|
+ const queryClient = useQueryClient()
|
|
|
|
|
+ const navigate = useNavigate()
|
|
|
|
|
+
|
|
|
|
|
+ const [draft, setDraft] = useState<string>('')
|
|
|
|
|
+ const [editing, setEditing] = useState(false)
|
|
|
|
|
+ const [valid, setValid] = useState(true)
|
|
|
|
|
+ const [mode, setMode] = useState<SchemaMode | ''>('')
|
|
|
|
|
+ const [busy, setBusy] = useState(false)
|
|
|
|
|
+ // The counts and examples from the last refused or audited change. Kept in
|
|
|
|
|
+ // state rather than shown as a toast: a list of ten document ids is
|
|
|
|
|
+ // something an operator reads and clicks, not something that should vanish.
|
|
|
|
|
+ const [violations, setViolations] = useState<{
|
|
|
|
|
+ rowsChecked: number
|
|
|
|
|
+ violatingRows: number
|
|
|
|
|
+ examples: SchemaRowViolation[]
|
|
|
|
|
+ refused: boolean
|
|
|
|
|
+ } | null>(null)
|
|
|
|
|
+
|
|
|
|
|
+ // A pre-2.16.0 database cannot answer any of these routes, so do not ask.
|
|
|
|
|
+ const supported = hasSchema !== undefined
|
|
|
|
|
+
|
|
|
|
|
+ const { data, isLoading } = useQuery({
|
|
|
|
|
+ queryKey: ['collection-schema', project, collection],
|
|
|
|
|
+ queryFn: async () => {
|
|
|
|
|
+ try {
|
|
|
|
|
+ return await api.getCollectionSchema(project, collection)
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ // 404 `no_schema` is the ordinary "none set" answer, not a failure.
|
|
|
|
|
+ if (e instanceof ApiError && e.code === 'no_schema') return null
|
|
|
|
|
+ throw e
|
|
|
|
|
+ }
|
|
|
|
|
+ },
|
|
|
|
|
+ // Only ASK when the collection GET already said there is one. `has_schema`
|
|
|
|
|
+ // is on that response, so fetching to be told 404 is both a wasted round
|
|
|
|
|
+ // trip and a red entry in the browser console on every schema-less
|
|
|
|
|
+ // collection - noise a developer will eventually chase. The 404 branch
|
|
|
|
|
+ // above stays as the belt-and-braces path for a stale `has_schema` (set
|
|
|
|
|
+ // elsewhere, or removed between the two calls).
|
|
|
|
|
+ enabled: supported && hasSchema === true,
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ if (!supported) return null
|
|
|
|
|
+
|
|
|
|
|
+ function describe(e: unknown): string {
|
|
|
|
|
+ return e instanceof ApiError ? e.message : 'Request failed'
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /// Pull the counts out of a refusal so they can be rendered rather than
|
|
|
|
|
+ /// flattened into a toast message.
|
|
|
|
|
+ function captureViolations(e: unknown, refused: boolean) {
|
|
|
|
|
+ if (!(e instanceof ApiError) || e.code !== 'schema_violation') return false
|
|
|
|
|
+ const d = (e.details ?? {}) as {
|
|
|
|
|
+ rows_checked?: number
|
|
|
|
|
+ violating_rows?: number
|
|
|
|
|
+ examples?: SchemaRowViolation[]
|
|
|
|
|
+ }
|
|
|
|
|
+ setViolations({
|
|
|
|
|
+ rowsChecked: d.rows_checked ?? 0,
|
|
|
|
|
+ violatingRows: d.violating_rows ?? 0,
|
|
|
|
|
+ examples: d.examples ?? [],
|
|
|
|
|
+ refused,
|
|
|
|
|
+ })
|
|
|
|
|
+ return true
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async function suggest() {
|
|
|
|
|
+ setBusy(true)
|
|
|
|
|
+ try {
|
|
|
|
|
+ const s = await api.suggestCollectionSchema(project, collection)
|
|
|
|
|
+ setDraft(JSON.stringify(s.schema, null, 2))
|
|
|
|
|
+ setEditing(true)
|
|
|
|
|
+ setViolations(null)
|
|
|
|
|
+ // Said out loud, because the whole risk of this button is someone
|
|
|
|
|
+ // believing it applied something.
|
|
|
|
|
+ push(
|
|
|
|
|
+ s.complete
|
|
|
|
|
+ ? `Suggested from ${s.rows_scanned.toLocaleString()} row(s). Nothing has been applied - review it and save.`
|
|
|
|
|
+ : `Suggested from a SAMPLE of ${s.rows_scanned.toLocaleString()} row(s), so a field absent here may still exist. Nothing applied.`,
|
|
|
|
|
+ 'info',
|
|
|
|
|
+ )
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ push(describe(e), 'error')
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ setBusy(false)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async function save() {
|
|
|
|
|
+ let parsed: unknown
|
|
|
|
|
+ try {
|
|
|
|
|
+ parsed = JSON.parse(draft)
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ push('The schema is not valid JSON.', 'error')
|
|
|
|
|
+ return
|
|
|
|
|
+ }
|
|
|
|
|
+ setBusy(true)
|
|
|
|
|
+ setViolations(null)
|
|
|
|
|
+ try {
|
|
|
|
|
+ const r = await api.setCollectionSchema(project, collection, parsed, mode || undefined)
|
|
|
|
|
+ // violating_rows above zero on SUCCESS means audit mode armed the schema
|
|
|
|
|
+ // over data that does not conform. That is the point of audit and it is
|
|
|
|
|
+ // invisible if only failures are reported, so it is surfaced here too.
|
|
|
|
|
+ if (r.violating_rows > 0) {
|
|
|
|
|
+ setViolations({
|
|
|
|
|
+ rowsChecked: r.rows_checked,
|
|
|
|
|
+ violatingRows: r.violating_rows,
|
|
|
|
|
+ examples: r.examples ?? [],
|
|
|
|
|
+ refused: false,
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+ const how = r.mode_defaulted ? ` (${r.mode} chosen for you)` : ''
|
|
|
|
|
+ push(`Schema saved in ${r.mode} mode${how}.`, 'success')
|
|
|
|
|
+ setEditing(false)
|
|
|
|
|
+ await queryClient.invalidateQueries({ queryKey: ['collection-schema', project, collection] })
|
|
|
|
|
+ await queryClient.invalidateQueries({ queryKey: ['collection', project, collection] })
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ if (captureViolations(e, true)) {
|
|
|
|
|
+ push('Refused: existing rows do not satisfy this schema. See the list below.', 'error')
|
|
|
|
|
+ } else {
|
|
|
|
|
+ push(describe(e), 'error')
|
|
|
|
|
+ }
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ setBusy(false)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async function remove() {
|
|
|
|
|
+ setBusy(true)
|
|
|
|
|
+ try {
|
|
|
|
|
+ await api.removeCollectionSchema(project, collection)
|
|
|
|
|
+ push('Schema removed. Writes are no longer validated.', 'success')
|
|
|
|
|
+ setEditing(false)
|
|
|
|
|
+ setDraft('')
|
|
|
|
|
+ setViolations(null)
|
|
|
|
|
+ await queryClient.invalidateQueries({ queryKey: ['collection-schema', project, collection] })
|
|
|
|
|
+ await queryClient.invalidateQueries({ queryKey: ['collection', project, collection] })
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ push(describe(e), 'error')
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ setBusy(false)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <section className="rounded-lg border border-slate-700/40 bg-slate-800/30 overflow-hidden">
|
|
|
|
|
+ <header className="flex items-center justify-between px-3 py-2 border-b border-slate-700/40">
|
|
|
|
|
+ <h3 className="flex items-center gap-2 text-sm font-medium text-slate-200">
|
|
|
|
|
+ <FileJson className="w-4 h-4 text-slate-400" />
|
|
|
|
|
+ Schema
|
|
|
|
|
+ {data && (
|
|
|
|
|
+ <span
|
|
|
|
|
+ className={`px-1.5 py-0.5 rounded text-[11px] font-medium ${
|
|
|
|
|
+ data.mode === 'enforce'
|
|
|
|
|
+ ? 'bg-emerald-500/15 text-emerald-300'
|
|
|
|
|
+ : 'bg-amber-500/15 text-amber-300'
|
|
|
|
|
+ }`}
|
|
|
|
|
+ >
|
|
|
|
|
+ {data.mode}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </h3>
|
|
|
|
|
+ <div className="flex items-center gap-2">
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={suggest}
|
|
|
|
|
+ disabled={busy}
|
|
|
|
|
+ title="Build a schema from the existing rows. Does not apply it."
|
|
|
|
|
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium text-indigo-300 bg-indigo-500/10 hover:bg-indigo-500/20 disabled:opacity-50 transition"
|
|
|
|
|
+ >
|
|
|
|
|
+ <Wand2 className="w-3.5 h-3.5" />
|
|
|
|
|
+ Suggest
|
|
|
|
|
+ </button>
|
|
|
|
|
+ {data && (
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={remove}
|
|
|
|
|
+ disabled={busy}
|
|
|
|
|
+ title="Remove the schema; writes stop being validated"
|
|
|
|
|
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium text-red-300 bg-red-500/10 hover:bg-red-500/20 disabled:opacity-50 transition"
|
|
|
|
|
+ >
|
|
|
|
|
+ <Trash2 className="w-3.5 h-3.5" />
|
|
|
|
|
+ Remove
|
|
|
|
|
+ </button>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </header>
|
|
|
|
|
+
|
|
|
|
|
+ <div className="p-3 space-y-3">
|
|
|
|
|
+ {/* A stored schema that no longer compiles validates NOTHING. Loudest
|
|
|
|
|
+ thing in the panel, because the badge above would otherwise read as
|
|
|
|
|
+ protection that is not there. */}
|
|
|
|
|
+ {data && !data.armed && (
|
|
|
|
|
+ <p className="flex items-start gap-2 text-xs text-red-300 bg-red-500/10 border border-red-500/30 rounded px-2 py-1.5">
|
|
|
|
|
+ <ShieldAlert className="w-4 h-4 shrink-0 mt-px" />
|
|
|
|
|
+ <span>
|
|
|
|
|
+ <strong>Not armed.</strong> The stored schema no longer compiles, so nothing is being
|
|
|
|
|
+ validated. Writes that would violate it are being accepted. Save a corrected schema or
|
|
|
|
|
+ remove it.
|
|
|
|
|
+ </span>
|
|
|
|
|
+ </p>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {isLoading && <p className="text-xs text-slate-500">Loading…</p>}
|
|
|
|
|
+
|
|
|
|
|
+ {!isLoading && !data && !editing && (
|
|
|
|
|
+ <p className="text-xs text-slate-500">
|
|
|
|
|
+ No schema. Writes are not validated. Use <strong>Suggest</strong> to draft one from the
|
|
|
|
|
+ existing rows, or{' '}
|
|
|
|
|
+ <button onClick={() => { setDraft('{\n "type": "object"\n}'); setEditing(true) }}
|
|
|
|
|
+ className="text-indigo-300 hover:underline">
|
|
|
|
|
+ start from scratch
|
|
|
|
|
+ </button>
|
|
|
|
|
+ .
|
|
|
|
|
+ </p>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {data && !editing && (
|
|
|
|
|
+ <>
|
|
|
|
|
+ <dl className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
|
|
|
|
|
+ <dt className="text-slate-500">Mode</dt>
|
|
|
|
|
+ <dd className="text-slate-300">{data.mode}</dd>
|
|
|
|
|
+ {data.mode === 'audit' ? (
|
|
|
|
|
+ <>
|
|
|
|
|
+ <dt className="text-slate-500">Violating writes let through</dt>
|
|
|
|
|
+ <dd className="text-amber-300">{data.audit_violations.toLocaleString()}</dd>
|
|
|
|
|
+ </>
|
|
|
|
|
+ ) : (
|
|
|
|
|
+ <>
|
|
|
|
|
+ <dt className="text-slate-500">Writes refused</dt>
|
|
|
|
|
+ <dd className="text-slate-300">{data.refusals.toLocaleString()}</dd>
|
|
|
|
|
+ </>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </dl>
|
|
|
|
|
+ <pre className="text-[11px] font-mono text-slate-300 bg-slate-900/50 rounded p-2 max-h-56 overflow-auto">
|
|
|
|
|
+ {JSON.stringify(data.schema, null, 2)}
|
|
|
|
|
+ </pre>
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() => { setDraft(JSON.stringify(data.schema, null, 2)); setEditing(true) }}
|
|
|
|
|
+ className="text-xs text-indigo-300 hover:underline"
|
|
|
|
|
+ >
|
|
|
|
|
+ Edit
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {editing && (
|
|
|
|
|
+ <div className="space-y-2">
|
|
|
|
|
+ <JsonEditor value={draft} onChange={setDraft} onValidityChange={setValid} height={300} />
|
|
|
|
|
+ <div className="flex items-center gap-3 flex-wrap">
|
|
|
|
|
+ <label className="text-xs text-slate-400">
|
|
|
|
|
+ Mode{' '}
|
|
|
|
|
+ <select
|
|
|
|
|
+ value={mode}
|
|
|
|
|
+ onChange={(e) => setMode(e.target.value as SchemaMode | '')}
|
|
|
|
|
+ className="ml-1 bg-slate-900/60 border border-slate-700/60 rounded px-1.5 py-1 text-xs text-slate-200"
|
|
|
|
|
+ >
|
|
|
|
|
+ {/* The SERVER picks when this is empty, and tells us which
|
|
|
|
|
+ rule it used. Duplicating "enforce if empty, audit if
|
|
|
|
|
+ populated" here would put one rule in two places. */}
|
|
|
|
|
+ <option value="">Choose for me</option>
|
|
|
|
|
+ <option value="enforce">enforce - refuse non-conforming writes</option>
|
|
|
|
|
+ <option value="audit">audit - count them and let them through</option>
|
|
|
|
|
+ </select>
|
|
|
|
|
+ </label>
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={save}
|
|
|
|
|
+ disabled={busy || !valid}
|
|
|
|
|
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium text-emerald-300 bg-emerald-500/10 hover:bg-emerald-500/20 disabled:opacity-50 transition"
|
|
|
|
|
+ >
|
|
|
|
|
+ <Check className="w-3.5 h-3.5" />
|
|
|
|
|
+ Save
|
|
|
|
|
+ </button>
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() => { setEditing(false); setViolations(null) }}
|
|
|
|
|
+ className="text-xs text-slate-400 hover:text-slate-200"
|
|
|
|
|
+ >
|
|
|
|
|
+ Cancel
|
|
|
|
|
+ </button>
|
|
|
|
|
+ {!valid && <span className="text-xs text-red-400">Not valid JSON</span>}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <p className="text-[11px] text-slate-500">
|
|
|
|
|
+ On an <strong>empty</strong> collection the default is <code>enforce</code>; on a{' '}
|
|
|
|
|
+ <strong>populated</strong> one it is <code>audit</code>, because enforce refuses the
|
|
|
|
|
+ whole change if any existing row does not conform.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {/* The counts and the offending rows. Rendered rather than toasted:
|
|
|
|
|
+ these are what an operator acts on. */}
|
|
|
|
|
+ {violations && (
|
|
|
|
|
+ <div
|
|
|
|
|
+ className={`rounded border px-2 py-1.5 space-y-1 ${
|
|
|
|
|
+ violations.refused
|
|
|
|
|
+ ? 'border-red-500/30 bg-red-500/10'
|
|
|
|
|
+ : 'border-amber-500/30 bg-amber-500/10'
|
|
|
|
|
+ }`}
|
|
|
|
|
+ >
|
|
|
|
|
+ <p className="flex items-start gap-2 text-xs text-slate-200">
|
|
|
|
|
+ <AlertTriangle
|
|
|
|
|
+ className={`w-4 h-4 shrink-0 mt-px ${
|
|
|
|
|
+ violations.refused ? 'text-red-300' : 'text-amber-300'
|
|
|
|
|
+ }`}
|
|
|
|
|
+ />
|
|
|
|
|
+ <span>
|
|
|
|
|
+ {violations.refused ? (
|
|
|
|
|
+ <>
|
|
|
|
|
+ <strong>Not applied.</strong> {violations.violatingRows.toLocaleString()} of{' '}
|
|
|
|
|
+ {violations.rowsChecked.toLocaleString()} existing row(s) do not conform. Fix
|
|
|
|
|
+ them, or save in <code>audit</code> mode to arm it anyway and count them.
|
|
|
|
|
+ </>
|
|
|
|
|
+ ) : (
|
|
|
|
|
+ <>
|
|
|
|
|
+ <strong>Armed in audit mode.</strong>{' '}
|
|
|
|
|
+ {violations.violatingRows.toLocaleString()} of{' '}
|
|
|
|
|
+ {violations.rowsChecked.toLocaleString()} existing row(s) do not conform. They
|
|
|
|
|
+ are being counted, not refused.
|
|
|
|
|
+ </>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ </p>
|
|
|
|
|
+ {violations.examples.length > 0 && (
|
|
|
|
|
+ <ul className="space-y-0.5 pl-6">
|
|
|
|
|
+ {violations.examples.map((v) => (
|
|
|
|
|
+ <li key={v.id} className="text-[11px] text-slate-400">
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() =>
|
|
|
|
|
+ navigate(
|
|
|
|
|
+ `/documents?collection=${encodeURIComponent(collection)}&open=${encodeURIComponent(v.id)}`,
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+ className="font-mono text-indigo-300 hover:underline"
|
|
|
|
|
+ >
|
|
|
|
|
+ {v.id}
|
|
|
|
|
+ </button>
|
|
|
|
|
+ {' — '}
|
|
|
|
|
+ {v.message}
|
|
|
|
|
+ {v.fields.length > 0 && (
|
|
|
|
|
+ <span className="text-slate-500"> ({v.fields.join(', ')})</span>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </li>
|
|
|
|
|
+ ))}
|
|
|
|
|
+ {violations.violatingRows > violations.examples.length && (
|
|
|
|
|
+ <li className="text-[11px] text-slate-500">
|
|
|
|
|
+ …and {(violations.violatingRows - violations.examples.length).toLocaleString()}{' '}
|
|
|
|
|
+ more (the server reports at most ten examples)
|
|
|
|
|
+ </li>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </ul>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </section>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|