|
@@ -0,0 +1,1387 @@
|
|
|
|
|
+import { Fragment, useEffect, useRef, useState } from 'react'
|
|
|
|
|
+import { useSearchParams } from 'react-router-dom'
|
|
|
|
|
+import { useQuery, useQueryClient } from '@tanstack/react-query'
|
|
|
|
|
+import {
|
|
|
|
|
+ Plus, RefreshCw, Trash2, Play, Copy, ShieldAlert, Globe, AlertTriangle,
|
|
|
|
|
+ CheckCircle2, XCircle, Code2,
|
|
|
|
|
+} from 'lucide-react'
|
|
|
|
|
+import { api } from '@/api/client'
|
|
|
|
|
+import { mountBase } from '@/api/base'
|
|
|
|
|
+import { useAuthStore } from '@/stores/authStore'
|
|
|
|
|
+import { useToastStore } from '@/stores/toastStore'
|
|
|
|
|
+import { ConfirmDialog } from '@/components/ConfirmDialog'
|
|
|
|
|
+import { JsonEditor } from '@/components/JsonEditor'
|
|
|
|
|
+import { SourceEditor } from '@/components/SourceEditor'
|
|
|
|
|
+import { ScopeRulesEditor, ScopeRulesView, usableRules } from '@/components/ScopeRules'
|
|
|
|
|
+import { Toggle, inputCls } from '@/components/form'
|
|
|
|
|
+import { ApiError } from '@/types'
|
|
|
|
|
+import type {
|
|
|
|
|
+ FunctionSummary, FunctionDetail, FunctionDescriptor, FunctionRun,
|
|
|
|
|
+ InvokeEnvelope, InvokeRequest, KeyScope, KeyScopeRule,
|
|
|
|
|
+} from '@/types'
|
|
|
|
|
+
|
|
|
|
|
+// ─── helpers ──────────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+function formatDate(epoch: number): string {
|
|
|
|
|
+ if (!epoch) return '-'
|
|
|
|
|
+ return new Date(epoch * 1000).toLocaleString(undefined, {
|
|
|
|
|
+ year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
|
|
|
|
|
+ })
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// An absent `method` list means EVERY method, which is the opposite of what an
|
|
|
|
|
+/// empty cell suggests - so it is spelled out.
|
|
|
|
|
+function methodsLabel(d: FunctionDescriptor): string {
|
|
|
|
|
+ const m = d.method ?? []
|
|
|
|
|
+ return m.length > 0 ? m.join(' ') : 'any method'
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function routeLabel(d: FunctionDescriptor): string {
|
|
|
|
|
+ if (d.type === 'http') return d.route || '(no route)'
|
|
|
|
|
+ if (d.type === 'cron') return `cron ${d.schedule ?? ''}`.trim()
|
|
|
|
|
+ return `${d.table ?? ''} ${d.event ?? ''}`.trim()
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// Where the public dispatcher serves this function. Built on mountBase() for
|
|
|
|
|
+/// the same reason every other URL is: behind a subpath proxy the prefix is
|
|
|
|
|
+/// stripped before the server sees the request, so only the browser knows it.
|
|
|
|
|
+function publicUrl(project: string, d: FunctionDescriptor): string {
|
|
|
|
|
+ return `${location.origin}${mountBase()}/fn/${encodeURIComponent(project)}${d.route ?? ''}`
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function detailField(details: unknown, key: string): string {
|
|
|
|
|
+ if (details && typeof details === 'object' && !Array.isArray(details)) {
|
|
|
|
|
+ const v = (details as Record<string, unknown>)[key]
|
|
|
|
|
+ if (typeof v === 'string') return v
|
|
|
|
|
+ }
|
|
|
|
|
+ return ''
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function errMessage(err: unknown): string {
|
|
|
|
|
+ return err instanceof ApiError || err instanceof Error ? err.message : String(err)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+const STARTER_SOURCE = `// The id lives in the source, never in the URL or the file name: it is the
|
|
|
|
|
+// registry row's identity, so the policy an admin grants travels with the code.
|
|
|
|
|
+export const on = {
|
|
|
|
|
+ id: 'hello',
|
|
|
|
|
+ type: 'http',
|
|
|
|
|
+ route: '/hello',
|
|
|
|
|
+ method: 'GET',
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+export default async function (ctx) {
|
|
|
|
|
+ ctx.log('called with', ctx.query)
|
|
|
|
|
+ return { status: 200, body: { ok: true, greeted: ctx.query.name || 'world' } }
|
|
|
|
|
+}
|
|
|
|
|
+`
|
|
|
|
|
+
|
|
|
|
|
+const INVOKE_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
|
|
|
|
|
+
|
|
|
|
|
+// ─── error panels ─────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+function ErrorPanel({
|
|
|
|
|
+ tone = 'red',
|
|
|
|
|
+ title,
|
|
|
|
|
+ children,
|
|
|
|
|
+}: {
|
|
|
|
|
+ tone?: 'red' | 'amber'
|
|
|
|
|
+ title: string
|
|
|
|
|
+ children?: React.ReactNode
|
|
|
|
|
+}) {
|
|
|
|
|
+ const tones = {
|
|
|
|
|
+ red: 'border-red-500/30 bg-red-500/5',
|
|
|
|
|
+ amber: 'border-amber-500/30 bg-amber-500/5',
|
|
|
|
|
+ }
|
|
|
|
|
+ const titles = { red: 'text-red-300', amber: 'text-amber-300' }
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className={`rounded-xl border px-4 py-3 ${tones[tone]}`} data-testid="fn-error-panel">
|
|
|
|
|
+ <p className={`text-sm font-medium ${titles[tone]}`}>{title}</p>
|
|
|
|
|
+ {children && <div className="mt-2 text-xs text-slate-300 flex flex-col gap-2">{children}</div>}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// Why a push or an invoke failed, in the terms the operator has to act in.
|
|
|
|
|
+///
|
|
|
|
|
+/// The slugs are not interchangeable: `no_runner` is a server configuration
|
|
|
|
|
+/// problem and nothing was stored, `compile_failed` is the author's own code,
|
|
|
|
|
+/// `id_mismatch` is a misunderstanding about where the id lives. One generic
|
|
|
|
|
+/// red toast for all three is what sends an operator to the wrong file.
|
|
|
|
|
+function PushErrorPanel({
|
|
|
|
|
+ err,
|
|
|
|
|
+ onOpenExisting,
|
|
|
|
|
+}: {
|
|
|
|
|
+ err: ApiError
|
|
|
|
|
+ onOpenExisting?: (id: string) => void
|
|
|
|
|
+}) {
|
|
|
|
|
+ if (err.code === 'no_runner') {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <ErrorPanel title="No function runner is available - nothing was stored.">
|
|
|
|
|
+ <p>
|
|
|
|
|
+ Installing the runner package does not switch functions on. The server has to be told
|
|
|
|
|
+ where the runners are: add a <code className="text-slate-200">functions.runners</code>{' '}
|
|
|
|
|
+ list to its <code className="text-slate-200">config.json</code> and restart it.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ <pre className="rounded-md bg-slate-950 border border-slate-700/60 px-3 py-2 overflow-x-auto text-[11px] text-slate-300">
|
|
|
|
|
+{`"functions": {
|
|
|
|
|
+ "runners": ["127.0.0.1:9100"],
|
|
|
|
|
+ "runs_kept": 50
|
|
|
|
|
+}`}
|
|
|
|
|
+ </pre>
|
|
|
|
|
+ <p>
|
|
|
|
|
+ If runners are already configured, then none of them is answering the health check.
|
|
|
|
|
+ Check that the runner service is up and that its token matches the server's
|
|
|
|
|
+ (<code className="text-slate-200">SVAPI_RUNNER_TOKEN</code>).
|
|
|
|
|
+ </p>
|
|
|
|
|
+ <p className="text-slate-400">
|
|
|
|
|
+ The server said: <span className="font-mono">{err.message}</span>
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (err.code === 'runner_unreachable') {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <ErrorPanel title="The runner could not be reached - nothing was stored.">
|
|
|
|
|
+ <p>
|
|
|
|
|
+ A runner is configured but did not give a usable answer. Code is never stored
|
|
|
|
|
+ unvalidated, so this push did not change anything.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ <p className="text-slate-400 font-mono">{err.message}</p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (err.code === 'compile_failed') {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <ErrorPanel title="The function did not compile - nothing was stored.">
|
|
|
|
|
+ <pre className="rounded-md bg-slate-950 border border-red-500/20 px-3 py-2 overflow-x-auto text-[11px] text-red-300 whitespace-pre-wrap">
|
|
|
|
|
+ {err.message}
|
|
|
|
|
+ </pre>
|
|
|
|
|
+ <p className="text-slate-400">
|
|
|
|
|
+ Compiled on a runner, by the same engine that would execute it.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (err.code === 'missing_function_id') {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <ErrorPanel title="The script declares no id.">
|
|
|
|
|
+ <p>
|
|
|
|
|
+ The exported <code className="text-slate-200">on</code> block needs an{' '}
|
|
|
|
|
+ <code className="text-slate-200">id</code>. The file path is never used as a fallback,
|
|
|
|
|
+ because the path is where you keep the file and the id is what the policy is attached to.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (err.code === 'id_mismatch') {
|
|
|
|
|
+ const declared = detailField(err.details, 'declared')
|
|
|
|
|
+ const url = detailField(err.details, 'url')
|
|
|
|
|
+ return (
|
|
|
|
|
+ <ErrorPanel title="The script's id does not match the function you are editing.">
|
|
|
|
|
+ <p>
|
|
|
|
|
+ This script declares{' '}
|
|
|
|
|
+ <span className="font-mono text-slate-200">{declared || '(unknown)'}</span>, but you are
|
|
|
|
|
+ pushing to <span className="font-mono text-slate-200">{url || '(unknown)'}</span>. The id
|
|
|
|
|
+ lives in the source, not in the URL, so this is not a rename: saving it here would move
|
|
|
|
|
+ your code onto another function's policy.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ <p>
|
|
|
|
|
+ Either put the id back, or create{' '}
|
|
|
|
|
+ <span className="font-mono text-slate-200">{declared || 'the new id'}</span> as a new
|
|
|
|
|
+ function.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (err.code === 'function_exists') {
|
|
|
|
|
+ const existing = detailField(err.details, 'function_id')
|
|
|
|
|
+ return (
|
|
|
|
|
+ <ErrorPanel tone="amber" title="That id is already registered.">
|
|
|
|
|
+ <p>
|
|
|
|
|
+ A function with this id exists already, so creating it would overwrite someone else's
|
|
|
|
|
+ code. Open it and push to it instead - that keeps its policy and its enabled state.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ {existing && onOpenExisting && (
|
|
|
|
|
+ <button
|
|
|
|
|
+ type="button"
|
|
|
|
|
+ onClick={() => onOpenExisting(existing)}
|
|
|
|
|
+ className="self-start inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition"
|
|
|
|
|
+ >
|
|
|
|
|
+ Open {existing}
|
|
|
|
|
+ </button>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (err.code === 'function_disabled' || err.code === 'function_invalid') {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <ErrorPanel tone="amber" title="This function cannot run right now.">
|
|
|
|
|
+ <p>{err.message}</p>
|
|
|
|
|
+ <p>
|
|
|
|
|
+ Enable it, or push a version that compiles. The registry row and its policy are kept
|
|
|
|
|
+ either way.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return <ErrorPanel title={`Request failed (${err.status}).`}><p>{err.message}</p></ErrorPanel>
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─── list ─────────────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+function StateBadges({ fn }: { fn: FunctionSummary }) {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex flex-wrap items-center gap-1">
|
|
|
|
|
+ <span
|
|
|
|
|
+ className={[
|
|
|
|
|
+ 'inline-block px-2 py-0.5 rounded text-xs font-medium border',
|
|
|
|
|
+ fn.enabled
|
|
|
|
|
+ ? 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30'
|
|
|
|
|
+ : 'bg-slate-600/30 text-slate-400 border-slate-600/30',
|
|
|
|
|
+ ].join(' ')}
|
|
|
|
|
+ >
|
|
|
|
|
+ {fn.enabled ? 'enabled' : 'disabled'}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ {!fn.valid && (
|
|
|
|
|
+ <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-red-500/15 text-red-300 border border-red-500/30">
|
|
|
|
|
+ invalid
|
|
|
|
|
+ </span>
|
|
|
|
|
+ )}
|
|
|
|
|
+ {fn.policy.rules.length === 0 && (
|
|
|
|
|
+ <span
|
|
|
|
|
+ className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-300 border border-amber-500/30"
|
|
|
|
|
+ title="Empty policy: the function runs but reaches no collection."
|
|
|
|
|
+ >
|
|
|
|
|
+ no data access
|
|
|
|
|
+ </span>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function FunctionsTable({
|
|
|
|
|
+ functions,
|
|
|
|
|
+ selected,
|
|
|
|
|
+ onSelect,
|
|
|
|
|
+}: {
|
|
|
|
|
+ functions: FunctionSummary[]
|
|
|
|
|
+ selected: string
|
|
|
|
|
+ onSelect: (id: string) => void
|
|
|
|
|
+}) {
|
|
|
|
|
+ if (functions.length === 0) {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center">
|
|
|
|
|
+ <p className="text-slate-400 text-sm">No functions in this project yet.</p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="rounded-xl border border-slate-700/40 overflow-x-auto">
|
|
|
|
|
+ <table className="w-full text-sm">
|
|
|
|
|
+ <thead>
|
|
|
|
|
+ <tr className="border-b border-slate-700/40 bg-slate-800/60">
|
|
|
|
|
+ {['Function', 'Trigger', 'Methods', 'State', 'Last error', 'Updated'].map((h) => (
|
|
|
|
|
+ <th
|
|
|
|
|
+ key={h}
|
|
|
|
|
+ className="text-left px-4 py-3 text-xs font-semibold text-slate-400 uppercase tracking-wider"
|
|
|
|
|
+ >
|
|
|
|
|
+ {h}
|
|
|
|
|
+ </th>
|
|
|
|
|
+ ))}
|
|
|
|
|
+ </tr>
|
|
|
|
|
+ </thead>
|
|
|
|
|
+ <tbody>
|
|
|
|
|
+ {functions.map((fn, idx) => (
|
|
|
|
|
+ <tr
|
|
|
|
|
+ key={fn.function_id}
|
|
|
|
|
+ onClick={() => onSelect(fn.function_id)}
|
|
|
|
|
+ className={[
|
|
|
|
|
+ 'border-b border-slate-700/20 cursor-pointer transition hover:bg-indigo-500/5',
|
|
|
|
|
+ fn.function_id === selected ? 'bg-indigo-500/10' : idx % 2 === 0 ? 'bg-slate-900/30' : 'bg-slate-800/20',
|
|
|
|
|
+ ].join(' ')}
|
|
|
|
|
+ data-testid="fn-row"
|
|
|
|
|
+ >
|
|
|
|
|
+ <td className="px-4 py-3">
|
|
|
|
|
+ <div className="font-mono text-slate-200 text-xs">{fn.function_id}</div>
|
|
|
|
|
+ {fn.path && <div className="font-mono text-slate-500 text-[11px]">{fn.path}</div>}
|
|
|
|
|
+ </td>
|
|
|
|
|
+ <td className="px-4 py-3 font-mono text-slate-300 text-xs">
|
|
|
|
|
+ <span className="text-slate-500">{fn.descriptor.type}</span> {routeLabel(fn.descriptor)}
|
|
|
|
|
+ </td>
|
|
|
|
|
+ <td className="px-4 py-3 font-mono text-slate-400 text-xs">{methodsLabel(fn.descriptor)}</td>
|
|
|
|
|
+ <td className="px-4 py-3"><StateBadges fn={fn} /></td>
|
|
|
|
|
+ <td className="px-4 py-3 text-xs text-red-400/80 max-w-xs truncate" title={fn.last_error}>
|
|
|
|
|
+ {fn.last_error || <span className="text-slate-600">-</span>}
|
|
|
|
|
+ </td>
|
|
|
|
|
+ <td className="px-4 py-3 text-slate-400 text-xs whitespace-nowrap">{formatDate(fn.updated_at)}</td>
|
|
|
|
|
+ </tr>
|
|
|
|
|
+ ))}
|
|
|
|
|
+ </tbody>
|
|
|
|
|
+ </table>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─── public URL ───────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+function PublicUrlPanel({ project, fn }: { project: string; fn: FunctionSummary }) {
|
|
|
|
|
+ const push = useToastStore((s) => s.push)
|
|
|
|
|
+ if (fn.descriptor.type !== 'http') return null
|
|
|
|
|
+ const url = publicUrl(project, fn.descriptor)
|
|
|
|
|
+
|
|
|
|
|
+ const copy = async () => {
|
|
|
|
|
+ try {
|
|
|
|
|
+ await navigator.clipboard.writeText(url)
|
|
|
|
|
+ push('Public URL copied to clipboard.', 'success')
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ push('Copy failed - clipboard unavailable.', 'error')
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="rounded-xl border border-amber-500/25 bg-amber-500/5 px-4 py-3 flex flex-col gap-2">
|
|
|
|
|
+ <div className="flex items-center gap-2">
|
|
|
|
|
+ <Globe size={14} className="text-amber-300" />
|
|
|
|
|
+ <span className="text-sm font-medium text-amber-300">Public, unauthenticated URL</span>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <div className="flex items-center gap-2">
|
|
|
|
|
+ <input
|
|
|
|
|
+ readOnly
|
|
|
|
|
+ value={url}
|
|
|
|
|
+ onClick={(e) => (e.target as HTMLInputElement).select()}
|
|
|
|
|
+ className="flex-1 rounded-md bg-slate-950 border border-slate-600 text-slate-200 font-mono text-xs px-3 py-2 focus:outline-none focus:border-indigo-500"
|
|
|
|
|
+ data-testid="fn-public-url"
|
|
|
|
|
+ />
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() => void copy()}
|
|
|
|
|
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium bg-slate-700 hover:bg-slate-600 text-slate-200 transition shrink-0"
|
|
|
|
|
+ aria-label="Copy public URL"
|
|
|
|
|
+ >
|
|
|
|
|
+ <Copy size={14} />
|
|
|
|
|
+ Copy
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <p className="text-xs text-slate-300">
|
|
|
|
|
+ Anyone who can reach this server can call this URL: <span className="font-mono">/fn/*</span>{' '}
|
|
|
|
|
+ carries no API key and no session. The only gates are this function being enabled and
|
|
|
|
|
+ valid, plus whatever the code itself checks. Accepts {methodsLabel(fn.descriptor)}.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─── source tab ───────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+interface SourceTabProps {
|
|
|
|
|
+ project: string
|
|
|
|
|
+ /// Null while creating: there is no id to push to until the script declares
|
|
|
|
|
+ /// one and the server has accepted it.
|
|
|
|
|
+ existing: FunctionDetail | null
|
|
|
|
|
+ onSaved: (id: string) => void
|
|
|
|
|
+ onOpenExisting: (id: string) => void
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function SourceTab({ project, existing, onSaved, onOpenExisting }: SourceTabProps) {
|
|
|
|
|
+ const push = useToastStore((s) => s.push)
|
|
|
|
|
+ const [source, setSource] = useState(existing?.source ?? STARTER_SOURCE)
|
|
|
|
|
+ const [path, setPath] = useState(existing?.path ?? '')
|
|
|
|
|
+ const [saving, setSaving] = useState(false)
|
|
|
|
|
+ const [pushError, setPushError] = useState<ApiError | null>(null)
|
|
|
|
|
+
|
|
|
|
|
+ // A different function (or a fresh draft) replaces the buffer outright: the
|
|
|
|
|
+ // source belongs to the row being left, exactly as the document editor drops
|
|
|
|
|
+ // a document when its collection changes.
|
|
|
|
|
+ const bufferKey = existing ? `${existing.function_id}:${existing.content_hash}` : 'new'
|
|
|
|
|
+ useEffect(() => {
|
|
|
|
|
+ setSource(existing?.source ?? STARTER_SOURCE)
|
|
|
|
|
+ setPath(existing?.path ?? '')
|
|
|
|
|
+ setPushError(null)
|
|
|
|
|
+ // eslint-disable-next-line react-hooks/exhaustive-deps
|
|
|
|
|
+ }, [bufferKey])
|
|
|
|
|
+
|
|
|
|
|
+ const dirty = source !== (existing?.source ?? STARTER_SOURCE) || path !== (existing?.path ?? '')
|
|
|
|
|
+
|
|
|
|
|
+ const save = async () => {
|
|
|
|
|
+ setSaving(true)
|
|
|
|
|
+ setPushError(null)
|
|
|
|
|
+ try {
|
|
|
|
|
+ const body = { source, path: path.trim() }
|
|
|
|
|
+ if (existing) {
|
|
|
|
|
+ await api.putFunction(project, existing.function_id, body)
|
|
|
|
|
+ push(`Pushed ${existing.function_id}. Its policy and enabled state are unchanged.`, 'success')
|
|
|
|
|
+ onSaved(existing.function_id)
|
|
|
|
|
+ } else {
|
|
|
|
|
+ const created = await api.createFunction(project, body)
|
|
|
|
|
+ push(`Registered ${created.function_id}.`, 'success')
|
|
|
|
|
+ onSaved(created.function_id)
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ if (err instanceof ApiError) setPushError(err)
|
|
|
|
|
+ else push(`Push failed: ${errMessage(err)}`, 'error')
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ setSaving(false)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex flex-col gap-4">
|
|
|
|
|
+ <div className="flex flex-wrap items-end gap-3">
|
|
|
|
|
+ <div className="flex-1 min-w-60">
|
|
|
|
|
+ <label className="block text-xs font-medium text-slate-400 mb-1">
|
|
|
|
|
+ Path <span className="text-slate-500">(where you keep the file; carries no meaning)</span>
|
|
|
|
|
+ </label>
|
|
|
|
|
+ <input
|
|
|
|
|
+ type="text"
|
|
|
|
|
+ value={path}
|
|
|
|
|
+ onChange={(e) => setPath(e.target.value)}
|
|
|
|
|
+ placeholder="kb-search.js"
|
|
|
|
|
+ className={inputCls}
|
|
|
|
|
+ data-testid="fn-path"
|
|
|
|
|
+ />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() => void save()}
|
|
|
|
|
+ disabled={saving || (!!existing && !dirty)}
|
|
|
|
|
+ className="inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition disabled:opacity-50 disabled:cursor-not-allowed"
|
|
|
|
|
+ data-testid="fn-save-source"
|
|
|
|
|
+ >
|
|
|
|
|
+ {saving ? 'Compiling...' : existing ? 'Push code' : 'Register function'}
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ <SourceEditor value={source} onChange={setSource} height={440} />
|
|
|
|
|
+
|
|
|
|
|
+ {pushError && <PushErrorPanel err={pushError} onOpenExisting={onOpenExisting} />}
|
|
|
|
|
+
|
|
|
|
|
+ <p className="text-xs text-slate-500">
|
|
|
|
|
+ Every push is compiled on a runner before it is stored, by the engine that will execute it.
|
|
|
|
|
+ A push carries code only: the policy below and the enabled state are server state, so
|
|
|
|
|
+ pushing never changes them - and never re-enables a function someone turned off.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─── policy tab ───────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+function PolicyTab({
|
|
|
|
|
+ project,
|
|
|
|
|
+ fn,
|
|
|
|
|
+ admin,
|
|
|
|
|
+ onSaved,
|
|
|
|
|
+}: {
|
|
|
|
|
+ project: string
|
|
|
|
|
+ fn: FunctionSummary
|
|
|
|
|
+ admin: boolean
|
|
|
|
|
+ onSaved: () => void
|
|
|
|
|
+}) {
|
|
|
|
|
+ const pushToast = useToastStore((s) => s.push)
|
|
|
|
|
+ const [rules, setRules] = useState<KeyScopeRule[]>(fn.policy.rules)
|
|
|
|
|
+ const [origins, setOrigins] = useState(fn.policy.origins.join(', '))
|
|
|
|
|
+ const [rateLimit, setRateLimit] = useState(fn.policy.rate_limit_per_min)
|
|
|
|
|
+ const [expiresAt, setExpiresAt] = useState(fn.policy.expires_at)
|
|
|
|
|
+ const [saving, setSaving] = useState(false)
|
|
|
|
|
+ const [err, setErr] = useState<ApiError | null>(null)
|
|
|
|
|
+
|
|
|
|
|
+ useEffect(() => {
|
|
|
|
|
+ setRules(fn.policy.rules)
|
|
|
|
|
+ setOrigins(fn.policy.origins.join(', '))
|
|
|
|
|
+ setRateLimit(fn.policy.rate_limit_per_min)
|
|
|
|
|
+ setExpiresAt(fn.policy.expires_at)
|
|
|
|
|
+ setErr(null)
|
|
|
|
|
+ // eslint-disable-next-line react-hooks/exhaustive-deps
|
|
|
|
|
+ }, [fn.function_id, fn.updated_at])
|
|
|
|
|
+
|
|
|
|
|
+ // A caller who may not edit still needs to SEE the policy: it is the answer
|
|
|
|
|
+ // to "why does my function get a 403?", and that question is asked by the
|
|
|
|
|
+ // person who wrote the code, not by the admin who granted the access.
|
|
|
|
|
+ if (!admin) {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex flex-col gap-4">
|
|
|
|
|
+ <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-4 py-3 flex items-start gap-2">
|
|
|
|
|
+ <ShieldAlert size={15} className="text-slate-400 mt-0.5 shrink-0" />
|
|
|
|
|
+ <p className="text-xs text-slate-400">
|
|
|
|
|
+ Read-only: only an admin key can change a function's policy. Developers push code,
|
|
|
|
|
+ admins grant what it may touch - the same split API keys have. If this function gets a
|
|
|
|
|
+ 403 from <span className="font-mono">ctx.collections(...)</span>, this list is why.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <ScopeRulesView rules={fn.policy.rules} />
|
|
|
|
|
+ <PolicyLimitsView policy={fn.policy} />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const save = async () => {
|
|
|
|
|
+ setSaving(true)
|
|
|
|
|
+ setErr(null)
|
|
|
|
|
+ try {
|
|
|
|
|
+ const policy: KeyScope = {
|
|
|
|
|
+ // require_human_token is dropped: it is an HTTP-header check and a
|
|
|
|
|
+ // function never presents one, so storing it would be decoration.
|
|
|
|
|
+ rules: usableRules(rules, false),
|
|
|
|
|
+ origins: origins.split(',').map((o) => o.trim()).filter((o) => o.length > 0),
|
|
|
|
|
+ rate_limit_per_min: rateLimit,
|
|
|
|
|
+ expires_at: expiresAt,
|
|
|
|
|
+ }
|
|
|
|
|
+ await api.setFunctionPolicy(project, fn.function_id, policy)
|
|
|
|
|
+ pushToast(
|
|
|
|
|
+ policy.rules.length === 0
|
|
|
|
|
+ ? `Policy replaced: ${fn.function_id} now reaches no collection.`
|
|
|
|
|
+ : `Policy replaced for ${fn.function_id}.`,
|
|
|
|
|
+ 'success',
|
|
|
|
|
+ )
|
|
|
|
|
+ onSaved()
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ if (e instanceof ApiError) setErr(e)
|
|
|
|
|
+ else pushToast(`Could not save the policy: ${errMessage(e)}`, 'error')
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ setSaving(false)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex flex-col gap-4">
|
|
|
|
|
+ <p className="text-xs text-slate-400">
|
|
|
|
|
+ Replaces the whole policy. Rules that name no collection or no operation are dropped - the
|
|
|
|
|
+ server rejects them. An <span className="text-amber-300">empty rule set is legal</span> and
|
|
|
|
|
+ means the function reaches nothing: it still runs, logs and calls out, but touches no
|
|
|
|
|
+ collection.
|
|
|
|
|
+ </p>
|
|
|
|
|
+
|
|
|
|
|
+ <ScopeRulesEditor
|
|
|
|
|
+ rules={rules}
|
|
|
|
|
+ onChange={setRules}
|
|
|
|
|
+ allowEmpty
|
|
|
|
|
+ showHumanToken={false}
|
|
|
|
|
+ accent="indigo"
|
|
|
|
|
+ label="Collection rules"
|
|
|
|
|
+ emptyHint="Saving with no rules grants no data access at all. That is a valid policy, not an unfinished one."
|
|
|
|
|
+ />
|
|
|
|
|
+
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <label className="block text-xs font-medium text-slate-400 mb-1">
|
|
|
|
|
+ Allowed origins <span className="text-slate-500">(comma-separated; empty = any)</span>
|
|
|
|
|
+ </label>
|
|
|
|
|
+ <input
|
|
|
|
|
+ type="text"
|
|
|
|
|
+ value={origins}
|
|
|
|
|
+ onChange={(e) => setOrigins(e.target.value)}
|
|
|
|
|
+ placeholder="https://app.example.com"
|
|
|
|
|
+ className={inputCls}
|
|
|
|
|
+ />
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ <div className="flex flex-wrap gap-3">
|
|
|
|
|
+ <div className="flex-1 min-w-40">
|
|
|
|
|
+ <label className="block text-xs font-medium text-slate-400 mb-1">
|
|
|
|
|
+ Rate limit / min <span className="text-slate-500">(0 = unlimited)</span>
|
|
|
|
|
+ </label>
|
|
|
|
|
+ <input
|
|
|
|
|
+ type="number"
|
|
|
|
|
+ min={0}
|
|
|
|
|
+ step={1}
|
|
|
|
|
+ value={rateLimit}
|
|
|
|
|
+ onChange={(e) => setRateLimit(Math.max(0, Math.floor(Number(e.target.value) || 0)))}
|
|
|
|
|
+ className={inputCls}
|
|
|
|
|
+ />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <div className="flex-1 min-w-40">
|
|
|
|
|
+ <label className="block text-xs font-medium text-slate-400 mb-1">
|
|
|
|
|
+ Expires at <span className="text-slate-500">(epoch seconds; 0 = never)</span>
|
|
|
|
|
+ </label>
|
|
|
|
|
+ <input
|
|
|
|
|
+ type="number"
|
|
|
|
|
+ min={0}
|
|
|
|
|
+ step={1}
|
|
|
|
|
+ value={expiresAt}
|
|
|
|
|
+ onChange={(e) => setExpiresAt(Math.max(0, Math.floor(Number(e.target.value) || 0)))}
|
|
|
|
|
+ className={inputCls}
|
|
|
|
|
+ />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ {err && <PushErrorPanel err={err} />}
|
|
|
|
|
+
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() => void save()}
|
|
|
|
|
+ disabled={saving}
|
|
|
|
|
+ className="self-start inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition disabled:opacity-50"
|
|
|
|
|
+ data-testid="fn-save-policy"
|
|
|
|
|
+ >
|
|
|
|
|
+ {saving ? 'Saving...' : 'Replace policy'}
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function PolicyLimitsView({ policy }: { policy: KeyScope }) {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <dl className="grid grid-cols-[auto,1fr] gap-x-4 gap-y-1 text-xs">
|
|
|
|
|
+ <dt className="text-slate-500">Origins</dt>
|
|
|
|
|
+ <dd className="text-slate-300 font-mono">
|
|
|
|
|
+ {policy.origins.length > 0 ? policy.origins.join(', ') : 'any'}
|
|
|
|
|
+ </dd>
|
|
|
|
|
+ <dt className="text-slate-500">Rate limit</dt>
|
|
|
|
|
+ <dd className="text-slate-300 font-mono">
|
|
|
|
|
+ {policy.rate_limit_per_min > 0 ? `${policy.rate_limit_per_min}/min` : 'unlimited'}
|
|
|
|
|
+ </dd>
|
|
|
|
|
+ <dt className="text-slate-500">Expires</dt>
|
|
|
|
|
+ <dd className="text-slate-300 font-mono">
|
|
|
|
|
+ {policy.expires_at > 0 ? formatDate(policy.expires_at) : 'never'}
|
|
|
|
|
+ </dd>
|
|
|
|
|
+ </dl>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─── invoke tab ───────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+/// A JSON object field small enough to stay a textarea. Invalid JSON is the
|
|
|
|
|
+/// caller's own typo, so it is reported here and blocks the run rather than
|
|
|
|
|
+/// being sent as a string.
|
|
|
|
|
+function JsonObjectField({
|
|
|
|
|
+ label,
|
|
|
|
|
+ hint,
|
|
|
|
|
+ value,
|
|
|
|
|
+ onChange,
|
|
|
|
|
+}: {
|
|
|
|
|
+ label: string
|
|
|
|
|
+ hint: string
|
|
|
|
|
+ value: string
|
|
|
|
|
+ onChange: (v: string) => void
|
|
|
|
|
+}) {
|
|
|
|
|
+ const invalid = value.trim() !== '' && !parsesToObject(value)
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex-1 min-w-52">
|
|
|
|
|
+ <label className="block text-xs font-medium text-slate-400 mb-1">
|
|
|
|
|
+ {label} <span className="text-slate-500">{hint}</span>
|
|
|
|
|
+ </label>
|
|
|
|
|
+ <textarea
|
|
|
|
|
+ value={value}
|
|
|
|
|
+ onChange={(e) => onChange(e.target.value)}
|
|
|
|
|
+ rows={3}
|
|
|
|
|
+ spellCheck={false}
|
|
|
|
|
+ className={`${inputCls} font-mono text-xs`}
|
|
|
|
|
+ placeholder="{}"
|
|
|
|
|
+ />
|
|
|
|
|
+ {invalid && <p className="text-xs text-red-400 mt-1">Not a JSON object.</p>}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function parsesToObject(text: string): boolean {
|
|
|
|
|
+ try {
|
|
|
|
|
+ const v: unknown = JSON.parse(text)
|
|
|
|
|
+ return !!v && typeof v === 'object' && !Array.isArray(v)
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ return false
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function parseObjectOrUndefined(text: string): Record<string, unknown> | undefined {
|
|
|
|
|
+ if (text.trim() === '') return undefined
|
|
|
|
|
+ try {
|
|
|
|
|
+ return JSON.parse(text) as Record<string, unknown>
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ return undefined
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function InvokeTab({ project, fn }: { project: string; fn: FunctionSummary }) {
|
|
|
|
|
+ const push = useToastStore((s) => s.push)
|
|
|
|
|
+ const queryClient = useQueryClient()
|
|
|
|
|
+ const [method, setMethod] = useState((fn.descriptor.method ?? [])[0] ?? 'POST')
|
|
|
|
|
+ const [path, setPath] = useState(fn.descriptor.route ?? '')
|
|
|
|
|
+ const [params, setParams] = useState('')
|
|
|
|
|
+ const [query, setQuery] = useState('')
|
|
|
|
|
+ const [headers, setHeaders] = useState('')
|
|
|
|
|
+ const [body, setBody] = useState('')
|
|
|
|
|
+ const [running, setRunning] = useState(false)
|
|
|
|
|
+ const [envelope, setEnvelope] = useState<InvokeEnvelope | null>(null)
|
|
|
|
|
+ const [err, setErr] = useState<ApiError | null>(null)
|
|
|
|
|
+
|
|
|
|
|
+ useEffect(() => {
|
|
|
|
|
+ setMethod((fn.descriptor.method ?? [])[0] ?? 'POST')
|
|
|
|
|
+ setPath(fn.descriptor.route ?? '')
|
|
|
|
|
+ setEnvelope(null)
|
|
|
|
|
+ setErr(null)
|
|
|
|
|
+ // eslint-disable-next-line react-hooks/exhaustive-deps
|
|
|
|
|
+ }, [fn.function_id])
|
|
|
|
|
+
|
|
|
|
|
+ const bodyInvalid = body.trim() !== '' && !parsesJson(body)
|
|
|
|
|
+ const blocked =
|
|
|
|
|
+ bodyInvalid ||
|
|
|
|
|
+ [params, query, headers].some((t) => t.trim() !== '' && !parsesToObject(t))
|
|
|
|
|
+
|
|
|
|
|
+ const run = async () => {
|
|
|
|
|
+ setRunning(true)
|
|
|
|
|
+ setErr(null)
|
|
|
|
|
+ try {
|
|
|
|
|
+ const req: InvokeRequest = { method, path }
|
|
|
|
|
+ const p = parseObjectOrUndefined(params)
|
|
|
|
|
+ const q = parseObjectOrUndefined(query)
|
|
|
|
|
+ const h = parseObjectOrUndefined(headers)
|
|
|
|
|
+ if (p) req.params = p
|
|
|
|
|
+ if (q) req.query = q
|
|
|
|
|
+ if (h) req.headers = h
|
|
|
|
|
+ if (body.trim() !== '') req.body = JSON.parse(body) as unknown
|
|
|
|
|
+ const env = await api.invokeFunction(project, fn.function_id, req)
|
|
|
|
|
+ setEnvelope(env)
|
|
|
|
|
+ // The run was recorded, so the log the Runs tab shows is now stale.
|
|
|
|
|
+ void queryClient.invalidateQueries({ queryKey: ['function-logs', project, fn.function_id] })
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ if (e instanceof ApiError) setErr(e)
|
|
|
|
|
+ else push(`Invoke failed: ${errMessage(e)}`, 'error')
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ setRunning(false)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex flex-col gap-4">
|
|
|
|
|
+ <p className="text-xs text-slate-400">
|
|
|
|
|
+ Every field is optional. Left as they are, the function runs on its declared route. The
|
|
|
|
|
+ invoke is recorded in the run log either way.
|
|
|
|
|
+ </p>
|
|
|
|
|
+
|
|
|
|
|
+ <div className="flex flex-wrap items-end gap-3">
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <label className="block text-xs font-medium text-slate-400 mb-1">Method</label>
|
|
|
|
|
+ <select
|
|
|
|
|
+ value={method}
|
|
|
|
|
+ onChange={(e) => setMethod(e.target.value)}
|
|
|
|
|
+ className="rounded-md bg-slate-800 border border-slate-600 text-slate-200 text-sm px-3 py-2 focus:outline-none focus:border-indigo-500"
|
|
|
|
|
+ >
|
|
|
|
|
+ {INVOKE_METHODS.map((m) => (
|
|
|
|
|
+ <option key={m} value={m}>{m}</option>
|
|
|
|
|
+ ))}
|
|
|
|
|
+ </select>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <div className="flex-1 min-w-60">
|
|
|
|
|
+ <label className="block text-xs font-medium text-slate-400 mb-1">
|
|
|
|
|
+ Path <span className="text-slate-500">(defaults to the declared route)</span>
|
|
|
|
|
+ </label>
|
|
|
|
|
+ <input
|
|
|
|
|
+ type="text"
|
|
|
|
|
+ value={path}
|
|
|
|
|
+ onChange={(e) => setPath(e.target.value)}
|
|
|
|
|
+ placeholder={fn.descriptor.route ?? '/'}
|
|
|
|
|
+ className={`${inputCls} font-mono text-xs`}
|
|
|
|
|
+ />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ <div className="flex flex-wrap gap-3">
|
|
|
|
|
+ <JsonObjectField label="Params" hint="(the route's :name captures)" value={params} onChange={setParams} />
|
|
|
|
|
+ <JsonObjectField label="Query" hint="(?a=b)" value={query} onChange={setQuery} />
|
|
|
|
|
+ <JsonObjectField label="Headers" hint="(cookies are never forwarded)" value={headers} onChange={setHeaders} />
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <label className="block text-xs font-medium text-slate-400 mb-1">
|
|
|
|
|
+ Body <span className="text-slate-500">(JSON; empty sends null)</span>
|
|
|
|
|
+ </label>
|
|
|
|
|
+ <JsonEditor value={body} onChange={setBody} height={150} />
|
|
|
|
|
+ {bodyInvalid && <p className="text-xs text-red-400 mt-1">Invalid JSON - fix before running.</p>}
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() => void run()}
|
|
|
|
|
+ disabled={running || blocked}
|
|
|
|
|
+ className="self-start inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition disabled:opacity-50"
|
|
|
|
|
+ data-testid="fn-invoke"
|
|
|
|
|
+ >
|
|
|
|
|
+ <Play size={15} />
|
|
|
|
|
+ {running ? 'Running...' : 'Run once'}
|
|
|
|
|
+ </button>
|
|
|
|
|
+
|
|
|
|
|
+ {err && <PushErrorPanel err={err} />}
|
|
|
|
|
+ {envelope && <EnvelopeView env={envelope} />}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function parsesJson(text: string): boolean {
|
|
|
|
|
+ try {
|
|
|
|
|
+ JSON.parse(text)
|
|
|
|
|
+ return true
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ return false
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// The whole envelope, and the distinction it exists for: the invoke succeeded
|
|
|
|
|
+/// whenever a run was performed, so a function answering 500 is reported here
|
|
|
|
|
+/// as a performed run that returned 500 - not as a failed request.
|
|
|
|
|
+function EnvelopeView({ env }: { env: InvokeEnvelope }) {
|
|
|
|
|
+ const Icon = env.ok ? CheckCircle2 : XCircle
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 flex flex-col" data-testid="fn-envelope">
|
|
|
|
|
+ <div className="flex flex-wrap items-center gap-3 px-4 py-3 border-b border-slate-700/40">
|
|
|
|
|
+ <span className="inline-flex items-center gap-1.5 text-sm font-medium text-slate-200">
|
|
|
|
|
+ <Icon size={15} className={env.ok ? 'text-emerald-400' : 'text-red-400'} />
|
|
|
|
|
+ Run performed
|
|
|
|
|
+ </span>
|
|
|
|
|
+ <span
|
|
|
|
|
+ className={[
|
|
|
|
|
+ 'inline-block px-2 py-0.5 rounded text-xs font-medium border',
|
|
|
|
|
+ env.ok
|
|
|
|
|
+ ? 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30'
|
|
|
|
|
+ : 'bg-red-500/15 text-red-300 border-red-500/30',
|
|
|
|
|
+ ].join(' ')}
|
|
|
|
|
+ >
|
|
|
|
|
+ ok: {String(env.ok)}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ <span className="inline-block px-2 py-0.5 rounded text-xs font-mono bg-slate-700/50 text-slate-300 border border-slate-600/40">
|
|
|
|
|
+ status {env.status}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ <span className="text-xs text-slate-400 font-mono">{env.duration_ms} ms</span>
|
|
|
|
|
+ {env.timed_out && (
|
|
|
|
|
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-300 border border-amber-500/30">
|
|
|
|
|
+ <AlertTriangle size={11} /> timed out
|
|
|
|
|
+ </span>
|
|
|
|
|
+ )}
|
|
|
|
|
+ {env.out_of_memory && (
|
|
|
|
|
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-300 border border-amber-500/30">
|
|
|
|
|
+ <AlertTriangle size={11} /> out of memory
|
|
|
|
|
+ </span>
|
|
|
|
|
+ )}
|
|
|
|
|
+ <span className="text-xs text-slate-500 font-mono ml-auto">run {env.run_id.slice(0, 12)}...</span>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ <div className="px-4 py-3 flex flex-col gap-3">
|
|
|
|
|
+ <p className="text-xs text-slate-500">
|
|
|
|
|
+ The invoke itself returned HTTP 200 because the run happened. The status above is the
|
|
|
|
|
+ function's own answer, so {env.status} here is a function result, not a failed request.
|
|
|
|
|
+ </p>
|
|
|
|
|
+
|
|
|
|
|
+ {env.error && (
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <p className="text-xs font-medium text-slate-400 mb-1">Error</p>
|
|
|
|
|
+ <pre className="rounded-md bg-slate-950 border border-red-500/20 px-3 py-2 overflow-x-auto text-[11px] text-red-300 whitespace-pre-wrap">
|
|
|
|
|
+ {env.error}
|
|
|
|
|
+ </pre>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <p className="text-xs font-medium text-slate-400 mb-1">Body</p>
|
|
|
|
|
+ <pre className="rounded-md bg-slate-950 border border-slate-700/60 px-3 py-2 overflow-x-auto max-h-72 text-[11px] text-slate-300">
|
|
|
|
|
+ {JSON.stringify(env.body ?? null, null, 2)}
|
|
|
|
|
+ </pre>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ {Object.keys(env.headers ?? {}).length > 0 && (
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <p className="text-xs font-medium text-slate-400 mb-1">Response headers</p>
|
|
|
|
|
+ <pre className="rounded-md bg-slate-950 border border-slate-700/60 px-3 py-2 overflow-x-auto text-[11px] text-slate-300">
|
|
|
|
|
+ {JSON.stringify(env.headers, null, 2)}
|
|
|
|
|
+ </pre>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ <ConsoleView lines={env.console} />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+function ConsoleView({ lines }: { lines: string[] }) {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <p className="text-xs font-medium text-slate-400 mb-1">Console</p>
|
|
|
|
|
+ {lines.length === 0 ? (
|
|
|
|
|
+ <p className="text-xs text-slate-500">The function logged nothing.</p>
|
|
|
|
|
+ ) : (
|
|
|
|
|
+ <pre className="rounded-md bg-slate-950 border border-slate-700/60 px-3 py-2 overflow-x-auto max-h-60 text-[11px] text-slate-300">
|
|
|
|
|
+ {lines.join('\n')}
|
|
|
|
|
+ </pre>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─── runs tab ─────────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+function RunsTab({ project, fn }: { project: string; fn: FunctionSummary }) {
|
|
|
|
|
+ const [limit, setLimit] = useState(50)
|
|
|
|
|
+ const [open, setOpen] = useState('')
|
|
|
|
|
+
|
|
|
|
|
+ const { data, isLoading, isError, error, refetch, isFetching } = useQuery({
|
|
|
|
|
+ queryKey: ['function-logs', project, fn.function_id, limit],
|
|
|
|
|
+ queryFn: () => api.functionLogs(project, fn.function_id, limit),
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ const runs: FunctionRun[] = data?.runs ?? []
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex flex-col gap-4">
|
|
|
|
|
+ <div className="flex flex-wrap items-end gap-3">
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <label className="block text-xs font-medium text-slate-400 mb-1">Limit</label>
|
|
|
|
|
+ <input
|
|
|
|
|
+ type="number"
|
|
|
|
|
+ min={1}
|
|
|
|
|
+ value={limit}
|
|
|
|
|
+ onChange={(e) => setLimit(Math.max(1, Math.floor(Number(e.target.value) || 1)))}
|
|
|
|
|
+ className={`${inputCls} w-24`}
|
|
|
|
|
+ />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() => void refetch()}
|
|
|
|
|
+ disabled={isFetching}
|
|
|
|
|
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium text-slate-300 bg-slate-700/50 hover:bg-slate-700 transition disabled:opacity-50"
|
|
|
|
|
+ >
|
|
|
|
|
+ <RefreshCw size={15} className={isFetching ? 'animate-spin' : ''} />
|
|
|
|
|
+ Refresh
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ {/* The log is trimmed on every write, so "fewer rows than asked for" is
|
|
|
|
|
+ the normal state, not a loading glitch, and an old run_id is gone for
|
|
|
|
|
+ good rather than momentarily missing. */}
|
|
|
|
|
+ <p className="text-xs text-slate-500">
|
|
|
|
|
+ Newest first. Only the newest runs per function are kept (50 by default, set by the
|
|
|
|
|
+ server's <span className="font-mono">functions.runs_kept</span>), and the log is trimmed on
|
|
|
|
|
+ every write - so asking for more than that returns what is left, and a run_id from an older
|
|
|
|
|
+ run stops resolving altogether.
|
|
|
|
|
+ </p>
|
|
|
|
|
+
|
|
|
|
|
+ {isError && (
|
|
|
|
|
+ <ErrorPanel title="Could not load the run log.">
|
|
|
|
|
+ <p>{errMessage(error)}</p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {isLoading && (
|
|
|
|
|
+ <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-8 text-center animate-pulse">
|
|
|
|
|
+ <p className="text-slate-400 text-sm">Loading runs...</p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {!isLoading && !isError && runs.length === 0 && (
|
|
|
|
|
+ <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-8 text-center">
|
|
|
|
|
+ <p className="text-slate-400 text-sm">No runs kept for this function.</p>
|
|
|
|
|
+ <p className="text-slate-500 text-xs mt-1">
|
|
|
|
|
+ Either it has never run, or every run it had has been trimmed away.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {runs.length > 0 && (
|
|
|
|
|
+ <div className="rounded-xl border border-slate-700/40 overflow-x-auto">
|
|
|
|
|
+ <table className="w-full text-sm">
|
|
|
|
|
+ <thead>
|
|
|
|
|
+ <tr className="border-b border-slate-700/40 bg-slate-800/60">
|
|
|
|
|
+ {['Started', 'Trigger', 'Result', 'Status', 'Duration', 'Error'].map((h) => (
|
|
|
|
|
+ <th
|
|
|
|
|
+ key={h}
|
|
|
|
|
+ className="text-left px-4 py-3 text-xs font-semibold text-slate-400 uppercase tracking-wider"
|
|
|
|
|
+ >
|
|
|
|
|
+ {h}
|
|
|
|
|
+ </th>
|
|
|
|
|
+ ))}
|
|
|
|
|
+ </tr>
|
|
|
|
|
+ </thead>
|
|
|
|
|
+ <tbody>
|
|
|
|
|
+ {runs.map((r, idx) => (
|
|
|
|
|
+ <Fragment key={r.run_id}>
|
|
|
|
|
+ <tr
|
|
|
|
|
+ onClick={() => setOpen(open === r.run_id ? '' : r.run_id)}
|
|
|
|
|
+ className={[
|
|
|
|
|
+ 'border-b border-slate-700/20 cursor-pointer transition hover:bg-indigo-500/5',
|
|
|
|
|
+ idx % 2 === 0 ? 'bg-slate-900/30' : 'bg-slate-800/20',
|
|
|
|
|
+ ].join(' ')}
|
|
|
|
|
+ data-testid="fn-run-row"
|
|
|
|
|
+ >
|
|
|
|
|
+ <td className="px-4 py-2.5 text-xs text-slate-300 whitespace-nowrap">
|
|
|
|
|
+ {formatDate(r.started_at)}
|
|
|
|
|
+ </td>
|
|
|
|
|
+ <td className="px-4 py-2.5 text-xs font-mono text-slate-400">{r.trigger}</td>
|
|
|
|
|
+ <td className="px-4 py-2.5">
|
|
|
|
|
+ <span
|
|
|
|
|
+ className={[
|
|
|
|
|
+ 'inline-block px-2 py-0.5 rounded text-xs font-medium border',
|
|
|
|
|
+ r.ok
|
|
|
|
|
+ ? 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30'
|
|
|
|
|
+ : 'bg-red-500/15 text-red-300 border-red-500/30',
|
|
|
|
|
+ ].join(' ')}
|
|
|
|
|
+ >
|
|
|
|
|
+ {r.ok ? 'ok' : 'failed'}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ </td>
|
|
|
|
|
+ <td className="px-4 py-2.5 text-xs font-mono text-slate-300">{r.status}</td>
|
|
|
|
|
+ <td className="px-4 py-2.5 text-xs font-mono text-slate-400">{r.duration_ms} ms</td>
|
|
|
|
|
+ <td className="px-4 py-2.5 text-xs text-red-400/80 max-w-xs truncate" title={r.error}>
|
|
|
|
|
+ {r.error || <span className="text-slate-600">-</span>}
|
|
|
|
|
+ </td>
|
|
|
|
|
+ </tr>
|
|
|
|
|
+ {open === r.run_id && (
|
|
|
|
|
+ <tr className="border-b border-slate-700/20 bg-slate-950/40">
|
|
|
|
|
+ <td colSpan={6} className="px-4 py-3">
|
|
|
|
|
+ <p className="text-[11px] text-slate-500 font-mono mb-2 break-all">run {r.run_id}</p>
|
|
|
|
|
+ <ConsoleView lines={r.console} />
|
|
|
|
|
+ </td>
|
|
|
|
|
+ </tr>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </Fragment>
|
|
|
|
|
+ ))}
|
|
|
|
|
+ </tbody>
|
|
|
|
|
+ </table>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─── detail ───────────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+type TabId = 'source' | 'policy' | 'invoke' | 'runs'
|
|
|
|
|
+
|
|
|
|
|
+function FunctionDetailPanel({
|
|
|
|
|
+ project,
|
|
|
|
|
+ summary,
|
|
|
|
|
+ detail,
|
|
|
|
|
+ detailLoading,
|
|
|
|
|
+ admin,
|
|
|
|
|
+ tab,
|
|
|
|
|
+ onTab,
|
|
|
|
|
+ onRefresh,
|
|
|
|
|
+ onDelete,
|
|
|
|
|
+ onOpenExisting,
|
|
|
|
|
+ onSaved,
|
|
|
|
|
+}: {
|
|
|
|
|
+ project: string
|
|
|
|
|
+ summary: FunctionSummary
|
|
|
|
|
+ detail: FunctionDetail | null
|
|
|
|
|
+ detailLoading: boolean
|
|
|
|
|
+ admin: boolean
|
|
|
|
|
+ tab: TabId
|
|
|
|
|
+ onTab: (t: TabId) => void
|
|
|
|
|
+ onRefresh: () => void
|
|
|
|
|
+ onDelete: () => void
|
|
|
|
|
+ onOpenExisting: (id: string) => void
|
|
|
|
|
+ onSaved: (id: string) => void
|
|
|
|
|
+}) {
|
|
|
|
|
+ const push = useToastStore((s) => s.push)
|
|
|
|
|
+ const [togglingEnabled, setTogglingEnabled] = useState(false)
|
|
|
|
|
+ const [confirmDelete, setConfirmDelete] = useState(false)
|
|
|
|
|
+
|
|
|
|
|
+ const setEnabled = async (next: boolean) => {
|
|
|
|
|
+ setTogglingEnabled(true)
|
|
|
|
|
+ try {
|
|
|
|
|
+ await api.setFunctionEnabled(project, summary.function_id, next)
|
|
|
|
|
+ push(`${summary.function_id} ${next ? 'enabled' : 'disabled'}.`, 'success')
|
|
|
|
|
+ onRefresh()
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ push(`Could not change the enabled state: ${errMessage(e)}`, 'error')
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ setTogglingEnabled(false)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const tabs: { id: TabId; label: string }[] = [
|
|
|
|
|
+ { id: 'source', label: 'Source' },
|
|
|
|
|
+ { id: 'policy', label: admin ? 'Policy' : 'Policy (read-only)' },
|
|
|
|
|
+ { id: 'invoke', label: 'Invoke' },
|
|
|
|
|
+ { id: 'runs', label: 'Runs' },
|
|
|
|
|
+ ]
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex flex-col gap-4 rounded-xl border border-slate-700/40 bg-slate-800/20 px-5 py-4">
|
|
|
|
|
+ <div className="flex flex-wrap items-start justify-between gap-3">
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <h2 className="text-lg font-semibold text-slate-100 font-mono">{summary.function_id}</h2>
|
|
|
|
|
+ <p className="text-xs text-slate-500 mt-0.5 font-mono">
|
|
|
|
|
+ {summary.descriptor.type} {routeLabel(summary.descriptor)} · {methodsLabel(summary.descriptor)}
|
|
|
|
|
+ {summary.path && ` · ${summary.path}`}
|
|
|
|
|
+ </p>
|
|
|
|
|
+ <p className="text-xs text-slate-500 mt-0.5">
|
|
|
|
|
+ updated {formatDate(summary.updated_at)} · hash{' '}
|
|
|
|
|
+ <span className="font-mono">{summary.content_hash.slice(0, 12)}</span>
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <div className="flex items-center gap-3">
|
|
|
|
|
+ <div className={togglingEnabled ? 'opacity-50 pointer-events-none' : ''}>
|
|
|
|
|
+ <Toggle checked={summary.enabled} onChange={(next) => void setEnabled(next)} />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() => setConfirmDelete(true)}
|
|
|
|
|
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium text-red-400 hover:text-red-300 hover:bg-red-500/10 transition"
|
|
|
|
|
+ data-testid="fn-delete"
|
|
|
|
|
+ >
|
|
|
|
|
+ <Trash2 size={13} />
|
|
|
|
|
+ Delete
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ {!summary.valid && (
|
|
|
|
|
+ <ErrorPanel title="The last push did not compile, so this function is marked invalid.">
|
|
|
|
|
+ <p className="font-mono text-slate-300">{summary.last_error || 'no error recorded'}</p>
|
|
|
|
|
+ <p>It keeps its row and its policy. Push a version that compiles to bring it back.</p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ <PublicUrlPanel project={project} fn={summary} />
|
|
|
|
|
+
|
|
|
|
|
+ <div className="flex flex-wrap gap-1 border-b border-slate-700">
|
|
|
|
|
+ {tabs.map((t) => (
|
|
|
|
|
+ <button
|
|
|
|
|
+ key={t.id}
|
|
|
|
|
+ type="button"
|
|
|
|
|
+ onClick={() => onTab(t.id)}
|
|
|
|
|
+ className={[
|
|
|
|
|
+ 'px-4 py-2 text-sm font-medium border-b-2 -mb-px transition',
|
|
|
|
|
+ t.id === tab ? 'border-indigo-500 text-slate-100' : 'border-transparent text-slate-400 hover:text-slate-200',
|
|
|
|
|
+ ].join(' ')}
|
|
|
|
|
+ data-testid={`fn-tab-${t.id}`}
|
|
|
|
|
+ >
|
|
|
|
|
+ {t.label}
|
|
|
|
|
+ </button>
|
|
|
|
|
+ ))}
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ {tab === 'source' &&
|
|
|
|
|
+ (detailLoading || !detail ? (
|
|
|
|
|
+ <p className="text-sm text-slate-400 animate-pulse">Loading source...</p>
|
|
|
|
|
+ ) : (
|
|
|
|
|
+ <SourceTab
|
|
|
|
|
+ project={project}
|
|
|
|
|
+ existing={detail}
|
|
|
|
|
+ onSaved={onSaved}
|
|
|
|
|
+ onOpenExisting={onOpenExisting}
|
|
|
|
|
+ />
|
|
|
|
|
+ ))}
|
|
|
|
|
+ {tab === 'policy' && (
|
|
|
|
|
+ <PolicyTab project={project} fn={summary} admin={admin} onSaved={onRefresh} />
|
|
|
|
|
+ )}
|
|
|
|
|
+ {tab === 'invoke' && <InvokeTab project={project} fn={summary} />}
|
|
|
|
|
+ {tab === 'runs' && <RunsTab project={project} fn={summary} />}
|
|
|
|
|
+
|
|
|
|
|
+ <ConfirmDialog
|
|
|
|
|
+ open={confirmDelete}
|
|
|
|
|
+ title="Delete function"
|
|
|
|
|
+ message={`Delete "${summary.function_id}"? Its code, its policy and its run log go with it, and its public URL stops answering.`}
|
|
|
|
|
+ confirmLabel="Delete"
|
|
|
|
|
+ onConfirm={onDelete}
|
|
|
|
|
+ onClose={() => setConfirmDelete(false)}
|
|
|
|
|
+ />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ─── page ─────────────────────────────────────────────────────────────────────
|
|
|
|
|
+
|
|
|
|
|
+export default function Functions() {
|
|
|
|
|
+ const currentProject = useAuthStore((s) => s.currentProject)
|
|
|
|
|
+ const admin = useAuthStore((s) => s.admin)
|
|
|
|
|
+ const push = useToastStore((s) => s.push)
|
|
|
|
|
+ const queryClient = useQueryClient()
|
|
|
|
|
+
|
|
|
|
|
+ // Selection and tab live in the URL, so a function (and the tab someone was
|
|
|
|
|
+ // looking at) is a shareable link, exactly as a filtered Documents view is.
|
|
|
|
|
+ const [searchParams, setSearchParams] = useSearchParams()
|
|
|
|
|
+ const selectedId = searchParams.get('fn') ?? ''
|
|
|
|
|
+ const creating = searchParams.get('new') === '1'
|
|
|
|
|
+ const tab = (searchParams.get('tab') as TabId) || 'source'
|
|
|
|
|
+
|
|
|
|
|
+ const setParams = (patch: Record<string, string>) => {
|
|
|
|
|
+ setSearchParams((prev) => {
|
|
|
|
|
+ const next = new URLSearchParams(prev)
|
|
|
|
|
+ for (const [k, v] of Object.entries(patch)) {
|
|
|
|
|
+ if (v) next.set(k, v)
|
|
|
|
|
+ else next.delete(k)
|
|
|
|
|
+ }
|
|
|
|
|
+ return next
|
|
|
|
|
+ }, { replace: true })
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const select = (id: string) => setParams({ fn: id, new: '', tab: tab })
|
|
|
|
|
+ const startNew = () => setParams({ fn: '', new: '1', tab: 'source' })
|
|
|
|
|
+ const clearSelection = () => setParams({ fn: '', new: '', tab: '' })
|
|
|
|
|
+
|
|
|
|
|
+ const { data, isLoading, isError, error, refetch, isFetching } = useQuery({
|
|
|
|
|
+ queryKey: ['functions', currentProject],
|
|
|
|
|
+ queryFn: () => api.listFunctions(currentProject!),
|
|
|
|
|
+ enabled: !!currentProject,
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ const functions = data?.functions ?? []
|
|
|
|
|
+ const summary = functions.find((f) => f.function_id === selectedId) ?? null
|
|
|
|
|
+
|
|
|
|
|
+ // The selected function belongs to the project being left, so switching
|
|
|
|
|
+ // project drops the selection instead of showing a stale editor. Keyed on an
|
|
|
|
|
+ // actual change, not on the first render: clearing on mount would empty the
|
|
|
|
|
+ // query string of a shared ?fn=...&tab=... link before it ever resolved.
|
|
|
|
|
+ const lastProject = useRef<string | null>(null)
|
|
|
|
|
+ useEffect(() => {
|
|
|
|
|
+ if (lastProject.current !== null && lastProject.current !== currentProject) clearSelection()
|
|
|
|
|
+ lastProject.current = currentProject
|
|
|
|
|
+ // eslint-disable-next-line react-hooks/exhaustive-deps
|
|
|
|
|
+ }, [currentProject])
|
|
|
|
|
+
|
|
|
|
|
+ // Only the single-function GET carries the source.
|
|
|
|
|
+ const { data: detail, isLoading: detailLoading } = useQuery({
|
|
|
|
|
+ queryKey: ['function', currentProject, selectedId],
|
|
|
|
|
+ queryFn: () => api.getFunction(currentProject!, selectedId),
|
|
|
|
|
+ enabled: !!currentProject && !!selectedId && !!summary,
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ const refresh = () => {
|
|
|
|
|
+ void queryClient.invalidateQueries({ queryKey: ['functions', currentProject] })
|
|
|
|
|
+ void queryClient.invalidateQueries({ queryKey: ['function', currentProject] })
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const handleSaved = (id: string) => {
|
|
|
|
|
+ refresh()
|
|
|
|
|
+ if (id !== selectedId || creating) setParams({ fn: id, new: '', tab: 'source' })
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const handleDelete = async () => {
|
|
|
|
|
+ if (!currentProject || !summary) return
|
|
|
|
|
+ try {
|
|
|
|
|
+ await api.deleteFunction(currentProject, summary.function_id)
|
|
|
|
|
+ push(`${summary.function_id} deleted.`, 'success')
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ // A 404 means it is already gone; the end state is the one asked for.
|
|
|
|
|
+ if (e instanceof ApiError && e.status === 404) {
|
|
|
|
|
+ push('That function was already removed; refreshed the list.', 'info')
|
|
|
|
|
+ } else {
|
|
|
|
|
+ push(`Delete failed: ${errMessage(e)}`, 'error')
|
|
|
|
|
+ return
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ clearSelection()
|
|
|
|
|
+ refresh()
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (!currentProject) {
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex flex-col gap-8">
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <h1 className="text-2xl font-semibold text-slate-100">Functions</h1>
|
|
|
|
|
+ <p className="text-slate-400 text-sm mt-1">Server-side JavaScript that serves HTTP routes.</p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center">
|
|
|
|
|
+ <p className="text-slate-400 text-sm">
|
|
|
|
|
+ No project selected - choose a project from the selector above.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className="flex flex-col gap-6">
|
|
|
|
|
+ <div className="flex items-center justify-between flex-wrap gap-3">
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <h1 className="text-2xl font-semibold text-slate-100">Functions</h1>
|
|
|
|
|
+ <p className="text-slate-400 text-sm mt-1">
|
|
|
|
|
+ Project: <span className="text-slate-300 font-mono">{currentProject}</span>
|
|
|
|
|
+ {!isLoading && !isError && (
|
|
|
|
|
+ <span className="ml-2 text-slate-500">
|
|
|
|
|
+ ({functions.length} {functions.length === 1 ? 'function' : 'functions'})
|
|
|
|
|
+ </span>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <div className="flex items-center gap-2">
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={() => void refetch()}
|
|
|
|
|
+ disabled={isFetching}
|
|
|
|
|
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium text-slate-300 bg-slate-700/50 hover:bg-slate-700 transition disabled:opacity-50"
|
|
|
|
|
+ title="Refresh functions"
|
|
|
|
|
+ >
|
|
|
|
|
+ <RefreshCw size={15} className={isFetching ? 'animate-spin' : ''} />
|
|
|
|
|
+ Refresh
|
|
|
|
|
+ </button>
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={startNew}
|
|
|
|
|
+ className="flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition"
|
|
|
|
|
+ data-testid="new-fn-btn"
|
|
|
|
|
+ >
|
|
|
|
|
+ <Plus size={16} />
|
|
|
|
|
+ New function
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ {isError && (
|
|
|
|
|
+ <ErrorPanel title="Failed to load functions.">
|
|
|
|
|
+ <p>{errMessage(error)}</p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {isLoading && (
|
|
|
|
|
+ <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center animate-pulse">
|
|
|
|
|
+ <p className="text-slate-400 text-sm">Loading functions...</p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {!isLoading && !isError && (
|
|
|
|
|
+ <FunctionsTable functions={functions} selected={selectedId} onSelect={select} />
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {creating && (
|
|
|
|
|
+ <div className="flex flex-col gap-4 rounded-xl border border-indigo-500/30 bg-indigo-500/5 px-5 py-4">
|
|
|
|
|
+ <div className="flex items-center justify-between gap-3">
|
|
|
|
|
+ <div className="flex items-center gap-2">
|
|
|
|
|
+ <Code2 size={16} className="text-indigo-300" />
|
|
|
|
|
+ <h2 className="text-lg font-semibold text-slate-100">New function</h2>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <button
|
|
|
|
|
+ onClick={clearSelection}
|
|
|
|
|
+ className="px-3 py-1.5 rounded-md text-xs font-medium text-slate-300 bg-slate-700/50 hover:bg-slate-700 transition"
|
|
|
|
|
+ >
|
|
|
|
|
+ Discard
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <p className="text-xs text-slate-400">
|
|
|
|
|
+ The id comes from the script's <span className="font-mono">on</span> block, so there is
|
|
|
|
|
+ nothing to name here. A first registration inherits the project's default policy, which
|
|
|
|
|
+ grants no collection at all: the function runs, logs and can call out, but reaches no
|
|
|
|
|
+ data until an admin grants it a rule.
|
|
|
|
|
+ </p>
|
|
|
|
|
+ <SourceTab
|
|
|
|
|
+ project={currentProject}
|
|
|
|
|
+ existing={null}
|
|
|
|
|
+ onSaved={handleSaved}
|
|
|
|
|
+ onOpenExisting={(id) => select(id)}
|
|
|
|
|
+ />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {summary && !creating && (
|
|
|
|
|
+ <FunctionDetailPanel
|
|
|
|
|
+ project={currentProject}
|
|
|
|
|
+ summary={summary}
|
|
|
|
|
+ detail={detail ?? null}
|
|
|
|
|
+ detailLoading={detailLoading}
|
|
|
|
|
+ admin={admin}
|
|
|
|
|
+ tab={tab}
|
|
|
|
|
+ onTab={(t) => setParams({ tab: t })}
|
|
|
|
|
+ onRefresh={refresh}
|
|
|
|
|
+ onDelete={() => void handleDelete()}
|
|
|
|
|
+ onOpenExisting={(id) => select(id)}
|
|
|
|
|
+ onSaved={handleSaved}
|
|
|
|
|
+ />
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {selectedId && !summary && !isLoading && !creating && (
|
|
|
|
|
+ <ErrorPanel tone="amber" title={`No function named "${selectedId}" in this project.`}>
|
|
|
|
|
+ <p>It may have been deleted, or the link was made for another project.</p>
|
|
|
|
|
+ </ErrorPanel>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )
|
|
|
|
|
+}
|