Files
ottyl/webapp/src/components/Params.tsx
T
Hugh KaznowskiandClaude Sonnet 5 b3e0272544 Add JSON field path extraction for params/metrics (ticket 015)
RegexToMetricPrimitiveMatcher and the standalone param declaration
(DeclareParamRequest/DataValue::ParamDeclaration) gain an optional
json_field_path, an alternative to capture_group that reads a
dot-separated field path (e.g. "foo.bar") out of lines that parse as
JSON objects. It's additive and serde-defaulted, so existing
regex-based params/metrics are unaffected. Params.tsx now offers a
"JSON field" extraction option when the message match regex looks
like a JSON object.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XFUNZwCvz3kcod3352ZR2o
2026-09-05 19:38:39 +01:00

189 lines
8.4 KiB
TypeScript

import { useMemo, useState } from 'react'
import { ApiError, declareParam, type ParamDeclaration } from '../lib/api'
import { CollapseToggle, PopOutButton, sectionHeaderClassName, sectionHeaderLeftClassName, useSectionCollapsed } from './CollapsibleSection'
import { HelpIcon } from './HelpIcon'
const EMPTY_KIND: ParamDeclaration['kind'] = 'string'
type ExtractionSource = 'regex' | 'json_field'
/// A JSON *object* (not an array/scalar) parses cleanly and pretty-prints with braces — the same
/// shape a JSON field path can be read from, so this is the "line looks like JSON" gate that
/// unlocks the "JSON field" extraction option.
function looksLikeJsonObject(text: string): boolean {
const trimmed = text.trim()
if (!trimmed.startsWith('{')) return false
try {
const parsed = JSON.parse(trimmed)
return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
} catch {
return false
}
}
export function Params({ params, onDeclared }: { params: ParamDeclaration[]; onDeclared: () => void }) {
const [name, setName] = useState('')
const [regex, setRegex] = useState('')
const [captureGroup, setCaptureGroup] = useState('')
const [jsonFieldPath, setJsonFieldPath] = useState('')
const [source, setSource] = useState<ExtractionSource>('regex')
const [kind, setKind] = useState<ParamDeclaration['kind']>(EMPTY_KIND)
const [submitError, setSubmitError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
const [collapsed, setCollapsed] = useSectionCollapsed('params')
// The message match regex doubles as a sample line here so a pasted JSON log line unlocks the
// "JSON field" extraction option — regex-based params are unaffected either way.
const detectedJson = useMemo(() => looksLikeJsonObject(regex), [regex])
const effectiveSource: ExtractionSource = detectedJson ? source : 'regex'
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setSubmitError(null)
setSubmitting(true)
try {
await declareParam({
name,
message_match_regex: regex,
capture_group: effectiveSource === 'json_field' ? '' : captureGroup,
json_field_path: effectiveSource === 'json_field' ? jsonFieldPath : null,
kind,
})
setName('')
setRegex('')
setCaptureGroup('')
setJsonFieldPath('')
setSource('regex')
setKind(EMPTY_KIND)
onDeclared()
} catch (err) {
setSubmitError(err instanceof ApiError ? err.message : 'Failed to declare param')
} finally {
setSubmitting(false)
}
}
return (
<div className="border-b border-border text-sm">
<div className={sectionHeaderClassName}>
<div className={sectionHeaderLeftClassName}>
Params
<HelpIcon sectionId="parameters" label="Help: Params" />
</div>
<div className="flex items-center gap-1.5">
<CollapseToggle collapsed={collapsed} onToggle={() => setCollapsed(!collapsed)} />
<PopOutButton section="params" />
</div>
</div>
<div className="flex gap-4 p-3" hidden={collapsed}>
<form onSubmit={handleSubmit} className="w-80 shrink-0 space-y-2">
<div>
<label className="mb-1 block text-xs text-text-subtle">Name</label>
<input
className="w-full rounded border border-border-soft bg-surface-1 px-2 py-1 text-sm text-text placeholder:text-text-subtle focus:border-border-strong focus:outline-none"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="path"
required
/>
</div>
<div>
<label className="mb-1 block text-xs text-text-subtle">Message match regex</label>
<input
className="w-full rounded border border-border-soft bg-surface-1 px-2 py-1 font-mono text-sm text-text placeholder:text-text-subtle focus:border-border-strong focus:outline-none"
value={regex}
onChange={(e) => setRegex(e.target.value)}
placeholder={String.raw`request path=(?P<path>\S+)`}
required
/>
</div>
{detectedJson && (
<div>
<label className="mb-1 block text-xs text-text-subtle">Extraction</label>
<select
className="w-full rounded border border-border-soft bg-surface-1 px-2 py-1 text-xs text-text focus:border-border-strong focus:outline-none"
value={source}
onChange={(e) => setSource(e.target.value as ExtractionSource)}
>
<option value="regex">Regex capture group</option>
<option value="json_field">JSON field</option>
</select>
</div>
)}
{effectiveSource === 'json_field' ? (
<div className="flex items-end gap-1">
<div className="min-w-0 flex-1">
<label className="mb-1 block text-xs text-text-subtle">JSON field path</label>
<input
className="w-full min-w-0 rounded border border-border-soft bg-surface-1 px-1.5 py-1 font-mono text-xs text-text placeholder:text-text-subtle focus:border-border-strong focus:outline-none"
value={jsonFieldPath}
onChange={(e) => setJsonFieldPath(e.target.value)}
placeholder="foo.bar"
required
/>
</div>
<select
className="rounded border border-border-soft bg-surface-1 px-1 py-1 text-xs text-text focus:border-border-strong focus:outline-none"
value={kind}
onChange={(e) => setKind(e.target.value as ParamDeclaration['kind'])}
>
<option value="string">string</option>
<option value="number">number</option>
<option value="timestamp">timestamp</option>
<option value="duration">duration</option>
</select>
</div>
) : (
<div className="flex items-end gap-1">
<div className="min-w-0 flex-1">
<label className="mb-1 block text-xs text-text-subtle">Capture group</label>
<input
className="w-full min-w-0 rounded border border-border-soft bg-surface-1 px-1.5 py-1 text-xs text-text placeholder:text-text-subtle focus:border-border-strong focus:outline-none"
value={captureGroup}
onChange={(e) => setCaptureGroup(e.target.value)}
placeholder="path"
required
/>
</div>
<select
className="rounded border border-border-soft bg-surface-1 px-1 py-1 text-xs text-text focus:border-border-strong focus:outline-none"
value={kind}
onChange={(e) => setKind(e.target.value as ParamDeclaration['kind'])}
>
<option value="string">string</option>
<option value="number">number</option>
<option value="timestamp">timestamp</option>
<option value="duration">duration</option>
</select>
</div>
)}
{submitError && <div className="rounded border border-danger-border bg-danger-bg/50 px-2 py-1 text-xs text-danger-text">{submitError}</div>}
<button
type="submit"
disabled={submitting}
className="rounded border border-border-soft px-3 py-1 text-sm text-text-secondary hover:bg-surface-2 disabled:opacity-50"
>
{submitting ? 'Declaring…' : 'Declare param'}
</button>
</form>
<div className="min-w-0 flex-1">
<div className="mb-1 text-xs text-text-subtle">Declared params</div>
<div className="flex flex-wrap gap-1">
{params.length === 0 && <span className="text-xs text-text-faint">No params declared yet.</span>}
{params.map((p) => (
<span
key={p.name}
className="rounded border border-border-soft px-2 py-1 text-xs text-text-secondary"
title={p.message_match_regex}
>
{p.name} ({p.kind}, {p.json_field_path ? `json field ${p.json_field_path}` : `group ${p.capture_group}`})
</span>
))}
</div>
</div>
</div>
</div>
)
}