Add Storage, Users, Secrets, Webhooks, Scheduled tasks, Audit log screens
Full management surfaces for the platform-admin tenant, mirroring the existing Tenants pattern (DataTable + row actions + create/edit dialogs + ConfirmDialog for destructive ops, all data-action tagged for the command bus, useRegisterAdminContext publishing for the assistant). - Storage (/storage): backends + credentials. Write-only secret fields, Validate/Activate/Deactivate/Set-default/Mark-degraded/Maintenance. - Users (/users): tabs for Users, Invitations, Roles. Per-user View drawer with profile, role add/remove, API keys (one-time reveal on create), usage + quota. - Secrets (/secrets): /api/v1/admin/secrets — create/rotate/rollback, versions dialog, enable/disable, generate-value helper. - Webhooks (/webhooks): CRUD, pause/resume, regenerate-secret with one-time reveal, send test event, deliveries dialog. - Scheduled tasks (/scheduled-tasks): cron CRUD, run-now trigger, enable/disable, expandable run history. - Audit log (/activity): replaces the empty stub. Filter by severity, resource type, date range; click for full JSON detail. All endpoints are hand-rolled HTTP because most aren't covered by the generated OpenAPI typed paths yet — switch to arcadia.typed.* when the backend wires them into OpenApiSpex. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,23 @@
|
||||
import { Activity } from "lucide-react"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { Link } from "react-router"
|
||||
import { Activity, Eye, RefreshCw } from "lucide-react"
|
||||
|
||||
import { ArcadiaError, useArcadiaClient } from "@crema/arcadia-client"
|
||||
import {
|
||||
ActionsCell,
|
||||
BadgeCell,
|
||||
DataTable,
|
||||
DateCell,
|
||||
Pagination,
|
||||
useTable,
|
||||
type BadgeTone,
|
||||
type Column,
|
||||
} from "@crema/table-ui"
|
||||
import { SearchInput } from "@crema/search-ui"
|
||||
import { AlertBanner, EmptyState, LoadingOverlay } from "@crema/feedback-ui"
|
||||
|
||||
import { AppShell } from "~/components/layout/app-shell"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -8,36 +25,405 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "~/components/ui/dialog"
|
||||
import { Input } from "~/components/ui/input"
|
||||
import { Label } from "~/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select"
|
||||
import {
|
||||
listAuditLogs,
|
||||
type AuditLog,
|
||||
type AuditSeverity,
|
||||
} from "~/lib/arcadia/audit-logs"
|
||||
import { pageTitle } from "~/lib/page-meta"
|
||||
import { useSession } from "~/lib/session"
|
||||
import { useRegisterAdminContext } from "~/lib/admin-context"
|
||||
|
||||
export const meta = () => pageTitle("Activity")
|
||||
export const meta = () => pageTitle("Audit log")
|
||||
|
||||
export default function ActivityRoute() {
|
||||
const session = useSession()
|
||||
const arcadia = useArcadiaClient()
|
||||
|
||||
const [logs, setLogs] = useState<AuditLog[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [search, setSearch] = useState("")
|
||||
const [severityFilter, setSeverityFilter] = useState<"all" | AuditSeverity>("all")
|
||||
const [resourceFilter, setResourceFilter] = useState("")
|
||||
const [from, setFrom] = useState("")
|
||||
const [to, setTo] = useState("")
|
||||
const [detail, setDetail] = useState<AuditLog | null>(null)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setError(null)
|
||||
setLoading(true)
|
||||
try {
|
||||
const list = await listAuditLogs(arcadia, {
|
||||
severity: severityFilter === "all" ? undefined : severityFilter,
|
||||
resource_type: resourceFilter || undefined,
|
||||
from: from ? new Date(from).toISOString() : undefined,
|
||||
to: to ? new Date(to).toISOString() : undefined,
|
||||
limit: 200,
|
||||
})
|
||||
setLogs(list)
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Failed to load audit logs.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [arcadia, severityFilter, resourceFilter, from, to])
|
||||
|
||||
useEffect(() => {
|
||||
if (session) refresh()
|
||||
}, [session, refresh])
|
||||
|
||||
const columns = useMemo<Column<AuditLog>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "time",
|
||||
header: "Time",
|
||||
accessor: "inserted_at",
|
||||
sortable: true,
|
||||
cell: (l) => <DateCell value={l.inserted_at} format="datetime" />,
|
||||
},
|
||||
{
|
||||
id: "user",
|
||||
header: "User",
|
||||
accessor: (l) => l.user?.email ?? "",
|
||||
sortable: true,
|
||||
cell: (l) => (
|
||||
<span className="text-sm">
|
||||
{l.user?.email ?? <span className="text-muted-foreground">system</span>}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "action",
|
||||
header: "Action",
|
||||
accessor: "action",
|
||||
sortable: true,
|
||||
cell: (l) => (
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{l.action}</code>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "resource",
|
||||
header: "Resource",
|
||||
accessor: "resource_type",
|
||||
sortable: true,
|
||||
cell: (l) => (
|
||||
<span className="text-sm">
|
||||
<span className="font-medium">{l.resource_type}</span>
|
||||
{l.resource_id ? (
|
||||
<span className="ml-1 font-mono text-xs text-muted-foreground">
|
||||
{l.resource_id.slice(0, 8)}…
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "severity",
|
||||
header: "Severity",
|
||||
accessor: "severity",
|
||||
sortable: true,
|
||||
cell: (l) => <BadgeCell label={l.severity} tone={severityTone(l.severity)} />,
|
||||
},
|
||||
{
|
||||
id: "ip",
|
||||
header: "IP",
|
||||
accessor: "ip_address",
|
||||
cell: (l) => (
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{l.ip_address ?? "—"}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
align: "right",
|
||||
cell: (l) => (
|
||||
<ActionsCell
|
||||
items={[
|
||||
{
|
||||
id: "view",
|
||||
label: "View details",
|
||||
icon: <Eye className="size-4" />,
|
||||
dataAction: `audit-${l.id}-view`,
|
||||
onSelect: () => setDetail(l),
|
||||
},
|
||||
]}
|
||||
triggerDataAction={`audit-${l.id}-actions`}
|
||||
/>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
)
|
||||
|
||||
const summary = useMemo(
|
||||
() => ({
|
||||
total: logs.length,
|
||||
bySeverity: countBy(logs, (l) => l.severity || "info"),
|
||||
byResource: countBy(logs, (l) => l.resource_type),
|
||||
latest: logs.slice(0, 5).map((l) => ({
|
||||
time: l.inserted_at,
|
||||
user: l.user?.email ?? "system",
|
||||
action: l.action,
|
||||
resource: `${l.resource_type}${l.resource_id ? `/${l.resource_id}` : ""}`,
|
||||
})),
|
||||
}),
|
||||
[logs],
|
||||
)
|
||||
useRegisterAdminContext("audit_log", summary)
|
||||
|
||||
const table = useTable<AuditLog>({
|
||||
data: logs,
|
||||
columns,
|
||||
getRowId: (l) => l.id,
|
||||
initialPageSize: 50,
|
||||
initialSearch: search,
|
||||
})
|
||||
useEffect(() => {
|
||||
table.setSearch(search)
|
||||
}, [search, table])
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<AppShell title="Audit log">
|
||||
<div className="p-8">
|
||||
<Card className="max-w-md">
|
||||
<CardHeader>
|
||||
<CardTitle>Sign in required</CardTitle>
|
||||
<CardDescription>The audit log requires an admin session.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button asChild>
|
||||
<Link to="/login?next=/activity">Sign in</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell title="Activity">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Activity</CardTitle>
|
||||
<CardDescription>
|
||||
Event stream, audit log, recent changes.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-muted-foreground/20 bg-muted/30 p-12 text-center">
|
||||
<div className="flex size-12 items-center justify-center rounded-xl bg-background text-muted-foreground">
|
||||
<Activity className="size-6" />
|
||||
</div>
|
||||
<div className="max-w-md">
|
||||
<p className="font-medium">No activity yet</p>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Once your app is doing things, this is where audit events,
|
||||
webhook deliveries, and recent changes show up — pair with{" "}
|
||||
<code className="font-mono text-xs">@crema/log-ui</code>.
|
||||
</p>
|
||||
</div>
|
||||
<AppShell title="Audit log">
|
||||
<div className="flex flex-col gap-4 p-6">
|
||||
<header className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Audit log</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Every authenticated action against the platform. Filter by date, severity, or
|
||||
resource type.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={refresh}
|
||||
disabled={loading}
|
||||
data-action="audit-refresh"
|
||||
>
|
||||
<RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
{error ? (
|
||||
<AlertBanner variant="error" dismissible onDismiss={() => setError(null)}>
|
||||
{error}
|
||||
</AlertBanner>
|
||||
) : null}
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-col gap-3 lg:flex-row lg:flex-wrap lg:items-end">
|
||||
<SearchInput
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
placeholder="Search by action, resource, or user"
|
||||
data-action="audit-search"
|
||||
className="max-w-sm flex-1"
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="audit-severity" className="text-xs">
|
||||
Severity
|
||||
</Label>
|
||||
<Select
|
||||
value={severityFilter}
|
||||
onValueChange={(v) => setSeverityFilter(v as typeof severityFilter)}
|
||||
>
|
||||
<SelectTrigger id="audit-severity" className="w-36" data-action="audit-severity-filter">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All</SelectItem>
|
||||
<SelectItem value="info">Info</SelectItem>
|
||||
<SelectItem value="warning">Warning</SelectItem>
|
||||
<SelectItem value="error">Error</SelectItem>
|
||||
<SelectItem value="critical">Critical</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="audit-resource" className="text-xs">
|
||||
Resource type
|
||||
</Label>
|
||||
<Input
|
||||
id="audit-resource"
|
||||
value={resourceFilter}
|
||||
onChange={(e) => setResourceFilter(e.target.value)}
|
||||
placeholder="e.g. user"
|
||||
className="w-40"
|
||||
data-action="audit-resource-filter"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="audit-from" className="text-xs">
|
||||
From
|
||||
</Label>
|
||||
<Input
|
||||
id="audit-from"
|
||||
type="datetime-local"
|
||||
value={from}
|
||||
onChange={(e) => setFrom(e.target.value)}
|
||||
className="w-44"
|
||||
data-action="audit-from-filter"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="audit-to" className="text-xs">
|
||||
To
|
||||
</Label>
|
||||
<Input
|
||||
id="audit-to"
|
||||
type="datetime-local"
|
||||
value={to}
|
||||
onChange={(e) => setTo(e.target.value)}
|
||||
className="w-44"
|
||||
data-action="audit-to-filter"
|
||||
/>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="relative p-0">
|
||||
<LoadingOverlay active={loading && logs.length === 0} label="Loading audit log…" />
|
||||
{table.total === 0 && !loading ? (
|
||||
<EmptyState
|
||||
icon={<Activity className="size-6" />}
|
||||
title="No events match those filters."
|
||||
description="Loosen the filter set or wait for new platform activity."
|
||||
className="py-12"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
rows={table.pageRows}
|
||||
getRowId={(l) => l.id}
|
||||
sort={table.sort}
|
||||
onSortToggle={table.toggleSort}
|
||||
loading={loading && logs.length > 0}
|
||||
stickyHeader
|
||||
/>
|
||||
<Pagination
|
||||
page={table.page}
|
||||
pageSize={table.pageSize}
|
||||
total={table.total}
|
||||
onPageChange={table.setPage}
|
||||
onPageSizeChange={table.setPageSize}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Dialog open={detail !== null} onOpenChange={(o) => !o && setDetail(null)}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Audit event</DialogTitle>
|
||||
<DialogDescription>
|
||||
{detail
|
||||
? `${detail.action} on ${detail.resource_type} at ${new Date(
|
||||
detail.inserted_at,
|
||||
).toLocaleString()}`
|
||||
: ""}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{detail ? <AuditDetailBody log={detail} /> : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
function AuditDetailBody({ log }: { log: AuditLog }) {
|
||||
const rows: { k: string; v: string }[] = [
|
||||
{ k: "ID", v: log.id },
|
||||
{ k: "Tenant", v: log.tenant_id },
|
||||
{ k: "User", v: log.user?.email ?? log.user_id ?? "—" },
|
||||
{ k: "Action", v: log.action },
|
||||
{ k: "Resource", v: `${log.resource_type}${log.resource_id ? `/${log.resource_id}` : ""}` },
|
||||
{ k: "Severity", v: log.severity },
|
||||
{ k: "IP", v: log.ip_address ?? "—" },
|
||||
{ k: "User agent", v: log.user_agent ?? "—" },
|
||||
{ k: "Time", v: new Date(log.inserted_at).toISOString() },
|
||||
]
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<dl className="grid grid-cols-[8rem_1fr] gap-y-1 text-sm">
|
||||
{rows.map((r) => (
|
||||
<div key={r.k} className="contents">
|
||||
<dt className="text-xs uppercase tracking-wide text-muted-foreground">{r.k}</dt>
|
||||
<dd className="break-all font-mono text-xs">{r.v}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{log.changes ? (
|
||||
<div>
|
||||
<h3 className="mb-1.5 text-sm font-semibold">Changes</h3>
|
||||
<pre className="overflow-x-auto rounded-md border bg-muted/50 p-3 text-xs">
|
||||
{JSON.stringify(log.changes, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
) : null}
|
||||
{log.metadata && Object.keys(log.metadata).length > 0 ? (
|
||||
<div>
|
||||
<h3 className="mb-1.5 text-sm font-semibold">Metadata</h3>
|
||||
<pre className="overflow-x-auto rounded-md border bg-muted/50 p-3 text-xs">
|
||||
{JSON.stringify(log.metadata, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function severityTone(s: AuditSeverity): BadgeTone {
|
||||
if (s === "critical" || s === "error") return "danger"
|
||||
if (s === "warning") return "warning"
|
||||
return "default"
|
||||
}
|
||||
|
||||
function countBy<T>(arr: T[], key: (x: T) => string): Record<string, number> {
|
||||
return arr.reduce<Record<string, number>>((acc, x) => {
|
||||
const k = key(x)
|
||||
acc[k] = (acc[k] ?? 0) + 1
|
||||
return acc
|
||||
}, {})
|
||||
}
|
||||
|
||||
879
app/routes/scheduled-tasks.tsx
Normal file
879
app/routes/scheduled-tasks.tsx
Normal file
@@ -0,0 +1,879 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { Link } from "react-router"
|
||||
import {
|
||||
CalendarClock,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
History,
|
||||
Pause,
|
||||
Play,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Trash2,
|
||||
Zap,
|
||||
} from "lucide-react"
|
||||
|
||||
import { ArcadiaError, useArcadiaClient } from "@crema/arcadia-client"
|
||||
import {
|
||||
ActionsCell,
|
||||
BadgeCell,
|
||||
DataTable,
|
||||
DateCell,
|
||||
Pagination,
|
||||
useTable,
|
||||
type ActionItem,
|
||||
type BadgeTone,
|
||||
type Column,
|
||||
} from "@crema/table-ui"
|
||||
import { SearchInput } from "@crema/search-ui"
|
||||
import { AlertBanner, ConfirmDialog, EmptyState, LoadingOverlay } from "@crema/feedback-ui"
|
||||
|
||||
import { AppShell } from "~/components/layout/app-shell"
|
||||
import { Badge } from "~/components/ui/badge"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "~/components/ui/dialog"
|
||||
import { Input } from "~/components/ui/input"
|
||||
import { Label } from "~/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select"
|
||||
import { Switch } from "~/components/ui/switch"
|
||||
import { Textarea } from "~/components/ui/textarea"
|
||||
import {
|
||||
createScheduledTask,
|
||||
deleteScheduledTask,
|
||||
disableScheduledTask,
|
||||
enableScheduledTask,
|
||||
listScheduledTasks,
|
||||
listTaskRuns,
|
||||
triggerScheduledTask,
|
||||
updateScheduledTask,
|
||||
type ScheduledTask,
|
||||
type ScheduledTaskAction,
|
||||
type ScheduledTaskInput,
|
||||
type TaskRun,
|
||||
} from "~/lib/arcadia/scheduled-tasks"
|
||||
import { pageTitle } from "~/lib/page-meta"
|
||||
import { useSession } from "~/lib/session"
|
||||
import { useRegisterAdminContext } from "~/lib/admin-context"
|
||||
|
||||
export const meta = () => pageTitle("Scheduled tasks")
|
||||
|
||||
type EditorState =
|
||||
| { mode: "create" }
|
||||
| { mode: "edit"; task: ScheduledTask }
|
||||
| null
|
||||
|
||||
export default function ScheduledTasksRoute() {
|
||||
const session = useSession()
|
||||
const arcadia = useArcadiaClient()
|
||||
|
||||
const [tasks, setTasks] = useState<ScheduledTask[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [info, setInfo] = useState<string | null>(null)
|
||||
const [search, setSearch] = useState("")
|
||||
const [editor, setEditor] = useState<EditorState>(null)
|
||||
const [pendingDelete, setPendingDelete] = useState<ScheduledTask | null>(null)
|
||||
const [runsFor, setRunsFor] = useState<ScheduledTask | null>(null)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setError(null)
|
||||
setLoading(true)
|
||||
try {
|
||||
setTasks(await listScheduledTasks(arcadia))
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Failed to load scheduled tasks.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [arcadia])
|
||||
|
||||
useEffect(() => {
|
||||
if (session) refresh()
|
||||
}, [session, refresh])
|
||||
|
||||
const columns = useMemo<Column<ScheduledTask>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "name",
|
||||
header: "Name",
|
||||
accessor: "name",
|
||||
sortable: true,
|
||||
cell: (t) => (
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{t.name}</span>
|
||||
{t.description ? (
|
||||
<span className="text-xs text-muted-foreground">{t.description}</span>
|
||||
) : null}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "cron",
|
||||
header: "Schedule",
|
||||
accessor: "cron_expression",
|
||||
sortable: true,
|
||||
cell: (t) => (
|
||||
<div className="flex flex-col">
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">
|
||||
{t.cron_expression}
|
||||
</code>
|
||||
<span className="text-[11px] text-muted-foreground">{t.timezone}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "action",
|
||||
header: "Action",
|
||||
accessor: "action_type",
|
||||
sortable: true,
|
||||
cell: (t) => (
|
||||
<Badge variant="secondary" className="font-mono text-xs">
|
||||
{t.action_type}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: "Status",
|
||||
accessor: "enabled",
|
||||
sortable: true,
|
||||
cell: (t) => (
|
||||
<BadgeCell
|
||||
label={t.enabled ? "enabled" : "disabled"}
|
||||
tone={t.enabled ? "success" : "default"}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "last",
|
||||
header: "Last run",
|
||||
accessor: "last_run_at",
|
||||
sortable: true,
|
||||
cell: (t) =>
|
||||
t.last_run_at ? (
|
||||
<DateCell value={t.last_run_at} format="short" />
|
||||
) : (
|
||||
<span className="text-muted-foreground">never</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "next",
|
||||
header: "Next run",
|
||||
accessor: "next_run_at",
|
||||
sortable: true,
|
||||
cell: (t) =>
|
||||
t.enabled && t.next_run_at ? (
|
||||
<DateCell value={t.next_run_at} format="short" />
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
align: "right",
|
||||
cell: (t) => (
|
||||
<ActionsCell
|
||||
items={rowActions(t, {
|
||||
arcadia,
|
||||
refresh,
|
||||
setEditor,
|
||||
setPendingDelete,
|
||||
setRunsFor,
|
||||
setError,
|
||||
setInfo,
|
||||
})}
|
||||
triggerDataAction={`task-${t.id}-actions`}
|
||||
/>
|
||||
),
|
||||
},
|
||||
],
|
||||
[arcadia, refresh],
|
||||
)
|
||||
|
||||
const summary = useMemo(
|
||||
() => ({
|
||||
total: tasks.length,
|
||||
enabled: tasks.filter((t) => t.enabled).length,
|
||||
byAction: countBy(tasks, (t) => t.action_type),
|
||||
tasks: tasks.map((t) => ({
|
||||
name: t.name,
|
||||
cron: t.cron_expression,
|
||||
timezone: t.timezone,
|
||||
action_type: t.action_type,
|
||||
enabled: t.enabled,
|
||||
last_run_at: t.last_run_at,
|
||||
next_run_at: t.next_run_at,
|
||||
})),
|
||||
}),
|
||||
[tasks],
|
||||
)
|
||||
useRegisterAdminContext("scheduled_tasks", summary)
|
||||
|
||||
const table = useTable<ScheduledTask>({
|
||||
data: tasks,
|
||||
columns,
|
||||
getRowId: (t) => t.id,
|
||||
initialPageSize: 25,
|
||||
initialSearch: search,
|
||||
})
|
||||
useEffect(() => {
|
||||
table.setSearch(search)
|
||||
}, [search, table])
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<AppShell title="Scheduled tasks">
|
||||
<div className="p-8">
|
||||
<Card className="max-w-md">
|
||||
<CardHeader>
|
||||
<CardTitle>Sign in required</CardTitle>
|
||||
<CardDescription>
|
||||
Scheduled task administration requires an admin session.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button asChild>
|
||||
<Link to="/login?next=/scheduled-tasks">Sign in</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell title="Scheduled tasks">
|
||||
<div className="flex flex-col gap-4 p-6">
|
||||
<header className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Scheduled tasks</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Cron-driven jobs run by arcadia. Trigger a task manually to test it without waiting
|
||||
for the next scheduled run.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={refresh}
|
||||
disabled={loading}
|
||||
data-action="tasks-refresh"
|
||||
>
|
||||
<RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setEditor({ mode: "create" })}
|
||||
data-action="tasks-create"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
New task
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{error ? (
|
||||
<AlertBanner variant="error" dismissible onDismiss={() => setError(null)}>
|
||||
{error}
|
||||
</AlertBanner>
|
||||
) : null}
|
||||
{info ? (
|
||||
<AlertBanner variant="success" dismissible onDismiss={() => setInfo(null)}>
|
||||
{info}
|
||||
</AlertBanner>
|
||||
) : null}
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center gap-3">
|
||||
<SearchInput
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
placeholder="Search by name, cron, or action"
|
||||
data-action="tasks-search"
|
||||
className="max-w-sm flex-1"
|
||||
/>
|
||||
<div className="ml-auto text-xs text-muted-foreground">
|
||||
{table.total} of {tasks.length}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="relative p-0">
|
||||
<LoadingOverlay active={loading && tasks.length === 0} label="Loading tasks…" />
|
||||
{table.total === 0 && !loading ? (
|
||||
<EmptyState
|
||||
icon={<CalendarClock className="size-6" />}
|
||||
title={search ? "No tasks match." : "No scheduled tasks yet."}
|
||||
description={
|
||||
search
|
||||
? "Try a different search."
|
||||
: "Schedule a recurring webhook or platform event."
|
||||
}
|
||||
className="py-12"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
rows={table.pageRows}
|
||||
getRowId={(t) => t.id}
|
||||
sort={table.sort}
|
||||
onSortToggle={table.toggleSort}
|
||||
loading={loading && tasks.length > 0}
|
||||
stickyHeader
|
||||
/>
|
||||
<Pagination
|
||||
page={table.page}
|
||||
pageSize={table.pageSize}
|
||||
total={table.total}
|
||||
onPageChange={table.setPage}
|
||||
onPageSizeChange={table.setPageSize}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={pendingDelete !== null}
|
||||
onOpenChange={(o) => !o && setPendingDelete(null)}
|
||||
title="Delete scheduled task?"
|
||||
description={
|
||||
pendingDelete
|
||||
? `${pendingDelete.name} will be permanently removed. Run history is retained.`
|
||||
: ""
|
||||
}
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
onConfirm={async () => {
|
||||
if (!pendingDelete) return
|
||||
try {
|
||||
await deleteScheduledTask(arcadia, pendingDelete.id)
|
||||
setPendingDelete(null)
|
||||
setInfo("Task deleted.")
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Delete failed.")
|
||||
setPendingDelete(null)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<TaskEditorDialog
|
||||
state={editor}
|
||||
onClose={() => setEditor(null)}
|
||||
onSaved={async () => {
|
||||
setEditor(null)
|
||||
await refresh()
|
||||
}}
|
||||
onError={setError}
|
||||
/>
|
||||
|
||||
<RunsDialog task={runsFor} onClose={() => setRunsFor(null)} onError={setError} />
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
function rowActions(
|
||||
t: ScheduledTask,
|
||||
ctx: {
|
||||
arcadia: ReturnType<typeof useArcadiaClient>
|
||||
refresh: () => Promise<void>
|
||||
setEditor: (s: EditorState) => void
|
||||
setPendingDelete: (t: ScheduledTask | null) => void
|
||||
setRunsFor: (t: ScheduledTask | null) => void
|
||||
setError: (m: string | null) => void
|
||||
setInfo: (m: string | null) => void
|
||||
},
|
||||
): ActionItem[] {
|
||||
const { arcadia, refresh, setEditor, setPendingDelete, setRunsFor, setError, setInfo } = ctx
|
||||
const items: ActionItem[] = []
|
||||
|
||||
items.push({
|
||||
id: "trigger",
|
||||
label: "Run now",
|
||||
icon: <Zap className="size-4" />,
|
||||
dataAction: `task-${t.id}-trigger`,
|
||||
onSelect: async () => {
|
||||
try {
|
||||
await triggerScheduledTask(arcadia, t.id)
|
||||
setInfo(`${t.name} triggered. Check the run log for status.`)
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Trigger failed.")
|
||||
}
|
||||
},
|
||||
})
|
||||
items.push({
|
||||
id: "edit",
|
||||
label: "Edit",
|
||||
dataAction: `task-${t.id}-edit`,
|
||||
onSelect: () => setEditor({ mode: "edit", task: t }),
|
||||
})
|
||||
items.push({
|
||||
id: "runs",
|
||||
label: "View runs",
|
||||
icon: <History className="size-4" />,
|
||||
dataAction: `task-${t.id}-runs`,
|
||||
onSelect: () => setRunsFor(t),
|
||||
})
|
||||
|
||||
if (t.enabled) {
|
||||
items.push({
|
||||
id: "disable",
|
||||
label: "Disable",
|
||||
icon: <Pause className="size-4" />,
|
||||
dataAction: `task-${t.id}-disable`,
|
||||
onSelect: async () => {
|
||||
try {
|
||||
await disableScheduledTask(arcadia, t.id)
|
||||
setInfo(`${t.name} disabled.`)
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Disable failed.")
|
||||
}
|
||||
},
|
||||
})
|
||||
} else {
|
||||
items.push({
|
||||
id: "enable",
|
||||
label: "Enable",
|
||||
icon: <Play className="size-4" />,
|
||||
dataAction: `task-${t.id}-enable`,
|
||||
onSelect: async () => {
|
||||
try {
|
||||
await enableScheduledTask(arcadia, t.id)
|
||||
setInfo(`${t.name} enabled.`)
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Enable failed.")
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
items.push({
|
||||
id: "delete",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="size-4" />,
|
||||
destructive: true,
|
||||
dataAction: `task-${t.id}-delete`,
|
||||
onSelect: () => setPendingDelete(t),
|
||||
})
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
function TaskEditorDialog({
|
||||
state,
|
||||
onClose,
|
||||
onSaved,
|
||||
onError,
|
||||
}: {
|
||||
state: EditorState
|
||||
onClose: () => void
|
||||
onSaved: () => Promise<void>
|
||||
onError: (msg: string | null) => void
|
||||
}) {
|
||||
const arcadia = useArcadiaClient()
|
||||
const open = state !== null
|
||||
const isEdit = state?.mode === "edit"
|
||||
const initial = isEdit ? state.task : null
|
||||
|
||||
const [name, setName] = useState("")
|
||||
const [description, setDescription] = useState("")
|
||||
const [cron, setCron] = useState("")
|
||||
const [timezone, setTimezone] = useState("UTC")
|
||||
const [actionType, setActionType] = useState<ScheduledTaskAction>("event")
|
||||
const [configText, setConfigText] = useState("{}")
|
||||
const [tagsText, setTagsText] = useState("")
|
||||
const [enabled, setEnabled] = useState(true)
|
||||
const [maxRetries, setMaxRetries] = useState("3")
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState("30")
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
if (initial) {
|
||||
setName(initial.name)
|
||||
setDescription(initial.description ?? "")
|
||||
setCron(initial.cron_expression)
|
||||
setTimezone(initial.timezone)
|
||||
setActionType(initial.action_type)
|
||||
setConfigText(
|
||||
initial.action_config ? JSON.stringify(initial.action_config, null, 2) : "{}",
|
||||
)
|
||||
setTagsText(initial.tags.join(", "))
|
||||
setEnabled(initial.enabled)
|
||||
setMaxRetries(String(initial.max_retries))
|
||||
setTimeoutSeconds(String(initial.timeout_seconds))
|
||||
} else {
|
||||
setName("")
|
||||
setDescription("")
|
||||
setCron("0 * * * *")
|
||||
setTimezone("UTC")
|
||||
setActionType("event")
|
||||
setConfigText('{\n "event": "platform.heartbeat"\n}')
|
||||
setTagsText("")
|
||||
setEnabled(true)
|
||||
setMaxRetries("3")
|
||||
setTimeoutSeconds("30")
|
||||
}
|
||||
}, [open, initial])
|
||||
|
||||
const submit = async () => {
|
||||
onError(null)
|
||||
setSaving(true)
|
||||
try {
|
||||
let parsedConfig: Record<string, unknown>
|
||||
try {
|
||||
parsedConfig = configText.trim() === "" ? {} : JSON.parse(configText)
|
||||
} catch {
|
||||
throw new Error("Action config must be valid JSON.")
|
||||
}
|
||||
|
||||
const tags = tagsText
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const input: ScheduledTaskInput = {
|
||||
name,
|
||||
description: description || null,
|
||||
cron_expression: cron,
|
||||
timezone,
|
||||
action_type: actionType,
|
||||
action_config: parsedConfig,
|
||||
tags,
|
||||
enabled,
|
||||
max_retries: Math.max(0, Number(maxRetries) || 0),
|
||||
timeout_seconds: Math.max(1, Number(timeoutSeconds) || 30),
|
||||
}
|
||||
|
||||
if (isEdit && initial) await updateScheduledTask(arcadia, initial.id, input)
|
||||
else await createScheduledTask(arcadia, input)
|
||||
await onSaved()
|
||||
} catch (err) {
|
||||
onError(
|
||||
err instanceof ArcadiaError
|
||||
? err.message
|
||||
: err instanceof Error
|
||||
? err.message
|
||||
: "Save failed.",
|
||||
)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? "Edit scheduled task" : "New scheduled task"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Cron uses standard 5-field syntax (minute hour dom month dow). Tasks run in the
|
||||
specified timezone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="col-span-2 flex flex-col gap-1.5">
|
||||
<Label htmlFor="task-name">Name</Label>
|
||||
<Input
|
||||
id="task-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Daily cleanup"
|
||||
data-action="task-form-name"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 flex flex-col gap-1.5">
|
||||
<Label htmlFor="task-description">Description</Label>
|
||||
<Input
|
||||
id="task-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
data-action="task-form-description"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="task-cron">Cron expression</Label>
|
||||
<Input
|
||||
id="task-cron"
|
||||
value={cron}
|
||||
onChange={(e) => setCron(e.target.value)}
|
||||
placeholder="0 2 * * *"
|
||||
data-action="task-form-cron"
|
||||
spellCheck={false}
|
||||
className="font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="task-timezone">Timezone</Label>
|
||||
<Input
|
||||
id="task-timezone"
|
||||
value={timezone}
|
||||
onChange={(e) => setTimezone(e.target.value)}
|
||||
placeholder="UTC"
|
||||
data-action="task-form-timezone"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Action type</Label>
|
||||
<Select
|
||||
value={actionType}
|
||||
onValueChange={(v) => setActionType(v as ScheduledTaskAction)}
|
||||
>
|
||||
<SelectTrigger data-action="task-form-action-type">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="event">Emit platform event</SelectItem>
|
||||
<SelectItem value="webhook">Send outbound webhook</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="task-tags">Tags (comma-separated)</Label>
|
||||
<Input
|
||||
id="task-tags"
|
||||
value={tagsText}
|
||||
onChange={(e) => setTagsText(e.target.value)}
|
||||
placeholder="cleanup, nightly"
|
||||
data-action="task-form-tags"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 flex flex-col gap-1.5">
|
||||
<Label htmlFor="task-config">
|
||||
Action config (JSON){" "}
|
||||
<span className="font-normal text-muted-foreground">
|
||||
{actionType === "webhook"
|
||||
? "{ url, method?, headers?, body? }"
|
||||
: "{ event: 'name', payload?: {…} }"}
|
||||
</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="task-config"
|
||||
rows={8}
|
||||
value={configText}
|
||||
onChange={(e) => setConfigText(e.target.value)}
|
||||
data-action="task-form-config"
|
||||
spellCheck={false}
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="task-retries">Max retries</Label>
|
||||
<Input
|
||||
id="task-retries"
|
||||
type="number"
|
||||
min={0}
|
||||
value={maxRetries}
|
||||
onChange={(e) => setMaxRetries(e.target.value)}
|
||||
data-action="task-form-retries"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="task-timeout">Timeout (seconds)</Label>
|
||||
<Input
|
||||
id="task-timeout"
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
data-action="task-form-timeout"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 flex items-center justify-between rounded-md border px-3 py-2">
|
||||
<div>
|
||||
<div className="text-sm font-medium">Enabled</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Disabled tasks skip their scheduled runs.
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
checked={enabled}
|
||||
onCheckedChange={setEnabled}
|
||||
data-action="task-form-enabled"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose} disabled={saving} data-action="task-form-cancel">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={submit}
|
||||
disabled={saving || !name || !cron}
|
||||
data-action="task-form-save"
|
||||
>
|
||||
{saving ? <RefreshCw className="size-4 animate-spin" /> : <CheckCircle2 className="size-4" />}
|
||||
{isEdit ? "Save" : "Create"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function RunsDialog({
|
||||
task,
|
||||
onClose,
|
||||
onError,
|
||||
}: {
|
||||
task: ScheduledTask | null
|
||||
onClose: () => void
|
||||
onError: (msg: string | null) => void
|
||||
}) {
|
||||
const arcadia = useArcadiaClient()
|
||||
const [runs, setRuns] = useState<TaskRun[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [expanded, setExpanded] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!task) return
|
||||
let mounted = true
|
||||
setLoading(true)
|
||||
listTaskRuns(arcadia, task.id, { limit: 50 })
|
||||
.then((r) => mounted && setRuns(r))
|
||||
.catch((err) =>
|
||||
onError(err instanceof ArcadiaError ? err.message : "Failed to load runs."),
|
||||
)
|
||||
.finally(() => mounted && setLoading(false))
|
||||
return () => {
|
||||
mounted = false
|
||||
}
|
||||
}, [arcadia, task, onError])
|
||||
|
||||
if (!task) return null
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="sm:max-w-3xl max-h-[85vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Run history</DialogTitle>
|
||||
<DialogDescription>
|
||||
{task.name} — last 50 runs, newest first.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{loading ? (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||
<RefreshCw className="mr-1 inline size-3.5 animate-spin" /> Loading…
|
||||
</p>
|
||||
) : runs.length === 0 ? (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">No runs yet.</p>
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y rounded-md border">
|
||||
{runs.map((r) => {
|
||||
const open = expanded === r.id
|
||||
return (
|
||||
<li key={r.id} className="flex flex-col gap-1 px-3 py-2 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded(open ? null : r.id)}
|
||||
data-action={`task-run-${r.id}-toggle`}
|
||||
className="flex items-start justify-between gap-3 text-left"
|
||||
>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="flex items-center gap-2">
|
||||
<Badge variant={runVariant(r.status)}>{r.status}</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
attempt {r.attempt}
|
||||
</span>
|
||||
{r.response_status ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
HTTP {r.response_status}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
<Clock className="mr-1 inline size-3" />
|
||||
{r.started_at
|
||||
? `started ${new Date(r.started_at).toLocaleString()}`
|
||||
: `queued ${new Date(r.inserted_at).toLocaleString()}`}
|
||||
{r.finished_at
|
||||
? ` · finished ${new Date(r.finished_at).toLocaleString()}`
|
||||
: ""}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="ml-1 mt-1 flex flex-col gap-2">
|
||||
{r.error ? (
|
||||
<div>
|
||||
<div className="text-xs font-semibold text-destructive">Error</div>
|
||||
<pre className="overflow-x-auto rounded-md border bg-muted/50 p-2 text-xs">
|
||||
{r.error}
|
||||
</pre>
|
||||
</div>
|
||||
) : null}
|
||||
{r.response_body ? (
|
||||
<div>
|
||||
<div className="text-xs font-semibold">Response body</div>
|
||||
<pre className="max-h-48 overflow-auto rounded-md border bg-muted/50 p-2 text-xs">
|
||||
{r.response_body}
|
||||
</pre>
|
||||
</div>
|
||||
) : null}
|
||||
{!r.error && !r.response_body ? (
|
||||
<p className="text-xs text-muted-foreground">No response captured.</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose} data-action="task-runs-close">
|
||||
Close
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function runVariant(status: string): "default" | "secondary" | "destructive" | "outline" {
|
||||
if (status === "succeeded") return "default"
|
||||
if (status === "failed") return "destructive"
|
||||
if (status === "running" || status === "pending") return "secondary"
|
||||
return "outline"
|
||||
}
|
||||
|
||||
function countBy<T>(arr: T[], key: (x: T) => string): Record<string, number> {
|
||||
return arr.reduce<Record<string, number>>((acc, x) => {
|
||||
const k = key(x)
|
||||
acc[k] = (acc[k] ?? 0) + 1
|
||||
return acc
|
||||
}, {})
|
||||
}
|
||||
1090
app/routes/secrets.tsx
Normal file
1090
app/routes/secrets.tsx
Normal file
File diff suppressed because it is too large
Load Diff
866
app/routes/storage.tsx
Normal file
866
app/routes/storage.tsx
Normal file
@@ -0,0 +1,866 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { Link } from "react-router"
|
||||
import {
|
||||
CheckCircle2,
|
||||
HardDrive,
|
||||
Pause,
|
||||
Play,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
Star,
|
||||
Trash2,
|
||||
Wrench,
|
||||
} from "lucide-react"
|
||||
|
||||
import { ArcadiaError, useArcadiaClient } from "@crema/arcadia-client"
|
||||
import {
|
||||
ActionsCell,
|
||||
BadgeCell,
|
||||
DataTable,
|
||||
DateCell,
|
||||
Pagination,
|
||||
useTable,
|
||||
type ActionItem,
|
||||
type BadgeTone,
|
||||
type Column,
|
||||
} from "@crema/table-ui"
|
||||
import { SearchInput } from "@crema/search-ui"
|
||||
import { AlertBanner, ConfirmDialog, EmptyState, LoadingOverlay } from "@crema/feedback-ui"
|
||||
|
||||
import { AppShell } from "~/components/layout/app-shell"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "~/components/ui/dialog"
|
||||
import { Input } from "~/components/ui/input"
|
||||
import { Label } from "~/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select"
|
||||
import { Switch } from "~/components/ui/switch"
|
||||
import { Textarea } from "~/components/ui/textarea"
|
||||
import {
|
||||
activateStorageConfig,
|
||||
createStorageConfig,
|
||||
deactivateStorageConfig,
|
||||
deleteStorageConfig,
|
||||
isMaskedSecret,
|
||||
isSecretField,
|
||||
listStorageConfigs,
|
||||
markStorageConfigDegraded,
|
||||
markStorageConfigMaintenance,
|
||||
OPTIONAL_FIELDS,
|
||||
REQUIRED_FIELDS,
|
||||
setDefaultStorageConfig,
|
||||
updateStorageConfig,
|
||||
validateStorageConfig,
|
||||
type StorageBackend,
|
||||
type StorageConfig,
|
||||
type StorageConfigInput,
|
||||
type StorageStatus,
|
||||
} from "~/lib/arcadia/storage-configs"
|
||||
import { pageTitle } from "~/lib/page-meta"
|
||||
import { useSession } from "~/lib/session"
|
||||
import { useRegisterAdminContext } from "~/lib/admin-context"
|
||||
|
||||
export const meta = () => pageTitle("Storage")
|
||||
|
||||
type PendingAction =
|
||||
| { kind: "deactivate" | "degraded" | "maintenance" | "delete"; config: StorageConfig }
|
||||
| null
|
||||
|
||||
type EditorState =
|
||||
| { mode: "create" }
|
||||
| { mode: "edit"; config: StorageConfig }
|
||||
| null
|
||||
|
||||
export default function StorageRoute() {
|
||||
const session = useSession()
|
||||
const arcadia = useArcadiaClient()
|
||||
|
||||
const [configs, setConfigs] = useState<StorageConfig[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [info, setInfo] = useState<string | null>(null)
|
||||
const [pending, setPending] = useState<PendingAction>(null)
|
||||
const [editor, setEditor] = useState<EditorState>(null)
|
||||
const [search, setSearch] = useState("")
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setError(null)
|
||||
setLoading(true)
|
||||
try {
|
||||
const list = await listStorageConfigs(arcadia)
|
||||
setConfigs(list)
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Failed to load storage configs.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [arcadia])
|
||||
|
||||
useEffect(() => {
|
||||
if (session) refresh()
|
||||
}, [session, refresh])
|
||||
|
||||
const runAction = useCallback(
|
||||
async (action: PendingAction) => {
|
||||
if (!action) return
|
||||
try {
|
||||
if (action.kind === "deactivate") await deactivateStorageConfig(arcadia, action.config.id)
|
||||
else if (action.kind === "degraded")
|
||||
await markStorageConfigDegraded(arcadia, action.config.id)
|
||||
else if (action.kind === "maintenance")
|
||||
await markStorageConfigMaintenance(arcadia, action.config.id)
|
||||
else if (action.kind === "delete") await deleteStorageConfig(arcadia, action.config.id)
|
||||
setPending(null)
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Action failed.")
|
||||
setPending(null)
|
||||
}
|
||||
},
|
||||
[arcadia, refresh],
|
||||
)
|
||||
|
||||
const validate = useCallback(
|
||||
async (config: StorageConfig) => {
|
||||
setError(null)
|
||||
setInfo(null)
|
||||
try {
|
||||
const result = await validateStorageConfig(arcadia, config.id)
|
||||
if (result?.ok) {
|
||||
setInfo(`${config.name}: validation passed.`)
|
||||
} else {
|
||||
setError(`${config.name}: ${result?.message ?? "validation failed."}`)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Validation failed.")
|
||||
}
|
||||
},
|
||||
[arcadia],
|
||||
)
|
||||
|
||||
const columns = useMemo<Column<StorageConfig>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "name",
|
||||
header: "Name",
|
||||
accessor: "name",
|
||||
sortable: true,
|
||||
cell: (c) => (
|
||||
<span className="flex items-center gap-2 font-medium">
|
||||
{c.is_default ? <Star className="size-3.5 fill-amber-400 text-amber-400" /> : null}
|
||||
{c.name}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "backend",
|
||||
header: "Backend",
|
||||
accessor: "backend_type",
|
||||
sortable: true,
|
||||
cell: (c) => (
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs uppercase">
|
||||
{c.backend_type}
|
||||
</code>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: "Status",
|
||||
accessor: "status",
|
||||
sortable: true,
|
||||
cell: (c) => <BadgeCell label={c.status} tone={statusTone(c.status)} />,
|
||||
},
|
||||
{
|
||||
id: "size",
|
||||
header: "Max size",
|
||||
accessor: "max_file_size_bytes",
|
||||
sortable: true,
|
||||
cell: (c) => (
|
||||
<span className="text-muted-foreground">{formatBytes(c.max_file_size_bytes)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "updated",
|
||||
header: "Updated",
|
||||
accessor: "updated_at",
|
||||
sortable: true,
|
||||
cell: (c) => <DateCell value={c.updated_at} format="short" />,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
align: "right",
|
||||
cell: (c) => (
|
||||
<ActionsCell
|
||||
items={rowActions(c, {
|
||||
arcadia,
|
||||
refresh,
|
||||
setPending,
|
||||
setEditor,
|
||||
setError,
|
||||
validate,
|
||||
})}
|
||||
triggerDataAction={`storage-${slugify(c.name)}-actions`}
|
||||
/>
|
||||
),
|
||||
},
|
||||
],
|
||||
[arcadia, refresh, validate],
|
||||
)
|
||||
|
||||
const summary = useMemo(
|
||||
() => ({
|
||||
total: configs.length,
|
||||
byStatus: configs.reduce<Record<string, number>>((acc, c) => {
|
||||
acc[c.status] = (acc[c.status] ?? 0) + 1
|
||||
return acc
|
||||
}, {}),
|
||||
byBackend: configs.reduce<Record<string, number>>((acc, c) => {
|
||||
acc[c.backend_type] = (acc[c.backend_type] ?? 0) + 1
|
||||
return acc
|
||||
}, {}),
|
||||
configs: configs.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
backend_type: c.backend_type,
|
||||
status: c.status,
|
||||
is_default: c.is_default,
|
||||
max_file_size_bytes: c.max_file_size_bytes,
|
||||
updated_at: c.updated_at,
|
||||
})),
|
||||
}),
|
||||
[configs],
|
||||
)
|
||||
useRegisterAdminContext("storage", summary)
|
||||
|
||||
const table = useTable<StorageConfig>({
|
||||
data: configs,
|
||||
columns,
|
||||
getRowId: (c) => c.id,
|
||||
initialPageSize: 25,
|
||||
initialSearch: search,
|
||||
})
|
||||
useEffect(() => {
|
||||
table.setSearch(search)
|
||||
}, [search, table])
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<AppShell title="Storage">
|
||||
<div className="p-8">
|
||||
<Card className="max-w-md">
|
||||
<CardHeader>
|
||||
<CardTitle>Sign in required</CardTitle>
|
||||
<CardDescription>
|
||||
Storage administration requires an admin session.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button asChild>
|
||||
<Link to="/login?next=/storage">Sign in</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell title="Storage">
|
||||
<div className="flex flex-col gap-4 p-6">
|
||||
<header className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Storage</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Storage backends and credentials for the platform-admin tenant.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={refresh}
|
||||
disabled={loading}
|
||||
data-action="storage-refresh"
|
||||
>
|
||||
<RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setEditor({ mode: "create" })}
|
||||
data-action="storage-create"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
New storage config
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{error ? (
|
||||
<AlertBanner variant="error" dismissible onDismiss={() => setError(null)}>
|
||||
{error}
|
||||
</AlertBanner>
|
||||
) : null}
|
||||
{info ? (
|
||||
<AlertBanner variant="success" dismissible onDismiss={() => setInfo(null)}>
|
||||
{info}
|
||||
</AlertBanner>
|
||||
) : null}
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-4">
|
||||
<SearchInput
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
placeholder="Search by name, backend, or status"
|
||||
data-action="storage-search"
|
||||
className="max-w-sm flex-1"
|
||||
/>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{table.total} of {configs.length}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="relative p-0">
|
||||
<LoadingOverlay active={loading && configs.length === 0} label="Loading storage configs…" />
|
||||
{table.total === 0 && !loading ? (
|
||||
<EmptyState
|
||||
title={search ? "No configs match that search." : "No storage configs yet."}
|
||||
description={
|
||||
search
|
||||
? "Try a different name, backend, or status."
|
||||
: "Create your first storage config to start uploading objects."
|
||||
}
|
||||
className="py-12"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
rows={table.pageRows}
|
||||
getRowId={(c) => c.id}
|
||||
sort={table.sort}
|
||||
onSortToggle={table.toggleSort}
|
||||
loading={loading && configs.length > 0}
|
||||
stickyHeader
|
||||
/>
|
||||
<Pagination
|
||||
page={table.page}
|
||||
pageSize={table.pageSize}
|
||||
total={table.total}
|
||||
onPageChange={table.setPage}
|
||||
onPageSizeChange={table.setPageSize}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={pending?.kind === "deactivate"}
|
||||
onOpenChange={(o) => !o && setPending(null)}
|
||||
title="Deactivate storage config?"
|
||||
description={
|
||||
pending
|
||||
? `${pending.config.name} will stop accepting new uploads. Existing objects remain accessible.`
|
||||
: ""
|
||||
}
|
||||
confirmLabel="Deactivate"
|
||||
variant="default"
|
||||
onConfirm={() => runAction(pending)}
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={pending?.kind === "degraded"}
|
||||
onOpenChange={(o) => !o && setPending(null)}
|
||||
title="Mark as degraded?"
|
||||
description={
|
||||
pending
|
||||
? `${pending.config.name} will be flagged as degraded. The platform may route new uploads elsewhere.`
|
||||
: ""
|
||||
}
|
||||
confirmLabel="Mark degraded"
|
||||
variant="default"
|
||||
onConfirm={() => runAction(pending)}
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={pending?.kind === "maintenance"}
|
||||
onOpenChange={(o) => !o && setPending(null)}
|
||||
title="Mark as in maintenance?"
|
||||
description={
|
||||
pending
|
||||
? `${pending.config.name} will be put into maintenance mode.`
|
||||
: ""
|
||||
}
|
||||
confirmLabel="Mark maintenance"
|
||||
variant="default"
|
||||
onConfirm={() => runAction(pending)}
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={pending?.kind === "delete"}
|
||||
onOpenChange={(o) => !o && setPending(null)}
|
||||
title="Delete storage config?"
|
||||
description={
|
||||
pending
|
||||
? `${pending.config.name} will be permanently removed. Objects already stored on this backend may become unreachable.`
|
||||
: ""
|
||||
}
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
onConfirm={() => runAction(pending)}
|
||||
/>
|
||||
|
||||
<StorageEditorDialog
|
||||
state={editor}
|
||||
onClose={() => setEditor(null)}
|
||||
onSaved={async () => {
|
||||
setEditor(null)
|
||||
await refresh()
|
||||
}}
|
||||
onError={setError}
|
||||
/>
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
function statusTone(status: StorageStatus): BadgeTone {
|
||||
if (status === "active") return "success"
|
||||
if (status === "degraded") return "warning"
|
||||
if (status === "maintenance") return "warning"
|
||||
if (status === "inactive") return "default"
|
||||
return "default"
|
||||
}
|
||||
|
||||
function rowActions(
|
||||
c: StorageConfig,
|
||||
ctx: {
|
||||
arcadia: ReturnType<typeof useArcadiaClient>
|
||||
refresh: () => Promise<void>
|
||||
setPending: (p: PendingAction) => void
|
||||
setEditor: (s: EditorState) => void
|
||||
setError: (msg: string | null) => void
|
||||
validate: (c: StorageConfig) => Promise<void>
|
||||
},
|
||||
): ActionItem[] {
|
||||
const { arcadia, refresh, setPending, setEditor, setError, validate } = ctx
|
||||
const slug = slugify(c.name)
|
||||
const items: ActionItem[] = []
|
||||
|
||||
items.push({
|
||||
id: "validate",
|
||||
label: "Validate",
|
||||
icon: <ShieldCheck className="size-4" />,
|
||||
dataAction: `storage-${slug}-validate`,
|
||||
onSelect: () => validate(c),
|
||||
})
|
||||
|
||||
items.push({
|
||||
id: "edit",
|
||||
label: "Edit",
|
||||
dataAction: `storage-${slug}-edit`,
|
||||
onSelect: () => setEditor({ mode: "edit", config: c }),
|
||||
})
|
||||
|
||||
if (c.status === "active") {
|
||||
items.push({
|
||||
id: "deactivate",
|
||||
label: "Deactivate",
|
||||
icon: <Pause className="size-4" />,
|
||||
dataAction: `storage-${slug}-deactivate`,
|
||||
onSelect: () => setPending({ kind: "deactivate", config: c }),
|
||||
})
|
||||
} else {
|
||||
items.push({
|
||||
id: "activate",
|
||||
label: "Activate",
|
||||
icon: <Play className="size-4" />,
|
||||
dataAction: `storage-${slug}-activate`,
|
||||
onSelect: async () => {
|
||||
try {
|
||||
await activateStorageConfig(arcadia, c.id)
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Activate failed.")
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (!c.is_default) {
|
||||
items.push({
|
||||
id: "set-default",
|
||||
label: "Set as default",
|
||||
icon: <Star className="size-4" />,
|
||||
dataAction: `storage-${slug}-set-default`,
|
||||
onSelect: async () => {
|
||||
try {
|
||||
await setDefaultStorageConfig(arcadia, c.id)
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Set default failed.")
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
items.push({
|
||||
id: "mark-degraded",
|
||||
label: "Mark degraded",
|
||||
icon: <Wrench className="size-4" />,
|
||||
dataAction: `storage-${slug}-mark-degraded`,
|
||||
onSelect: () => setPending({ kind: "degraded", config: c }),
|
||||
})
|
||||
items.push({
|
||||
id: "mark-maintenance",
|
||||
label: "Mark maintenance",
|
||||
icon: <Wrench className="size-4" />,
|
||||
dataAction: `storage-${slug}-mark-maintenance`,
|
||||
onSelect: () => setPending({ kind: "maintenance", config: c }),
|
||||
})
|
||||
|
||||
items.push({
|
||||
id: "delete",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="size-4" />,
|
||||
destructive: true,
|
||||
dataAction: `storage-${slug}-delete`,
|
||||
onSelect: () => setPending({ kind: "delete", config: c }),
|
||||
})
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
function StorageEditorDialog({
|
||||
state,
|
||||
onClose,
|
||||
onSaved,
|
||||
onError,
|
||||
}: {
|
||||
state: EditorState
|
||||
onClose: () => void
|
||||
onSaved: () => Promise<void>
|
||||
onError: (msg: string | null) => void
|
||||
}) {
|
||||
const arcadia = useArcadiaClient()
|
||||
const open = state !== null
|
||||
const isEdit = state?.mode === "edit"
|
||||
const initial = isEdit ? state.config : null
|
||||
|
||||
const [name, setName] = useState("")
|
||||
const [backend, setBackend] = useState<StorageBackend>("s3")
|
||||
const [isDefault, setIsDefault] = useState(false)
|
||||
const [maxSize, setMaxSize] = useState<string>("")
|
||||
const [allowedTypes, setAllowedTypes] = useState<string>("")
|
||||
const [fields, setFields] = useState<Record<string, string>>({})
|
||||
const [secretTouched, setSecretTouched] = useState<Record<string, boolean>>({})
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// Reset form whenever the dialog opens / target changes.
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
if (initial) {
|
||||
setName(initial.name)
|
||||
setBackend(initial.backend_type)
|
||||
setIsDefault(initial.is_default)
|
||||
setMaxSize(
|
||||
initial.max_file_size_bytes == null ? "" : String(initial.max_file_size_bytes),
|
||||
)
|
||||
setAllowedTypes((initial.allowed_content_types ?? []).join(", "))
|
||||
const initialFields: Record<string, string> = {}
|
||||
const cfg = (initial.config ?? {}) as Record<string, unknown>
|
||||
for (const k of Object.keys(cfg)) {
|
||||
const v = cfg[k]
|
||||
initialFields[k] = isMaskedSecret(v) ? "" : v == null ? "" : String(v)
|
||||
}
|
||||
setFields(initialFields)
|
||||
setSecretTouched({})
|
||||
} else {
|
||||
setName("")
|
||||
setBackend("s3")
|
||||
setIsDefault(false)
|
||||
setMaxSize("")
|
||||
setAllowedTypes("")
|
||||
setFields({})
|
||||
setSecretTouched({})
|
||||
}
|
||||
}, [open, initial])
|
||||
|
||||
const required = REQUIRED_FIELDS[backend]
|
||||
const optional = OPTIONAL_FIELDS[backend]
|
||||
|
||||
const setField = (key: string, value: string) => {
|
||||
setFields((f) => ({ ...f, [key]: value }))
|
||||
if (isSecretField(backend, key)) {
|
||||
setSecretTouched((t) => ({ ...t, [key]: true }))
|
||||
}
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
onError(null)
|
||||
setSaving(true)
|
||||
try {
|
||||
const config: Record<string, unknown> = {}
|
||||
for (const k of [...required, ...optional]) {
|
||||
const v = fields[k]
|
||||
if (isSecretField(backend, k)) {
|
||||
// Only send a secret if the user typed a fresh value.
|
||||
if (secretTouched[k] && v !== "") config[k] = v
|
||||
} else if (v !== undefined && v !== "") {
|
||||
config[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
const allowed = allowedTypes
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const max = maxSize.trim() === "" ? null : Number(maxSize)
|
||||
if (max != null && Number.isNaN(max)) {
|
||||
throw new Error("Max file size must be a number (bytes).")
|
||||
}
|
||||
|
||||
const input: StorageConfigInput = {
|
||||
name,
|
||||
backend_type: backend,
|
||||
config,
|
||||
is_default: isDefault,
|
||||
max_file_size_bytes: max,
|
||||
allowed_content_types: allowed.length ? allowed : undefined,
|
||||
}
|
||||
|
||||
if (isEdit && initial) {
|
||||
await updateStorageConfig(arcadia, initial.id, input)
|
||||
} else {
|
||||
await createStorageConfig(arcadia, input)
|
||||
}
|
||||
await onSaved()
|
||||
} catch (err) {
|
||||
onError(err instanceof ArcadiaError ? err.message : err instanceof Error ? err.message : "Save failed.")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? "Edit storage config" : "New storage config"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{isEdit
|
||||
? "Secrets are write-only — leave masked fields blank to keep the existing value."
|
||||
: "Connect a backend to start storing objects on this tenant."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="storage-name">Name</Label>
|
||||
<Input
|
||||
id="storage-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Primary S3 storage"
|
||||
data-action="storage-form-name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Backend</Label>
|
||||
<Select
|
||||
value={backend}
|
||||
onValueChange={(v) => setBackend(v as StorageBackend)}
|
||||
disabled={isEdit}
|
||||
>
|
||||
<SelectTrigger data-action="storage-form-backend">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="s3">S3 (or S3-compatible)</SelectItem>
|
||||
<SelectItem value="gcs">Google Cloud Storage</SelectItem>
|
||||
<SelectItem value="local">Local filesystem</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{required.map((k) => (
|
||||
<BackendField
|
||||
key={k}
|
||||
label={fieldLabel(k)}
|
||||
field={k}
|
||||
backend={backend}
|
||||
value={fields[k] ?? ""}
|
||||
originalIsMasked={
|
||||
!!initial && isMaskedSecret((initial.config ?? {})[k as keyof typeof initial.config])
|
||||
}
|
||||
touched={!!secretTouched[k]}
|
||||
onChange={(v) => setField(k, v)}
|
||||
required
|
||||
/>
|
||||
))}
|
||||
{optional.map((k) => (
|
||||
<BackendField
|
||||
key={k}
|
||||
label={fieldLabel(k)}
|
||||
field={k}
|
||||
backend={backend}
|
||||
value={fields[k] ?? ""}
|
||||
originalIsMasked={false}
|
||||
touched={false}
|
||||
onChange={(v) => setField(k, v)}
|
||||
/>
|
||||
))}
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="storage-max-size">Max file size (bytes)</Label>
|
||||
<Input
|
||||
id="storage-max-size"
|
||||
value={maxSize}
|
||||
onChange={(e) => setMaxSize(e.target.value)}
|
||||
placeholder="e.g. 104857600"
|
||||
data-action="storage-form-max-size"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="storage-allowed-types">Allowed content types (comma-separated)</Label>
|
||||
<Textarea
|
||||
id="storage-allowed-types"
|
||||
value={allowedTypes}
|
||||
onChange={(e) => setAllowedTypes(e.target.value)}
|
||||
placeholder="image/jpeg, image/png, application/pdf"
|
||||
data-action="storage-form-allowed-types"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-md border px-3 py-2">
|
||||
<div>
|
||||
<div className="text-sm font-medium">Default backend</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
New uploads go here unless another backend is specified.
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isDefault}
|
||||
onCheckedChange={setIsDefault}
|
||||
data-action="storage-form-is-default"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose} disabled={saving} data-action="storage-form-cancel">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={submit} disabled={saving || name.trim() === ""} data-action="storage-form-save">
|
||||
{saving ? (
|
||||
<RefreshCw className="size-4 animate-spin" />
|
||||
) : (
|
||||
<CheckCircle2 className="size-4" />
|
||||
)}
|
||||
{isEdit ? "Save changes" : "Create"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function BackendField({
|
||||
label,
|
||||
field,
|
||||
backend,
|
||||
value,
|
||||
originalIsMasked,
|
||||
touched,
|
||||
onChange,
|
||||
required,
|
||||
}: {
|
||||
label: string
|
||||
field: string
|
||||
backend: StorageBackend
|
||||
value: string
|
||||
originalIsMasked: boolean
|
||||
touched: boolean
|
||||
onChange: (v: string) => void
|
||||
required?: boolean
|
||||
}) {
|
||||
const secret = isSecretField(backend, field)
|
||||
const isJson = field === "service_account_json"
|
||||
const placeholder = secret && originalIsMasked && !touched ? "•••••• (unchanged)" : ""
|
||||
const inputId = `storage-config-field-${field}`
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={inputId}>
|
||||
{label}
|
||||
{required ? <span className="ml-1 text-destructive">*</span> : null}
|
||||
</Label>
|
||||
{isJson ? (
|
||||
<Textarea
|
||||
id={inputId}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder || "Paste service account JSON"}
|
||||
rows={4}
|
||||
data-action={`storage-form-config-${field}`}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
id={inputId}
|
||||
type={secret ? "password" : "text"}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
data-action={`storage-form-config-${field}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function fieldLabel(key: string): string {
|
||||
return key
|
||||
.split("_")
|
||||
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
function slugify(s: string): string {
|
||||
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "config"
|
||||
}
|
||||
|
||||
function formatBytes(n: number | null): string {
|
||||
if (n == null) return "—"
|
||||
const units = ["B", "KB", "MB", "GB", "TB"]
|
||||
let i = 0
|
||||
let v = n
|
||||
while (v >= 1024 && i < units.length - 1) {
|
||||
v /= 1024
|
||||
i++
|
||||
}
|
||||
return `${v < 10 ? v.toFixed(1) : Math.round(v)} ${units[i]}`
|
||||
}
|
||||
1519
app/routes/users.tsx
Normal file
1519
app/routes/users.tsx
Normal file
File diff suppressed because it is too large
Load Diff
921
app/routes/webhooks.tsx
Normal file
921
app/routes/webhooks.tsx
Normal file
@@ -0,0 +1,921 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { Link } from "react-router"
|
||||
import {
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
Copy,
|
||||
History,
|
||||
KeyRound,
|
||||
Pause,
|
||||
Play,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
RotateCw,
|
||||
Send,
|
||||
Trash2,
|
||||
Webhook as WebhookIcon,
|
||||
} from "lucide-react"
|
||||
|
||||
import { ArcadiaError, useArcadiaClient } from "@crema/arcadia-client"
|
||||
import {
|
||||
ActionsCell,
|
||||
BadgeCell,
|
||||
DataTable,
|
||||
DateCell,
|
||||
Pagination,
|
||||
useTable,
|
||||
type ActionItem,
|
||||
type BadgeTone,
|
||||
type Column,
|
||||
} from "@crema/table-ui"
|
||||
import { SearchInput } from "@crema/search-ui"
|
||||
import { AlertBanner, ConfirmDialog, EmptyState, LoadingOverlay } from "@crema/feedback-ui"
|
||||
|
||||
import { AppShell } from "~/components/layout/app-shell"
|
||||
import { Badge } from "~/components/ui/badge"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "~/components/ui/dialog"
|
||||
import { Input } from "~/components/ui/input"
|
||||
import { Label } from "~/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select"
|
||||
import { Textarea } from "~/components/ui/textarea"
|
||||
import {
|
||||
COMMON_WEBHOOK_EVENTS,
|
||||
createWebhook,
|
||||
deleteWebhook,
|
||||
listWebhookDeliveries,
|
||||
listWebhooks,
|
||||
pauseWebhook,
|
||||
regenerateWebhookSecret,
|
||||
resumeWebhook,
|
||||
testWebhook,
|
||||
updateWebhook,
|
||||
type Webhook,
|
||||
type WebhookDelivery,
|
||||
type WebhookInput,
|
||||
type WebhookRetryStrategy,
|
||||
type WebhookStatus,
|
||||
} from "~/lib/arcadia/webhooks"
|
||||
import { pageTitle } from "~/lib/page-meta"
|
||||
import { useSession } from "~/lib/session"
|
||||
import { useRegisterAdminContext } from "~/lib/admin-context"
|
||||
|
||||
export const meta = () => pageTitle("Webhooks")
|
||||
|
||||
type EditorState =
|
||||
| { mode: "create" }
|
||||
| { mode: "edit"; webhook: Webhook }
|
||||
| null
|
||||
|
||||
export default function WebhooksRoute() {
|
||||
const session = useSession()
|
||||
const arcadia = useArcadiaClient()
|
||||
|
||||
const [webhooks, setWebhooks] = useState<Webhook[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [info, setInfo] = useState<string | null>(null)
|
||||
const [search, setSearch] = useState("")
|
||||
const [editor, setEditor] = useState<EditorState>(null)
|
||||
const [pendingDelete, setPendingDelete] = useState<Webhook | null>(null)
|
||||
const [deliveriesFor, setDeliveriesFor] = useState<Webhook | null>(null)
|
||||
const [revealedSecret, setRevealedSecret] = useState<{
|
||||
webhookId: string
|
||||
secret: string
|
||||
isNew?: boolean
|
||||
} | null>(null)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setError(null)
|
||||
setLoading(true)
|
||||
try {
|
||||
setWebhooks(await listWebhooks(arcadia))
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Failed to load webhooks.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [arcadia])
|
||||
|
||||
useEffect(() => {
|
||||
if (session) refresh()
|
||||
}, [session, refresh])
|
||||
|
||||
const columns = useMemo<Column<Webhook>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "url",
|
||||
header: "URL",
|
||||
accessor: "url",
|
||||
sortable: true,
|
||||
cell: (w) => (
|
||||
<div className="flex flex-col">
|
||||
<span className="font-mono text-xs">{w.url}</span>
|
||||
{w.description ? (
|
||||
<span className="text-xs text-muted-foreground">{w.description}</span>
|
||||
) : null}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: "Status",
|
||||
accessor: "status",
|
||||
sortable: true,
|
||||
cell: (w) => <BadgeCell label={w.status} tone={statusTone(w.status)} />,
|
||||
},
|
||||
{
|
||||
id: "events",
|
||||
header: "Events",
|
||||
cell: (w) =>
|
||||
w.events.length === 0 ? (
|
||||
<span className="text-muted-foreground">all</span>
|
||||
) : (
|
||||
<span className="text-xs">{w.events.length}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "success",
|
||||
header: "Success",
|
||||
accessor: "success_count",
|
||||
sortable: true,
|
||||
cell: (w) => <span className="font-mono text-xs">{w.success_count}</span>,
|
||||
},
|
||||
{
|
||||
id: "failure",
|
||||
header: "Failure",
|
||||
accessor: "failure_count",
|
||||
sortable: true,
|
||||
cell: (w) => (
|
||||
<span
|
||||
className={`font-mono text-xs ${
|
||||
w.failure_count > 0 ? "text-destructive" : "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{w.failure_count}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "last",
|
||||
header: "Last triggered",
|
||||
accessor: "last_triggered_at",
|
||||
sortable: true,
|
||||
cell: (w) =>
|
||||
w.last_triggered_at ? (
|
||||
<DateCell value={w.last_triggered_at} format="short" />
|
||||
) : (
|
||||
<span className="text-muted-foreground">never</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
align: "right",
|
||||
cell: (w) => (
|
||||
<ActionsCell
|
||||
items={rowActions(w, {
|
||||
arcadia,
|
||||
refresh,
|
||||
setEditor,
|
||||
setPendingDelete,
|
||||
setDeliveriesFor,
|
||||
setRevealedSecret,
|
||||
setError,
|
||||
setInfo,
|
||||
})}
|
||||
triggerDataAction={`webhook-${w.id}-actions`}
|
||||
/>
|
||||
),
|
||||
},
|
||||
],
|
||||
[arcadia, refresh],
|
||||
)
|
||||
|
||||
const summary = useMemo(
|
||||
() => ({
|
||||
total: webhooks.length,
|
||||
byStatus: countBy(webhooks, (w) => w.status),
|
||||
total_failures: webhooks.reduce((a, w) => a + w.failure_count, 0),
|
||||
total_successes: webhooks.reduce((a, w) => a + w.success_count, 0),
|
||||
webhooks: webhooks.map((w) => ({
|
||||
url: w.url,
|
||||
status: w.status,
|
||||
events: w.events,
|
||||
success_count: w.success_count,
|
||||
failure_count: w.failure_count,
|
||||
last_triggered_at: w.last_triggered_at,
|
||||
})),
|
||||
}),
|
||||
[webhooks],
|
||||
)
|
||||
useRegisterAdminContext("webhooks", summary)
|
||||
|
||||
const table = useTable<Webhook>({
|
||||
data: webhooks,
|
||||
columns,
|
||||
getRowId: (w) => w.id,
|
||||
initialPageSize: 25,
|
||||
initialSearch: search,
|
||||
})
|
||||
useEffect(() => {
|
||||
table.setSearch(search)
|
||||
}, [search, table])
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<AppShell title="Webhooks">
|
||||
<div className="p-8">
|
||||
<Card className="max-w-md">
|
||||
<CardHeader>
|
||||
<CardTitle>Sign in required</CardTitle>
|
||||
<CardDescription>Webhook administration requires an admin session.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button asChild>
|
||||
<Link to="/login?next=/webhooks">Sign in</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell title="Webhooks">
|
||||
<div className="flex flex-col gap-4 p-6">
|
||||
<header className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Webhooks</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Outbound HTTP callbacks for platform events. Each delivery is signed with the
|
||||
endpoint's secret.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={refresh}
|
||||
disabled={loading}
|
||||
data-action="webhooks-refresh"
|
||||
>
|
||||
<RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setEditor({ mode: "create" })}
|
||||
data-action="webhooks-create"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
New webhook
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{error ? (
|
||||
<AlertBanner variant="error" dismissible onDismiss={() => setError(null)}>
|
||||
{error}
|
||||
</AlertBanner>
|
||||
) : null}
|
||||
{info ? (
|
||||
<AlertBanner variant="success" dismissible onDismiss={() => setInfo(null)}>
|
||||
{info}
|
||||
</AlertBanner>
|
||||
) : null}
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center gap-3">
|
||||
<SearchInput
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
placeholder="Search by URL, description, or status"
|
||||
data-action="webhooks-search"
|
||||
className="max-w-sm flex-1"
|
||||
/>
|
||||
<div className="ml-auto text-xs text-muted-foreground">
|
||||
{table.total} of {webhooks.length}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="relative p-0">
|
||||
<LoadingOverlay active={loading && webhooks.length === 0} label="Loading webhooks…" />
|
||||
{table.total === 0 && !loading ? (
|
||||
<EmptyState
|
||||
icon={<WebhookIcon className="size-6" />}
|
||||
title={search ? "No webhooks match." : "No webhooks yet."}
|
||||
description={
|
||||
search
|
||||
? "Try a different search."
|
||||
: "Add an endpoint to receive event notifications from arcadia."
|
||||
}
|
||||
className="py-12"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
rows={table.pageRows}
|
||||
getRowId={(w) => w.id}
|
||||
sort={table.sort}
|
||||
onSortToggle={table.toggleSort}
|
||||
loading={loading && webhooks.length > 0}
|
||||
stickyHeader
|
||||
/>
|
||||
<Pagination
|
||||
page={table.page}
|
||||
pageSize={table.pageSize}
|
||||
total={table.total}
|
||||
onPageChange={table.setPage}
|
||||
onPageSizeChange={table.setPageSize}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={pendingDelete !== null}
|
||||
onOpenChange={(o) => !o && setPendingDelete(null)}
|
||||
title="Delete webhook?"
|
||||
description={
|
||||
pendingDelete
|
||||
? `${pendingDelete.url} will stop receiving events. Pending retries are abandoned.`
|
||||
: ""
|
||||
}
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
onConfirm={async () => {
|
||||
if (!pendingDelete) return
|
||||
try {
|
||||
await deleteWebhook(arcadia, pendingDelete.id)
|
||||
setPendingDelete(null)
|
||||
setInfo("Webhook deleted.")
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Delete failed.")
|
||||
setPendingDelete(null)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<WebhookEditorDialog
|
||||
state={editor}
|
||||
onClose={() => setEditor(null)}
|
||||
onSaved={async (created) => {
|
||||
setEditor(null)
|
||||
if (created?.secret) {
|
||||
setRevealedSecret({ webhookId: created.id, secret: created.secret, isNew: true })
|
||||
}
|
||||
await refresh()
|
||||
}}
|
||||
onError={setError}
|
||||
/>
|
||||
|
||||
<DeliveriesDialog
|
||||
webhook={deliveriesFor}
|
||||
onClose={() => setDeliveriesFor(null)}
|
||||
onError={setError}
|
||||
/>
|
||||
|
||||
<RevealSecretDialog reveal={revealedSecret} onClose={() => setRevealedSecret(null)} />
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
function statusTone(s: WebhookStatus): BadgeTone {
|
||||
if (s === "active") return "success"
|
||||
if (s === "paused") return "warning"
|
||||
return "default"
|
||||
}
|
||||
|
||||
function rowActions(
|
||||
w: Webhook,
|
||||
ctx: {
|
||||
arcadia: ReturnType<typeof useArcadiaClient>
|
||||
refresh: () => Promise<void>
|
||||
setEditor: (s: EditorState) => void
|
||||
setPendingDelete: (w: Webhook | null) => void
|
||||
setDeliveriesFor: (w: Webhook | null) => void
|
||||
setRevealedSecret: (
|
||||
r: { webhookId: string; secret: string; isNew?: boolean } | null,
|
||||
) => void
|
||||
setError: (m: string | null) => void
|
||||
setInfo: (m: string | null) => void
|
||||
},
|
||||
): ActionItem[] {
|
||||
const {
|
||||
arcadia,
|
||||
refresh,
|
||||
setEditor,
|
||||
setPendingDelete,
|
||||
setDeliveriesFor,
|
||||
setRevealedSecret,
|
||||
setError,
|
||||
setInfo,
|
||||
} = ctx
|
||||
const items: ActionItem[] = []
|
||||
|
||||
items.push({
|
||||
id: "edit",
|
||||
label: "Edit",
|
||||
dataAction: `webhook-${w.id}-edit`,
|
||||
onSelect: () => setEditor({ mode: "edit", webhook: w }),
|
||||
})
|
||||
items.push({
|
||||
id: "deliveries",
|
||||
label: "View deliveries",
|
||||
icon: <History className="size-4" />,
|
||||
dataAction: `webhook-${w.id}-deliveries`,
|
||||
onSelect: () => setDeliveriesFor(w),
|
||||
})
|
||||
items.push({
|
||||
id: "test",
|
||||
label: "Send test event",
|
||||
icon: <Send className="size-4" />,
|
||||
dataAction: `webhook-${w.id}-test`,
|
||||
onSelect: async () => {
|
||||
try {
|
||||
const r = await testWebhook(arcadia, w.id)
|
||||
setInfo(r.ok === false ? r.message ?? "Test failed." : "Test event sent.")
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Test failed.")
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
if (w.status === "active") {
|
||||
items.push({
|
||||
id: "pause",
|
||||
label: "Pause",
|
||||
icon: <Pause className="size-4" />,
|
||||
dataAction: `webhook-${w.id}-pause`,
|
||||
onSelect: async () => {
|
||||
try {
|
||||
await pauseWebhook(arcadia, w.id)
|
||||
setInfo("Webhook paused.")
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Pause failed.")
|
||||
}
|
||||
},
|
||||
})
|
||||
} else {
|
||||
items.push({
|
||||
id: "resume",
|
||||
label: "Resume",
|
||||
icon: <Play className="size-4" />,
|
||||
dataAction: `webhook-${w.id}-resume`,
|
||||
onSelect: async () => {
|
||||
try {
|
||||
await resumeWebhook(arcadia, w.id)
|
||||
setInfo("Webhook resumed.")
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Resume failed.")
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
items.push({
|
||||
id: "regen-secret",
|
||||
label: "Regenerate secret",
|
||||
icon: <RotateCw className="size-4" />,
|
||||
dataAction: `webhook-${w.id}-regen-secret`,
|
||||
onSelect: async () => {
|
||||
try {
|
||||
const updated = await regenerateWebhookSecret(arcadia, w.id)
|
||||
if (updated.secret) {
|
||||
setRevealedSecret({ webhookId: updated.id, secret: updated.secret })
|
||||
}
|
||||
await refresh()
|
||||
} catch (err) {
|
||||
setError(err instanceof ArcadiaError ? err.message : "Regenerate failed.")
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
items.push({
|
||||
id: "delete",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="size-4" />,
|
||||
destructive: true,
|
||||
dataAction: `webhook-${w.id}-delete`,
|
||||
onSelect: () => setPendingDelete(w),
|
||||
})
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
function WebhookEditorDialog({
|
||||
state,
|
||||
onClose,
|
||||
onSaved,
|
||||
onError,
|
||||
}: {
|
||||
state: EditorState
|
||||
onClose: () => void
|
||||
onSaved: (created?: Webhook) => Promise<void>
|
||||
onError: (msg: string | null) => void
|
||||
}) {
|
||||
const arcadia = useArcadiaClient()
|
||||
const open = state !== null
|
||||
const isEdit = state?.mode === "edit"
|
||||
const initial = isEdit ? state.webhook : null
|
||||
|
||||
const [url, setUrl] = useState("")
|
||||
const [description, setDescription] = useState("")
|
||||
const [eventsText, setEventsText] = useState("")
|
||||
const [headersText, setHeadersText] = useState("")
|
||||
const [maxRetries, setMaxRetries] = useState("3")
|
||||
const [retryStrategy, setRetryStrategy] = useState<WebhookRetryStrategy>("exponential")
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
if (initial) {
|
||||
setUrl(initial.url)
|
||||
setDescription(initial.description ?? "")
|
||||
setEventsText(initial.events.join("\n"))
|
||||
setHeadersText(
|
||||
Object.entries(initial.headers ?? {})
|
||||
.map(([k, v]) => `${k}: ${v}`)
|
||||
.join("\n"),
|
||||
)
|
||||
setMaxRetries(String(initial.max_retries))
|
||||
setRetryStrategy(initial.retry_strategy)
|
||||
} else {
|
||||
setUrl("")
|
||||
setDescription("")
|
||||
setEventsText("")
|
||||
setHeadersText("")
|
||||
setMaxRetries("3")
|
||||
setRetryStrategy("exponential")
|
||||
}
|
||||
}, [open, initial])
|
||||
|
||||
const submit = async () => {
|
||||
onError(null)
|
||||
setSaving(true)
|
||||
try {
|
||||
const events = eventsText
|
||||
.split(/\r?\n/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
const headers: Record<string, string> = {}
|
||||
for (const line of headersText.split(/\r?\n/)) {
|
||||
const idx = line.indexOf(":")
|
||||
if (idx <= 0) continue
|
||||
const k = line.slice(0, idx).trim()
|
||||
const v = line.slice(idx + 1).trim()
|
||||
if (k) headers[k] = v
|
||||
}
|
||||
const input: WebhookInput = {
|
||||
url,
|
||||
description: description || null,
|
||||
events,
|
||||
headers,
|
||||
max_retries: Math.max(0, Number(maxRetries) || 0),
|
||||
retry_strategy: retryStrategy,
|
||||
}
|
||||
if (isEdit && initial) {
|
||||
const updated = await updateWebhook(arcadia, initial.id, input)
|
||||
await onSaved(updated)
|
||||
} else {
|
||||
const created = await createWebhook(arcadia, input)
|
||||
await onSaved(created)
|
||||
}
|
||||
} catch (err) {
|
||||
onError(
|
||||
err instanceof ArcadiaError
|
||||
? err.message
|
||||
: err instanceof Error
|
||||
? err.message
|
||||
: "Save failed.",
|
||||
)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? "Edit webhook" : "New webhook"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{isEdit
|
||||
? "Update the destination and event filter."
|
||||
: "Arcadia POSTs JSON payloads to this URL when the listed events fire."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="webhook-url">URL</Label>
|
||||
<Input
|
||||
id="webhook-url"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder="https://example.com/webhooks/arcadia"
|
||||
data-action="webhook-form-url"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="webhook-description">Description</Label>
|
||||
<Input
|
||||
id="webhook-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
data-action="webhook-form-description"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="webhook-events">Events (one per line, blank = all events)</Label>
|
||||
<Textarea
|
||||
id="webhook-events"
|
||||
rows={6}
|
||||
value={eventsText}
|
||||
onChange={(e) => setEventsText(e.target.value)}
|
||||
placeholder={COMMON_WEBHOOK_EVENTS.slice(0, 5).join("\n")}
|
||||
data-action="webhook-form-events"
|
||||
/>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{COMMON_WEBHOOK_EVENTS.map((ev) => {
|
||||
const has = eventsText
|
||||
.split(/\r?\n/)
|
||||
.some((l) => l.trim() === ev)
|
||||
return (
|
||||
<button
|
||||
key={ev}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setEventsText((prev) => {
|
||||
const lines = prev.split(/\r?\n/).map((l) => l.trim()).filter(Boolean)
|
||||
if (has) return lines.filter((l) => l !== ev).join("\n")
|
||||
return [...lines, ev].join("\n")
|
||||
})
|
||||
}}
|
||||
data-action={`webhook-form-event-${ev}`}
|
||||
className={`rounded-full border px-2 py-0.5 text-xs font-medium transition-colors ${
|
||||
has
|
||||
? "border-primary bg-primary/10 text-primary"
|
||||
: "border-border text-muted-foreground hover:bg-accent"
|
||||
}`}
|
||||
>
|
||||
{ev}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="webhook-headers">Custom headers (key: value, one per line)</Label>
|
||||
<Textarea
|
||||
id="webhook-headers"
|
||||
rows={3}
|
||||
value={headersText}
|
||||
onChange={(e) => setHeadersText(e.target.value)}
|
||||
placeholder="Authorization: Bearer xyz"
|
||||
data-action="webhook-form-headers"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="webhook-retries">Max retries</Label>
|
||||
<Input
|
||||
id="webhook-retries"
|
||||
type="number"
|
||||
min={0}
|
||||
value={maxRetries}
|
||||
onChange={(e) => setMaxRetries(e.target.value)}
|
||||
data-action="webhook-form-retries"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Retry strategy</Label>
|
||||
<Select
|
||||
value={retryStrategy}
|
||||
onValueChange={(v) => setRetryStrategy(v as WebhookRetryStrategy)}
|
||||
>
|
||||
<SelectTrigger data-action="webhook-form-retry-strategy">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="exponential">Exponential</SelectItem>
|
||||
<SelectItem value="linear">Linear</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose} disabled={saving} data-action="webhook-form-cancel">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={submit} disabled={saving || !url} data-action="webhook-form-save">
|
||||
{saving ? <RefreshCw className="size-4 animate-spin" /> : <CheckCircle2 className="size-4" />}
|
||||
{isEdit ? "Save" : "Create"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function DeliveriesDialog({
|
||||
webhook,
|
||||
onClose,
|
||||
onError,
|
||||
}: {
|
||||
webhook: Webhook | null
|
||||
onClose: () => void
|
||||
onError: (msg: string | null) => void
|
||||
}) {
|
||||
const arcadia = useArcadiaClient()
|
||||
const [deliveries, setDeliveries] = useState<WebhookDelivery[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
if (!webhook) return
|
||||
let mounted = true
|
||||
setLoading(true)
|
||||
listWebhookDeliveries(arcadia, webhook.id, { limit: 50 })
|
||||
.then((d) => mounted && setDeliveries(d))
|
||||
.catch((err) =>
|
||||
onError(err instanceof ArcadiaError ? err.message : "Failed to load deliveries."),
|
||||
)
|
||||
.finally(() => mounted && setLoading(false))
|
||||
return () => {
|
||||
mounted = false
|
||||
}
|
||||
}, [arcadia, webhook, onError])
|
||||
|
||||
if (!webhook) return null
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="sm:max-w-3xl max-h-[85vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Recent deliveries</DialogTitle>
|
||||
<DialogDescription>
|
||||
<span className="font-mono text-xs">{webhook.url}</span>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{loading ? (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||
<RefreshCw className="mr-1 inline size-3.5 animate-spin" /> Loading…
|
||||
</p>
|
||||
) : deliveries.length === 0 ? (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||
No deliveries recorded yet.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y rounded-md border">
|
||||
{deliveries.map((d) => (
|
||||
<li key={d.id} className="flex items-start justify-between gap-3 px-3 py-2 text-sm">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={
|
||||
d.status === "delivered"
|
||||
? "default"
|
||||
: d.status === "failed"
|
||||
? "destructive"
|
||||
: "secondary"
|
||||
}
|
||||
>
|
||||
{d.status}
|
||||
</Badge>
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">
|
||||
{d.event_type}
|
||||
</code>
|
||||
{d.response_status ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
HTTP {d.response_status}
|
||||
</span>
|
||||
) : null}
|
||||
{d.response_time_ms != null ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{d.response_time_ms}ms
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
<Clock className="mr-1 inline size-3" />
|
||||
attempt {d.attempt} ·{" "}
|
||||
{d.completed_at
|
||||
? new Date(d.completed_at).toLocaleString()
|
||||
: new Date(d.inserted_at).toLocaleString()}
|
||||
</span>
|
||||
{d.error_message ? (
|
||||
<span className="text-xs text-destructive">{d.error_message}</span>
|
||||
) : null}
|
||||
{d.next_retry_at ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
next retry {new Date(d.next_retry_at).toLocaleString()}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose} data-action="webhook-deliveries-close">
|
||||
Close
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function RevealSecretDialog({
|
||||
reveal,
|
||||
onClose,
|
||||
}: {
|
||||
reveal: { webhookId: string; secret: string; isNew?: boolean } | null
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
useEffect(() => {
|
||||
if (!reveal) setCopied(false)
|
||||
}, [reveal])
|
||||
|
||||
if (!reveal) return null
|
||||
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(reveal.secret)
|
||||
setCopied(true)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<KeyRound className="size-5 text-amber-500" />
|
||||
{reveal.isNew ? "Webhook secret" : "New webhook secret"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
<strong>This is the only time the secret will be shown.</strong> Copy it now — store it
|
||||
with your verifying code so you can validate the X-Signature header on incoming
|
||||
deliveries.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-2 rounded-md border bg-muted/30 p-3">
|
||||
<code className="select-all break-all font-mono text-xs">{reveal.secret}</code>
|
||||
<Button size="sm" variant="outline" onClick={copy} data-action="webhook-secret-copy">
|
||||
{copied ? <CheckCircle2 className="size-3.5" /> : <Copy className="size-3.5" />}
|
||||
{copied ? "Copied" : "Copy"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button onClick={onClose} data-action="webhook-secret-close">
|
||||
Done
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function countBy<T>(arr: T[], key: (x: T) => string): Record<string, number> {
|
||||
return arr.reduce<Record<string, number>>((acc, x) => {
|
||||
const k = key(x)
|
||||
acc[k] = (acc[k] ?? 0) + 1
|
||||
return acc
|
||||
}, {})
|
||||
}
|
||||
Reference in New Issue
Block a user