mirror of
https://github.com/SigNoz/signoz.git
synced 2026-06-18 22:40:34 +01:00
Compare commits
5 Commits
nv/schema-
...
feat/llm-a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfbf0a4f9e | ||
|
|
d9df868e33 | ||
|
|
1c06a57361 | ||
|
|
dfd3bce670 | ||
|
|
9725a268cc |
@@ -330,3 +330,10 @@ export const AIAssistantPage = Loadable(
|
||||
/* webpackChunkName: "AI Assistant Page" */ 'pages/AIAssistantPage/AIAssistantPage'
|
||||
),
|
||||
);
|
||||
|
||||
export const LLMObservabilityAttributeMappingPage = Loadable(
|
||||
() =>
|
||||
import(
|
||||
/* webpackChunkName: "LLM Observability Attribute Mapping Page" */ 'pages/LLMObservabilityAttributeMapping'
|
||||
),
|
||||
);
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
IntegrationsDetailsPage,
|
||||
LicensePage,
|
||||
ListAllALertsPage,
|
||||
LLMObservabilityAttributeMappingPage,
|
||||
LiveLogs,
|
||||
Login,
|
||||
Logs,
|
||||
@@ -505,6 +506,13 @@ const routes: AppRoutes[] = [
|
||||
key: 'AI_ASSISTANT',
|
||||
isPrivate: true,
|
||||
},
|
||||
{
|
||||
path: ROUTES.LLM_OBSERVABILITY_ATTRIBUTE_MAPPING,
|
||||
exact: true,
|
||||
component: LLMObservabilityAttributeMappingPage,
|
||||
key: 'LLM_OBSERVABILITY_ATTRIBUTE_MAPPING',
|
||||
isPrivate: true,
|
||||
},
|
||||
];
|
||||
|
||||
export const SUPPORT_ROUTE: AppRoutes = {
|
||||
|
||||
@@ -91,6 +91,8 @@ const ROUTES = {
|
||||
AI_ASSISTANT_BASE: '/ai-assistant',
|
||||
AI_ASSISTANT_ICON_PREVIEW: '/ai-assistant-icon-preview',
|
||||
MCP_SERVER: '/settings/mcp-server',
|
||||
LLM_OBSERVABILITY_ATTRIBUTE_MAPPING:
|
||||
'/llm-observability/settings/attribute-mapping',
|
||||
} as const;
|
||||
|
||||
export default ROUTES;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
|
||||
interface AttributeMappingHeaderProps {
|
||||
isDirty: boolean;
|
||||
isSaving: boolean;
|
||||
onDiscard: () => void;
|
||||
onSave: () => void;
|
||||
}
|
||||
|
||||
function AttributeMappingHeader({
|
||||
isDirty,
|
||||
isSaving,
|
||||
onDiscard,
|
||||
onSave,
|
||||
}: AttributeMappingHeaderProps): JSX.Element {
|
||||
return (
|
||||
<header className="page-header">
|
||||
<div className="page-header__title">
|
||||
<h1>Attribute Mapping</h1>
|
||||
<p>Configure source-to-target attribute remapping for LLM traces</p>
|
||||
</div>
|
||||
<div className="page-header__actions">
|
||||
{isDirty && (
|
||||
<span className="page-header__unsaved" data-testid="unsaved-changes">
|
||||
Unsaved changes
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
onClick={onDiscard}
|
||||
disabled={!isDirty || isSaving}
|
||||
testId="discard-changes-btn"
|
||||
>
|
||||
Discard
|
||||
</Button>
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={onSave}
|
||||
loading={isSaving}
|
||||
disabled={!isDirty || isSaving}
|
||||
testId="save-changes-btn"
|
||||
>
|
||||
{isSaving ? 'Saving…' : 'Save changes'}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export default AttributeMappingHeader;
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Plus, X } from '@signozhq/icons';
|
||||
|
||||
import KeySearchInput from './KeySearchInput';
|
||||
import { FieldContextValue } from './types';
|
||||
|
||||
interface ConditionKeyListProps {
|
||||
label: string;
|
||||
labelHint?: string;
|
||||
keys: string[];
|
||||
placeholder: string;
|
||||
addLabel: string;
|
||||
testIdPrefix: string;
|
||||
fieldContext: FieldContextValue;
|
||||
onChange: (keys: string[]) => void;
|
||||
}
|
||||
|
||||
// Editor for one list of condition keys (the group's span-attribute or
|
||||
// resource gating keys). Substring "contains" match, order irrelevant.
|
||||
function ConditionKeyList({
|
||||
label,
|
||||
labelHint,
|
||||
keys,
|
||||
placeholder,
|
||||
addLabel,
|
||||
testIdPrefix,
|
||||
fieldContext,
|
||||
onChange,
|
||||
}: ConditionKeyListProps): JSX.Element {
|
||||
const updateKey = (index: number, value: string): void => {
|
||||
onChange(keys.map((key, i) => (i === index ? value : key)));
|
||||
};
|
||||
|
||||
const addKey = (): void => {
|
||||
onChange([...keys, '']);
|
||||
};
|
||||
|
||||
const removeKey = (index: number): void => {
|
||||
onChange(keys.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="group-form__field">
|
||||
<span className="group-form__label">
|
||||
{label}
|
||||
{labelHint && <span className="group-form__label-hint"> {labelHint}</span>}
|
||||
</span>
|
||||
|
||||
{keys.length > 0 && (
|
||||
<div className="group-form__keys">
|
||||
{keys.map((key, index) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<div className="group-form__key" key={index}>
|
||||
<KeySearchInput
|
||||
className="group-form__key-input"
|
||||
placeholder={placeholder}
|
||||
value={key}
|
||||
fieldContext={fieldContext}
|
||||
onChange={(next): void => updateKey(index, next)}
|
||||
testId={`${testIdPrefix}-${index}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="icon"
|
||||
aria-label="Remove key"
|
||||
onClick={(): void => removeKey(index)}
|
||||
testId={`${testIdPrefix}-remove-${index}`}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="dashed"
|
||||
color="secondary"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={addKey}
|
||||
testId={`${testIdPrefix}-add`}
|
||||
>
|
||||
{addLabel}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ConditionKeyList;
|
||||
@@ -0,0 +1,76 @@
|
||||
.group-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
padding: 4px 0;
|
||||
|
||||
&__field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
&--row {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
}
|
||||
|
||||
&__label {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
&__label-hint {
|
||||
font-weight: 400;
|
||||
text-transform: none;
|
||||
letter-spacing: normal;
|
||||
}
|
||||
|
||||
&__hint {
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
&__keys {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__key {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
&__key-input {
|
||||
flex: 1;
|
||||
font-family: 'Geist Mono', monospace;
|
||||
}
|
||||
|
||||
&__error {
|
||||
padding: 10px 12px;
|
||||
border-radius: 4px;
|
||||
background: rgba(229, 72, 77, 0.1);
|
||||
color: var(--bg-cherry-400);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
&__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__footer-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { DrawerWrapper } from '@signozhq/ui/drawer';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import { Trash2 } from '@signozhq/icons';
|
||||
|
||||
import ConditionKeyList from './ConditionKeyList';
|
||||
import { FieldContext, GroupDraft, MapperDraftMode } from './types';
|
||||
import { isGroupDraftValid } from './utils';
|
||||
|
||||
import './GroupFormDrawer.styles.scss';
|
||||
|
||||
interface GroupFormDrawerProps {
|
||||
isOpen: boolean;
|
||||
mode: MapperDraftMode;
|
||||
draft: GroupDraft;
|
||||
setDraft: (next: GroupDraft) => void;
|
||||
onClose: () => void;
|
||||
onSave: () => void;
|
||||
onDelete: () => void;
|
||||
isSaving: boolean;
|
||||
isDeleting: boolean;
|
||||
saveError: string | null;
|
||||
}
|
||||
|
||||
function GroupFormDrawer({
|
||||
isOpen,
|
||||
mode,
|
||||
draft,
|
||||
setDraft,
|
||||
onClose,
|
||||
onSave,
|
||||
onDelete,
|
||||
isSaving,
|
||||
isDeleting,
|
||||
saveError,
|
||||
}: GroupFormDrawerProps): JSX.Element {
|
||||
const isEdit = mode === 'edit';
|
||||
const isValid = isGroupDraftValid(draft);
|
||||
|
||||
return (
|
||||
<DrawerWrapper
|
||||
open={isOpen}
|
||||
onOpenChange={(open): void => {
|
||||
if (!open) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
title={isEdit ? 'Edit group' : 'New group'}
|
||||
subTitle="A group gates which spans its mappings run on"
|
||||
width="wide"
|
||||
testId="group-form-drawer"
|
||||
footer={
|
||||
<div className="group-form__footer">
|
||||
{isEdit && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="destructive"
|
||||
prefix={<Trash2 size={14} />}
|
||||
onClick={onDelete}
|
||||
disabled={isDeleting}
|
||||
testId="group-form-delete"
|
||||
>
|
||||
{isDeleting ? 'Deleting…' : 'Delete'}
|
||||
</Button>
|
||||
)}
|
||||
<div className="group-form__footer-actions">
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
onClick={onClose}
|
||||
testId="group-form-cancel"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={onSave}
|
||||
disabled={!isValid || isSaving}
|
||||
testId="group-form-save"
|
||||
>
|
||||
{/* eslint-disable-next-line no-nested-ternary */}
|
||||
{isSaving ? 'Saving…' : isEdit ? 'Save group' : 'Create group'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="group-form">
|
||||
<div className="group-form__field">
|
||||
<span className="group-form__label">Group name</span>
|
||||
<Input
|
||||
placeholder="e.g. OpenAI gateway"
|
||||
value={draft.name}
|
||||
onChange={(event): void =>
|
||||
setDraft({ ...draft, name: event.target.value })
|
||||
}
|
||||
testId="group-form-name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="group-form__field group-form__field--row">
|
||||
<span className="group-form__label">Enabled</span>
|
||||
<Switch
|
||||
value={draft.enabled}
|
||||
onChange={(checked): void => setDraft({ ...draft, enabled: checked })}
|
||||
testId="group-form-enabled"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ConditionKeyList
|
||||
label="Condition · span attribute keys"
|
||||
labelHint="· runs when a span attribute key contains any of these"
|
||||
keys={draft.attributes}
|
||||
placeholder="e.g. gen_ai."
|
||||
addLabel="Add attribute key"
|
||||
testIdPrefix="group-form-attribute"
|
||||
fieldContext={FieldContext.attribute}
|
||||
onChange={(attributes): void => setDraft({ ...draft, attributes })}
|
||||
/>
|
||||
|
||||
<ConditionKeyList
|
||||
label="Condition · resource keys"
|
||||
labelHint="· or when a resource key contains any of these"
|
||||
keys={draft.resource}
|
||||
placeholder="e.g. service.name"
|
||||
addLabel="Add resource key"
|
||||
testIdPrefix="group-form-resource"
|
||||
fieldContext={FieldContext.resource}
|
||||
onChange={(resource): void => setDraft({ ...draft, resource })}
|
||||
/>
|
||||
|
||||
<span className="group-form__hint">
|
||||
Leave both empty to run this group on every span.
|
||||
</span>
|
||||
|
||||
{saveError && (
|
||||
<div className="group-form__error" role="alert">
|
||||
{saveError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DrawerWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export default GroupFormDrawer;
|
||||
@@ -0,0 +1,10 @@
|
||||
interface IndexBadgeProps {
|
||||
index: number;
|
||||
}
|
||||
|
||||
// Small positional badge mirroring the Pipelines list ordering chip.
|
||||
function IndexBadge({ index }: IndexBadgeProps): JSX.Element {
|
||||
return <span className="am-index-badge">{index + 1}</span>;
|
||||
}
|
||||
|
||||
export default IndexBadge;
|
||||
@@ -0,0 +1,51 @@
|
||||
.key-search {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
&__dropdown {
|
||||
position: absolute;
|
||||
top: calc(100% + 4px);
|
||||
left: 0;
|
||||
z-index: 20;
|
||||
min-width: 100%;
|
||||
width: max-content;
|
||||
max-width: 420px;
|
||||
max-height: 240px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--bg-slate-400, rgba(255, 255, 255, 0.12));
|
||||
border-radius: 6px;
|
||||
background: var(--bg-ink-400, #121317);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
|
||||
|
||||
&--empty {
|
||||
padding: 8px 10px;
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
}
|
||||
|
||||
&__option {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
padding: 6px 10px;
|
||||
border: none;
|
||||
border-radius: 3px;
|
||||
background: transparent;
|
||||
color: var(--bg-vanilla-100);
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: 12px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--bg-slate-400, rgba(255, 255, 255, 0.08));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { useGetFieldsKeys } from 'api/generated/services/fields';
|
||||
import {
|
||||
TelemetrytypesFieldContextDTO,
|
||||
TelemetrytypesSignalDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import cx from 'classnames';
|
||||
import useDebounce from 'hooks/useDebounce';
|
||||
|
||||
import { FieldContext, FieldContextValue } from './types';
|
||||
|
||||
import './KeySearchInput.styles.scss';
|
||||
|
||||
const SUGGESTION_LIMIT = 50;
|
||||
const DEBOUNCE_MS = 300;
|
||||
|
||||
interface KeySearchInputProps {
|
||||
value: string;
|
||||
fieldContext: FieldContextValue;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
testId?: string;
|
||||
onChange: (value: string) => void;
|
||||
}
|
||||
|
||||
// Maps the mapper's attribute/resource context to the fields-endpoint context.
|
||||
function toFieldsContext(
|
||||
context: FieldContextValue,
|
||||
): TelemetrytypesFieldContextDTO {
|
||||
return context === FieldContext.resource
|
||||
? TelemetrytypesFieldContextDTO.resource
|
||||
: TelemetrytypesFieldContextDTO.attribute;
|
||||
}
|
||||
|
||||
// Free-text input with span/resource key suggestions from /api/v1/fields/keys
|
||||
// (signal=traces). Typing keeps the custom value; suggestions are assistive.
|
||||
function KeySearchInput({
|
||||
value,
|
||||
fieldContext,
|
||||
placeholder,
|
||||
className,
|
||||
disabled,
|
||||
testId,
|
||||
onChange,
|
||||
}: KeySearchInputProps): JSX.Element {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const debouncedSearch = useDebounce(value, DEBOUNCE_MS);
|
||||
|
||||
const { data, isFetching } = useGetFieldsKeys(
|
||||
{
|
||||
signal: TelemetrytypesSignalDTO.traces,
|
||||
fieldContext: toFieldsContext(fieldContext),
|
||||
searchText: debouncedSearch,
|
||||
limit: SUGGESTION_LIMIT,
|
||||
},
|
||||
{ query: { enabled: isOpen && !disabled, keepPreviousData: true } },
|
||||
);
|
||||
|
||||
const suggestions = useMemo(() => {
|
||||
const keys = data?.data?.keys ?? {};
|
||||
return Object.keys(keys)
|
||||
.filter((key) => key !== value)
|
||||
.slice(0, SUGGESTION_LIMIT);
|
||||
}, [data, value]);
|
||||
|
||||
return (
|
||||
<div className={cx('key-search', className)}>
|
||||
<Input
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
autoComplete="off"
|
||||
onChange={(event): void => {
|
||||
onChange(event.target.value);
|
||||
setIsOpen(true);
|
||||
}}
|
||||
onFocus={(): void => setIsOpen(true)}
|
||||
onBlur={(): void => setIsOpen(false)}
|
||||
testId={testId}
|
||||
/>
|
||||
{isOpen && suggestions.length > 0 && (
|
||||
<div className="key-search__dropdown" data-testid={`${testId}-dropdown`}>
|
||||
{suggestions.map((name) => (
|
||||
<button
|
||||
type="button"
|
||||
key={name}
|
||||
className="key-search__option"
|
||||
// onMouseDown (not onClick) so selection runs before the input blur.
|
||||
onMouseDown={(event): void => {
|
||||
event.preventDefault();
|
||||
onChange(name);
|
||||
setIsOpen(false);
|
||||
}}
|
||||
data-testid={`${testId}-option-${name}`}
|
||||
>
|
||||
{name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{isOpen && isFetching && suggestions.length === 0 && (
|
||||
<div className="key-search__dropdown key-search__dropdown--empty">
|
||||
Searching…
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default KeySearchInput;
|
||||
@@ -0,0 +1,183 @@
|
||||
.llm-observability-attribute-mapping {
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
|
||||
&__title {
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 13px;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
}
|
||||
|
||||
&__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
&__unsaved {
|
||||
font-size: 13px;
|
||||
color: var(--bg-amber-400);
|
||||
}
|
||||
}
|
||||
|
||||
.page-error {
|
||||
padding: 12px 16px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg-cherry-500-opacity-10, rgba(229, 72, 77, 0.1));
|
||||
color: var(--bg-cherry-400);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.page-footer {
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
.am-index-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 22px;
|
||||
height: 22px;
|
||||
padding: 0 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--bg-robin-500);
|
||||
color: var(--bg-vanilla-100);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.am-row-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.am-add-row {
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.groups-table__wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.am-table {
|
||||
&__empty {
|
||||
padding: 24px 12px;
|
||||
text-align: center;
|
||||
color: var(--bg-vanilla-400);
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
.groups-table {
|
||||
&__name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&__name-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__sub-row > td {
|
||||
padding: 0 16px 12px;
|
||||
background: var(--bg-ink-400, rgba(255, 255, 255, 0.02));
|
||||
}
|
||||
|
||||
&__filters {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
&__filter {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
&__filter-key {
|
||||
font-family: 'Geist Mono', monospace;
|
||||
}
|
||||
|
||||
&__edited {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.mappers-table__wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.mappers-table {
|
||||
margin: 4px 0;
|
||||
|
||||
&__target {
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&__sources {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
&__source-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
max-width: 220px;
|
||||
padding: 2px 8px;
|
||||
border: 1px solid var(--bg-slate-400, rgba(255, 255, 255, 0.12));
|
||||
border-radius: 6px;
|
||||
background: var(--bg-ink-300, rgba(255, 255, 255, 0.04));
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
&__source-more {
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&__error {
|
||||
padding: 12px;
|
||||
font-size: 13px;
|
||||
color: var(--bg-cherry-400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useCallback } from 'react';
|
||||
|
||||
import AttributeMappingHeader from './AttributeMappingHeader';
|
||||
import GroupFormDrawer from './GroupFormDrawer';
|
||||
import MapperGroupsTable from './MapperGroupsTable';
|
||||
import { useAttributeMappingStore } from './useAttributeMappingStore';
|
||||
import { useGroupFormDrawer } from './useGroupFormDrawer';
|
||||
|
||||
import './LLMObservabilityAttributeMapping.styles.scss';
|
||||
|
||||
function LLMObservabilityAttributeMapping(): JSX.Element {
|
||||
const store = useAttributeMappingStore();
|
||||
const groupDrawer = useGroupFormDrawer();
|
||||
|
||||
const handleGroupSave = useCallback((): void => {
|
||||
store.upsertGroup(groupDrawer.draft);
|
||||
groupDrawer.close();
|
||||
}, [store, groupDrawer]);
|
||||
|
||||
const handleGroupDelete = useCallback((): void => {
|
||||
if (groupDrawer.draft.id) {
|
||||
store.removeGroup(groupDrawer.draft.id);
|
||||
}
|
||||
groupDrawer.close();
|
||||
}, [store, groupDrawer]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="llm-observability-attribute-mapping"
|
||||
data-testid="llm-observability-attribute-mapping-page"
|
||||
>
|
||||
<AttributeMappingHeader
|
||||
isDirty={store.isDirty}
|
||||
isSaving={store.isSaving}
|
||||
onDiscard={store.discard}
|
||||
onSave={store.save}
|
||||
/>
|
||||
|
||||
{store.saveError && (
|
||||
<div className="page-error" role="alert">
|
||||
{store.saveError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{store.isError && (
|
||||
<div className="page-error" role="alert">
|
||||
Failed to load mapping groups. Please try again.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<MapperGroupsTable
|
||||
store={store}
|
||||
onEditGroup={groupDrawer.openForEdit}
|
||||
onAddGroup={groupDrawer.openForAdd}
|
||||
/>
|
||||
|
||||
<footer className="page-footer">
|
||||
Showing {store.groups.length} group{store.groups.length === 1 ? '' : 's'}
|
||||
</footer>
|
||||
|
||||
<GroupFormDrawer
|
||||
isOpen={groupDrawer.isOpen}
|
||||
mode={groupDrawer.mode}
|
||||
draft={groupDrawer.draft}
|
||||
setDraft={groupDrawer.setDraft}
|
||||
onClose={groupDrawer.close}
|
||||
onSave={handleGroupSave}
|
||||
onDelete={handleGroupDelete}
|
||||
isSaving={false}
|
||||
isDeleting={false}
|
||||
saveError={null}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LLMObservabilityAttributeMapping;
|
||||
@@ -0,0 +1,104 @@
|
||||
.mapper-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
padding: 4px 0;
|
||||
|
||||
&__field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__label {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
&__label-hint {
|
||||
font-weight: 400;
|
||||
text-transform: none;
|
||||
letter-spacing: normal;
|
||||
}
|
||||
|
||||
&__hint {
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
&__sources {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__source {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
&__source-handle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 4px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--bg-vanilla-400);
|
||||
cursor: grab;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
}
|
||||
|
||||
&__source-index {
|
||||
width: 20px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
&__source-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-family: 'Geist Mono', monospace;
|
||||
}
|
||||
|
||||
&__source-select {
|
||||
flex: 0 0 auto;
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
&__field-context {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
&__error {
|
||||
padding: 10px 12px;
|
||||
border-radius: 4px;
|
||||
background: rgba(229, 72, 77, 0.1);
|
||||
color: var(--bg-cherry-400);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
&__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__footer-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { DrawerWrapper } from '@signozhq/ui/drawer';
|
||||
import { SelectSimple } from '@signozhq/ui/select';
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
DragEndEvent,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from '@dnd-kit/core';
|
||||
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { Plus, Trash2 } from '@signozhq/icons';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
import KeySearchInput from './KeySearchInput';
|
||||
import SourceAttributeRow from './SourceAttributeRow';
|
||||
import {
|
||||
FieldContext,
|
||||
FieldContextValue,
|
||||
MapperDraft,
|
||||
MapperDraftMode,
|
||||
SourceConfig,
|
||||
} from './types';
|
||||
import { createEmptySource, isMapperDraftValid } from './utils';
|
||||
|
||||
import './MapperFormDrawer.styles.scss';
|
||||
|
||||
const FIELD_CONTEXT_OPTIONS = [
|
||||
{ value: FieldContext.attribute, label: 'Span attribute' },
|
||||
{ value: FieldContext.resource, label: 'Resource' },
|
||||
];
|
||||
|
||||
interface MapperFormDrawerProps {
|
||||
isOpen: boolean;
|
||||
mode: MapperDraftMode;
|
||||
draft: MapperDraft;
|
||||
setDraft: (next: MapperDraft) => void;
|
||||
onClose: () => void;
|
||||
onSave: () => void;
|
||||
onDelete: () => void;
|
||||
isSaving: boolean;
|
||||
isDeleting: boolean;
|
||||
saveError: string | null;
|
||||
}
|
||||
|
||||
function MapperFormDrawer({
|
||||
isOpen,
|
||||
mode,
|
||||
draft,
|
||||
setDraft,
|
||||
onClose,
|
||||
onSave,
|
||||
onDelete,
|
||||
isSaving,
|
||||
isDeleting,
|
||||
saveError,
|
||||
}: MapperFormDrawerProps): JSX.Element {
|
||||
const isEdit = mode === 'edit';
|
||||
const isValid = isMapperDraftValid(draft);
|
||||
|
||||
// Stable per-row ids for the sortable list. These are UI-only (never sent to
|
||||
// the API and excluded from the draft), so dnd-kit can track rows reliably
|
||||
// even though sources are stored as a plain array. Re-seeded each time the
|
||||
// drawer opens; kept in lockstep with the sources array on add/remove/drag.
|
||||
const [rowIds, setRowIds] = useState<string[]>([]);
|
||||
const wasOpen = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen && !wasOpen.current) {
|
||||
setRowIds(draft.sources.map(() => uuid()));
|
||||
}
|
||||
wasOpen.current = isOpen;
|
||||
// Only re-seed on the closed→open transition.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isOpen]);
|
||||
|
||||
const sourceIds = draft.sources.map(
|
||||
(_, index) => rowIds[index] ?? `pending-${index}`,
|
||||
);
|
||||
|
||||
// 5px activation distance so clicking into the input never starts a drag.
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
|
||||
);
|
||||
|
||||
const updateSource = (index: number, patch: Partial<SourceConfig>): void => {
|
||||
const sources = draft.sources.map((source, i) =>
|
||||
i === index ? { ...source, ...patch } : source,
|
||||
);
|
||||
setDraft({ ...draft, sources });
|
||||
};
|
||||
|
||||
const addSource = (): void => {
|
||||
setDraft({ ...draft, sources: [...draft.sources, createEmptySource()] });
|
||||
setRowIds((prev) => [...prev, uuid()]);
|
||||
};
|
||||
|
||||
const removeSource = (index: number): void => {
|
||||
const sources = draft.sources.filter((_, i) => i !== index);
|
||||
if (sources.length === 0) {
|
||||
setDraft({ ...draft, sources: [createEmptySource()] });
|
||||
setRowIds([uuid()]);
|
||||
return;
|
||||
}
|
||||
setDraft({ ...draft, sources });
|
||||
setRowIds((prev) => prev.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent): void => {
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) {
|
||||
return;
|
||||
}
|
||||
const from = sourceIds.indexOf(String(active.id));
|
||||
const to = sourceIds.indexOf(String(over.id));
|
||||
if (from === -1 || to === -1) {
|
||||
return;
|
||||
}
|
||||
setDraft({ ...draft, sources: arrayMove(draft.sources, from, to) });
|
||||
setRowIds((prev) => arrayMove(prev, from, to));
|
||||
};
|
||||
|
||||
return (
|
||||
<DrawerWrapper
|
||||
open={isOpen}
|
||||
onOpenChange={(open): void => {
|
||||
if (!open) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
title={isEdit ? 'Edit mapping' : 'New custom mapping'}
|
||||
subTitle="Map source attributes onto a canonical target attribute"
|
||||
width="wide"
|
||||
testId="mapper-form-drawer"
|
||||
footer={
|
||||
<div className="mapper-form__footer">
|
||||
{isEdit && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="destructive"
|
||||
prefix={<Trash2 size={14} />}
|
||||
onClick={onDelete}
|
||||
disabled={isDeleting}
|
||||
testId="mapper-form-delete"
|
||||
>
|
||||
{isDeleting ? 'Deleting…' : 'Delete'}
|
||||
</Button>
|
||||
)}
|
||||
<div className="mapper-form__footer-actions">
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
onClick={onClose}
|
||||
testId="mapper-form-cancel"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={onSave}
|
||||
disabled={!isValid || isSaving}
|
||||
testId="mapper-form-save"
|
||||
>
|
||||
{/* eslint-disable-next-line no-nested-ternary */}
|
||||
{isSaving ? 'Saving…' : isEdit ? 'Save mapping' : 'Create mapping'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="mapper-form">
|
||||
<div className="mapper-form__field">
|
||||
<span className="mapper-form__label">Target attribute</span>
|
||||
<KeySearchInput
|
||||
placeholder="e.g. gen_ai.content.prompt"
|
||||
value={draft.name}
|
||||
fieldContext={draft.fieldContext}
|
||||
disabled={isEdit}
|
||||
onChange={(name): void => setDraft({ ...draft, name })}
|
||||
testId="mapper-form-target"
|
||||
/>
|
||||
{isEdit && (
|
||||
<span className="mapper-form__hint">
|
||||
The target attribute can't be changed after creation.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mapper-form__field">
|
||||
<span className="mapper-form__label">Write target to</span>
|
||||
<SelectSimple
|
||||
className="mapper-form__field-context"
|
||||
items={FIELD_CONTEXT_OPTIONS}
|
||||
value={draft.fieldContext}
|
||||
withPortal={false}
|
||||
onChange={(next): void =>
|
||||
setDraft({ ...draft, fieldContext: next as FieldContextValue })
|
||||
}
|
||||
testId="mapper-form-field-context"
|
||||
/>
|
||||
<span className="mapper-form__hint">
|
||||
Where the standardized attribute is written.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mapper-form__field">
|
||||
<span className="mapper-form__label">
|
||||
Source attributes
|
||||
<span className="mapper-form__label-hint">
|
||||
{' '}
|
||||
· priority: top → bottom · drag to reorder
|
||||
</span>
|
||||
</span>
|
||||
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
modifiers={[restrictToVerticalAxis]}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext items={sourceIds} strategy={verticalListSortingStrategy}>
|
||||
<div className="mapper-form__sources">
|
||||
{draft.sources.map((source, index) => (
|
||||
<SourceAttributeRow
|
||||
key={sourceIds[index]}
|
||||
id={sourceIds[index]}
|
||||
index={index}
|
||||
value={source}
|
||||
canRemove={draft.sources.length > 1}
|
||||
onChange={updateSource}
|
||||
onRemove={removeSource}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
<Button
|
||||
variant="dashed"
|
||||
color="secondary"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={addSource}
|
||||
testId="mapper-form-add-source"
|
||||
>
|
||||
Add another source
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{saveError && (
|
||||
<div className="mapper-form__error" role="alert">
|
||||
{saveError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DrawerWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export default MapperFormDrawer;
|
||||
@@ -0,0 +1,212 @@
|
||||
import { useState } from 'react';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@signozhq/ui/table';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Pencil,
|
||||
Plus,
|
||||
Trash2,
|
||||
} from '@signozhq/icons';
|
||||
|
||||
import MappersTable from './MappersTable';
|
||||
import { DraftGroup } from './types';
|
||||
import { AttributeMappingStore } from './useAttributeMappingStore';
|
||||
import { conditionFiltersFromGroup } from './utils';
|
||||
|
||||
const COLUMN_COUNT = 4;
|
||||
|
||||
interface MapperGroupsTableProps {
|
||||
store: AttributeMappingStore;
|
||||
onEditGroup: (group: DraftGroup) => void;
|
||||
onAddGroup: () => void;
|
||||
}
|
||||
|
||||
function FiltersCell({ group }: { group: DraftGroup }): JSX.Element {
|
||||
const filters = conditionFiltersFromGroup(group);
|
||||
if (filters.length === 0) {
|
||||
return <span className="muted">No condition · always runs</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="groups-table__filters"
|
||||
data-testid={`group-filters-${group.localId}`}
|
||||
>
|
||||
{filters.map((filter) => (
|
||||
<div
|
||||
className="groups-table__filter"
|
||||
key={`${filter.context}:${filter.key}`}
|
||||
>
|
||||
<Badge
|
||||
color={filter.context === 'resource' ? 'amber' : 'robin'}
|
||||
variant="outline"
|
||||
>
|
||||
{filter.context}
|
||||
</Badge>
|
||||
<span className="groups-table__filter-key">contains {filter.key}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface GroupRowProps {
|
||||
group: DraftGroup;
|
||||
store: AttributeMappingStore;
|
||||
isExpanded: boolean;
|
||||
onToggleExpand: (localId: string) => void;
|
||||
onEditGroup: (group: DraftGroup) => void;
|
||||
}
|
||||
|
||||
function GroupRow({
|
||||
group,
|
||||
store,
|
||||
isExpanded,
|
||||
onToggleExpand,
|
||||
onEditGroup,
|
||||
}: GroupRowProps): JSX.Element {
|
||||
return (
|
||||
<>
|
||||
<TableRow data-testid={`group-row-${group.localId}`}>
|
||||
<TableCell>
|
||||
<div className="groups-table__name-cell">
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="icon"
|
||||
aria-label={isExpanded ? 'Collapse group' : 'Expand group'}
|
||||
onClick={(): void => onToggleExpand(group.localId)}
|
||||
testId={`group-expand-${group.localId}`}
|
||||
>
|
||||
{isExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
|
||||
</Button>
|
||||
<span
|
||||
className="groups-table__name"
|
||||
data-testid={`group-name-${group.localId}`}
|
||||
>
|
||||
{group.name}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<FiltersCell group={group} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="muted">{group.mappers.length} mappings</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="am-row-actions">
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="icon"
|
||||
aria-label="Edit group"
|
||||
onClick={(): void => onEditGroup(group)}
|
||||
testId={`group-edit-${group.localId}`}
|
||||
>
|
||||
<Pencil size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="destructive"
|
||||
size="icon"
|
||||
aria-label="Delete group"
|
||||
onClick={(): void => store.removeGroup(group.localId)}
|
||||
testId={`group-delete-${group.localId}`}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
<Switch
|
||||
value={group.enabled}
|
||||
onChange={(checked): void => store.toggleGroup(group.localId, checked)}
|
||||
testId={`group-enabled-${group.localId}`}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{isExpanded && (
|
||||
<TableRow className="groups-table__sub-row">
|
||||
<TableCell colSpan={COLUMN_COUNT}>
|
||||
<MappersTable group={group} store={store} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function MapperGroupsTable({
|
||||
store,
|
||||
onEditGroup,
|
||||
onAddGroup,
|
||||
}: MapperGroupsTableProps): JSX.Element {
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
|
||||
const toggleExpand = (localId: string): void => {
|
||||
setExpandedId((current) => (current === localId ? null : localId));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="groups-table__wrapper">
|
||||
<Table testId="mapper-groups-table" className="am-table">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Group name</TableHead>
|
||||
<TableHead>Filters</TableHead>
|
||||
<TableHead>Mappings</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{store.isLoading && store.groups.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={COLUMN_COUNT} className="am-table__empty">
|
||||
Loading groups…
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{!store.isLoading && store.groups.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={COLUMN_COUNT} className="am-table__empty">
|
||||
No mapping groups yet.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{store.groups.map((group) => (
|
||||
<GroupRow
|
||||
key={group.localId}
|
||||
group={group}
|
||||
store={store}
|
||||
isExpanded={expandedId === group.localId}
|
||||
onToggleExpand={toggleExpand}
|
||||
onEditGroup={onEditGroup}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="primary"
|
||||
prefix={<Plus size={14} />}
|
||||
className="am-add-row"
|
||||
onClick={onAddGroup}
|
||||
testId="add-group-row"
|
||||
>
|
||||
Add a new group
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default MapperGroupsTable;
|
||||
@@ -0,0 +1,208 @@
|
||||
import { useCallback } from 'react';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@signozhq/ui/table';
|
||||
import { Pencil, Plus, Trash2 } from '@signozhq/icons';
|
||||
|
||||
import IndexBadge from './IndexBadge';
|
||||
import MapperFormDrawer from './MapperFormDrawer';
|
||||
import { DraftGroup, DraftMapper, FieldContext } from './types';
|
||||
import { AttributeMappingStore } from './useAttributeMappingStore';
|
||||
import { useMapperFormDrawer } from './useMapperFormDrawer';
|
||||
|
||||
const MAX_VISIBLE_SOURCES = 3;
|
||||
const COLUMN_COUNT = 5;
|
||||
|
||||
interface MappersTableProps {
|
||||
group: DraftGroup;
|
||||
store: AttributeMappingStore;
|
||||
}
|
||||
|
||||
function SourcesCell({ mapper }: { mapper: DraftMapper }): JSX.Element {
|
||||
if (mapper.sources.length === 0) {
|
||||
return <span className="muted">—</span>;
|
||||
}
|
||||
|
||||
const visible = mapper.sources.slice(0, MAX_VISIBLE_SOURCES);
|
||||
const remaining = mapper.sources.length - visible.length;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="mappers-table__sources"
|
||||
data-testid={`mapper-sources-${mapper.localId}`}
|
||||
>
|
||||
{visible.map((source) => (
|
||||
<span
|
||||
className="mappers-table__source-chip"
|
||||
key={`${source.context}:${source.key}`}
|
||||
title={source.key}
|
||||
>
|
||||
{source.key}
|
||||
</span>
|
||||
))}
|
||||
{remaining > 0 && (
|
||||
<span className="mappers-table__source-more muted">+{remaining} more</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface MapperRowProps {
|
||||
mapper: DraftMapper;
|
||||
index: number;
|
||||
onEdit: (mapper: DraftMapper) => void;
|
||||
onDelete: (mapperLocalId: string) => void;
|
||||
onToggle: (mapperLocalId: string, enabled: boolean) => void;
|
||||
}
|
||||
|
||||
function MapperRow({
|
||||
mapper,
|
||||
index,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onToggle,
|
||||
}: MapperRowProps): JSX.Element {
|
||||
return (
|
||||
<TableRow data-testid={`mapper-row-${mapper.localId}`}>
|
||||
<TableCell>
|
||||
<IndexBadge index={index} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span
|
||||
className="mappers-table__target"
|
||||
data-testid={`mapper-target-${mapper.localId}`}
|
||||
>
|
||||
{mapper.name}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<SourcesCell mapper={mapper} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
color={mapper.fieldContext === FieldContext.resource ? 'amber' : 'robin'}
|
||||
variant="outline"
|
||||
>
|
||||
{mapper.fieldContext}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="am-row-actions">
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="icon"
|
||||
aria-label="Edit mapping"
|
||||
onClick={(): void => onEdit(mapper)}
|
||||
testId={`mapper-edit-${mapper.localId}`}
|
||||
>
|
||||
<Pencil size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="destructive"
|
||||
size="icon"
|
||||
aria-label="Delete mapping"
|
||||
onClick={(): void => onDelete(mapper.localId)}
|
||||
testId={`mapper-delete-${mapper.localId}`}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
<Switch
|
||||
value={mapper.enabled}
|
||||
onChange={(checked): void => onToggle(mapper.localId, checked)}
|
||||
testId={`mapper-enabled-${mapper.localId}`}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
|
||||
function MappersTable({ group, store }: MappersTableProps): JSX.Element {
|
||||
const drawer = useMapperFormDrawer();
|
||||
|
||||
const handleSave = useCallback((): void => {
|
||||
store.upsertMapper(group.localId, drawer.draft);
|
||||
drawer.close();
|
||||
}, [store, group.localId, drawer]);
|
||||
|
||||
const handleDelete = useCallback((): void => {
|
||||
if (drawer.draft.id) {
|
||||
store.removeMapper(group.localId, drawer.draft.id);
|
||||
}
|
||||
drawer.close();
|
||||
}, [store, group.localId, drawer]);
|
||||
|
||||
return (
|
||||
<div className="mappers-table__wrapper">
|
||||
<Table testId={`mappers-table-${group.localId}`} className="am-table">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>#</TableHead>
|
||||
<TableHead>Target</TableHead>
|
||||
<TableHead>Sources</TableHead>
|
||||
<TableHead>Writes to</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{group.mappers.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={COLUMN_COUNT} className="am-table__empty">
|
||||
No mappings in this group yet.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{group.mappers.map((mapper, index) => (
|
||||
<MapperRow
|
||||
key={mapper.localId}
|
||||
mapper={mapper}
|
||||
index={index}
|
||||
onEdit={drawer.openForEdit}
|
||||
onDelete={(localId): void => store.removeMapper(group.localId, localId)}
|
||||
onToggle={(localId, enabled): void =>
|
||||
store.toggleMapper(group.localId, localId, enabled)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="primary"
|
||||
size="sm"
|
||||
prefix={<Plus size={14} />}
|
||||
className="am-add-row"
|
||||
onClick={drawer.openForAdd}
|
||||
testId={`add-mapper-${group.localId}`}
|
||||
>
|
||||
Add mapping
|
||||
</Button>
|
||||
|
||||
<MapperFormDrawer
|
||||
isOpen={drawer.isOpen}
|
||||
mode={drawer.mode}
|
||||
draft={drawer.draft}
|
||||
setDraft={drawer.setDraft}
|
||||
onClose={drawer.close}
|
||||
onSave={handleSave}
|
||||
onDelete={handleDelete}
|
||||
isSaving={false}
|
||||
isDeleting={false}
|
||||
saveError={null}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default MappersTable;
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { SelectSimple } from '@signozhq/ui/select';
|
||||
import { useSortable } from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { GripVertical, X } from '@signozhq/icons';
|
||||
|
||||
import KeySearchInput from './KeySearchInput';
|
||||
import {
|
||||
FieldContext,
|
||||
FieldContextValue,
|
||||
MapperOperation,
|
||||
MapperOperationValue,
|
||||
SourceConfig,
|
||||
} from './types';
|
||||
|
||||
const CONTEXT_OPTIONS = [
|
||||
{ value: FieldContext.attribute, label: 'Attribute' },
|
||||
{ value: FieldContext.resource, label: 'Resource' },
|
||||
];
|
||||
|
||||
const OPERATION_OPTIONS = [
|
||||
{ value: MapperOperation.move, label: 'Move' },
|
||||
{ value: MapperOperation.copy, label: 'Copy' },
|
||||
];
|
||||
|
||||
interface SourceAttributeRowProps {
|
||||
id: string;
|
||||
index: number;
|
||||
value: SourceConfig;
|
||||
canRemove: boolean;
|
||||
onChange: (index: number, patch: Partial<SourceConfig>) => void;
|
||||
onRemove: (index: number) => void;
|
||||
}
|
||||
|
||||
// A single draggable source row. Order = priority (top wins). Each source can
|
||||
// be read from a span attribute or the resource, and moved (delete source) or
|
||||
// copied (keep source). Only the grip is a drag handle.
|
||||
function SourceAttributeRow({
|
||||
id,
|
||||
index,
|
||||
value,
|
||||
canRemove,
|
||||
onChange,
|
||||
onRemove,
|
||||
}: SourceAttributeRowProps): JSX.Element {
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.6 : 1,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mapper-form__source" ref={setNodeRef} style={style}>
|
||||
<div
|
||||
className="mapper-form__source-handle"
|
||||
data-testid={`mapper-form-source-handle-${index}`}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
>
|
||||
<GripVertical size={14} />
|
||||
</div>
|
||||
<span className="mapper-form__source-index">{index + 1}</span>
|
||||
<KeySearchInput
|
||||
className="mapper-form__source-input"
|
||||
placeholder="Source attribute key"
|
||||
value={value.key}
|
||||
fieldContext={value.context}
|
||||
onChange={(key): void => onChange(index, { key })}
|
||||
testId={`mapper-form-source-${index}`}
|
||||
/>
|
||||
<SelectSimple
|
||||
className="mapper-form__source-select"
|
||||
items={CONTEXT_OPTIONS}
|
||||
value={value.context}
|
||||
withPortal={false}
|
||||
onChange={(next): void =>
|
||||
onChange(index, { context: next as FieldContextValue })
|
||||
}
|
||||
testId={`mapper-form-source-context-${index}`}
|
||||
/>
|
||||
<SelectSimple
|
||||
className="mapper-form__source-select"
|
||||
items={OPERATION_OPTIONS}
|
||||
value={value.operation}
|
||||
withPortal={false}
|
||||
onChange={(next): void =>
|
||||
onChange(index, { operation: next as MapperOperationValue })
|
||||
}
|
||||
testId={`mapper-form-source-operation-${index}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="icon"
|
||||
aria-label="Remove source"
|
||||
disabled={!canRemove}
|
||||
onClick={(): void => onRemove(index)}
|
||||
testId={`mapper-form-source-remove-${index}`}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SourceAttributeRow;
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useState } from 'react';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
|
||||
import ConditionKeyList from '../ConditionKeyList';
|
||||
import { FieldContext } from '../types';
|
||||
|
||||
const FIELDS_ENDPOINT = '*/api/v1/fields/keys';
|
||||
|
||||
function Harness({ initial = [] as string[] }): JSX.Element {
|
||||
const [keys, setKeys] = useState<string[]>(initial);
|
||||
return (
|
||||
<ConditionKeyList
|
||||
label="Attributes"
|
||||
keys={keys}
|
||||
placeholder="key"
|
||||
addLabel="Add attribute key"
|
||||
testIdPrefix="cond"
|
||||
fieldContext={FieldContext.attribute}
|
||||
onChange={setKeys}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ConditionKeyList', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.get(FIELDS_ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success', data: { complete: true, keys: {} } }),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('renders no key rows and only the add button when empty', () => {
|
||||
render(<Harness />);
|
||||
expect(screen.queryByTestId('cond-0')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('cond-add')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('adds a key row when the add button is clicked', () => {
|
||||
render(<Harness />);
|
||||
fireEvent.click(screen.getByTestId('cond-add'));
|
||||
expect(screen.getByTestId('cond-0')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('removes a key row when its remove button is clicked', () => {
|
||||
render(<Harness initial={['gen_ai.', 'llm.']} />);
|
||||
|
||||
expect(screen.getByTestId('cond-0')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('cond-1')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByTestId('cond-remove-1'));
|
||||
|
||||
expect(screen.queryByTestId('cond-1')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('cond-0')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { fireEvent, render, screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import KeySearchInput from '../KeySearchInput';
|
||||
import { FieldContext } from '../types';
|
||||
|
||||
const FIELDS_ENDPOINT = '*/api/v1/fields/keys';
|
||||
|
||||
const mockKeysResponse = {
|
||||
status: 'success',
|
||||
data: {
|
||||
complete: true,
|
||||
keys: {
|
||||
'gen_ai.request.model': [
|
||||
{ name: 'gen_ai.request.model', fieldContext: 'attribute' },
|
||||
],
|
||||
'llm.model': [{ name: 'llm.model', fieldContext: 'attribute' }],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe('KeySearchInput', () => {
|
||||
let lastRequestParams: Record<string, string | null> = {};
|
||||
|
||||
beforeEach(() => {
|
||||
lastRequestParams = {};
|
||||
server.use(
|
||||
rest.get(FIELDS_ENDPOINT, (req, res, ctx) => {
|
||||
lastRequestParams = {
|
||||
signal: req.url.searchParams.get('signal'),
|
||||
fieldContext: req.url.searchParams.get('fieldContext'),
|
||||
searchText: req.url.searchParams.get('searchText'),
|
||||
};
|
||||
return res(ctx.status(200), ctx.json(mockKeysResponse));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('does not show suggestions until the input is focused', () => {
|
||||
render(
|
||||
<KeySearchInput
|
||||
value=""
|
||||
fieldContext={FieldContext.attribute}
|
||||
onChange={jest.fn()}
|
||||
testId="key"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByTestId('key-dropdown')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows suggestions on focus and selecting one calls onChange with the key', async () => {
|
||||
const onChange = jest.fn();
|
||||
render(
|
||||
<KeySearchInput
|
||||
value=""
|
||||
fieldContext={FieldContext.attribute}
|
||||
onChange={onChange}
|
||||
testId="key"
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.focus(screen.getByTestId('key'));
|
||||
|
||||
const option = await screen.findByTestId('key-option-gen_ai.request.model');
|
||||
fireEvent.mouseDown(option);
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('gen_ai.request.model');
|
||||
});
|
||||
|
||||
it('queries traces with the resource context when fieldContext is resource', async () => {
|
||||
render(
|
||||
<KeySearchInput
|
||||
value=""
|
||||
fieldContext={FieldContext.resource}
|
||||
onChange={jest.fn()}
|
||||
testId="key"
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.focus(screen.getByTestId('key'));
|
||||
|
||||
await waitFor(() => expect(lastRequestParams.fieldContext).toBe('resource'));
|
||||
expect(lastRequestParams.signal).toBe('traces');
|
||||
});
|
||||
|
||||
it('accepts free text typed by the user (custom key)', () => {
|
||||
const onChange = jest.fn();
|
||||
render(
|
||||
<KeySearchInput
|
||||
value=""
|
||||
fieldContext={FieldContext.attribute}
|
||||
onChange={onChange}
|
||||
testId="key"
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByTestId('key'), {
|
||||
target: { value: 'my.custom.key' },
|
||||
});
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('my.custom.key');
|
||||
});
|
||||
|
||||
it('does not query while disabled', () => {
|
||||
render(
|
||||
<KeySearchInput
|
||||
value=""
|
||||
fieldContext={FieldContext.attribute}
|
||||
disabled
|
||||
onChange={jest.fn()}
|
||||
testId="key"
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.focus(screen.getByTestId('key'));
|
||||
expect(screen.queryByTestId('key-dropdown')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { SpantypesSpanMapperGroupDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
|
||||
import LLMObservabilityAttributeMapping from '../LLMObservabilityAttributeMapping';
|
||||
|
||||
const GROUPS_ENDPOINT = '*/api/v1/span_mapper_groups';
|
||||
const MAPPERS_ENDPOINT = '*/api/v1/span_mapper_groups/:groupId/span_mappers';
|
||||
|
||||
const mockGroups: SpantypesSpanMapperGroupDTO[] = [
|
||||
{
|
||||
id: 'group-openai',
|
||||
orgId: 'org-1',
|
||||
name: 'OpenAI gateway',
|
||||
enabled: true,
|
||||
condition: { attributes: ['gen_ai.'], resource: [] },
|
||||
updatedBy: 'gaurav.tewari@signoz.io',
|
||||
updatedAt: '2026-06-10T09:30:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
describe('LLMObservabilityAttributeMapping', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.get(MAPPERS_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: { items: [] } })),
|
||||
),
|
||||
rest.get(GROUPS_ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success', data: { items: mockGroups } }),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('renders the page header and the group row', async () => {
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
|
||||
await screen.findByTestId('group-name-group-openai');
|
||||
expect(screen.getByText('Attribute Mapping')).toBeInTheDocument();
|
||||
expect(screen.getByText('OpenAI gateway')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the group drawer in Add mode with empty name', async () => {
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
|
||||
await screen.findByTestId('group-name-group-openai');
|
||||
fireEvent.click(screen.getByTestId('add-group-row'));
|
||||
|
||||
const input = (await screen.findByTestId(
|
||||
'group-form-name',
|
||||
)) as HTMLInputElement;
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('opens the group drawer in Edit mode prefilled with the group name', async () => {
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
|
||||
await screen.findByTestId('group-name-group-openai');
|
||||
fireEvent.click(screen.getByTestId('group-edit-group-openai'));
|
||||
|
||||
const input = (await screen.findByTestId(
|
||||
'group-form-name',
|
||||
)) as HTMLInputElement;
|
||||
expect(input.value).toBe('OpenAI gateway');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useState } from 'react';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
|
||||
import MapperFormDrawer from '../MapperFormDrawer';
|
||||
import {
|
||||
FieldContext,
|
||||
MapperDraft,
|
||||
MapperDraftMode,
|
||||
MapperOperation,
|
||||
} from '../types';
|
||||
import { EMPTY_MAPPER_DRAFT } from '../utils';
|
||||
|
||||
const FIELDS_ENDPOINT = '*/api/v1/fields/keys';
|
||||
|
||||
const filledDraft: MapperDraft = {
|
||||
id: null,
|
||||
name: 'gen_ai.request.model',
|
||||
fieldContext: FieldContext.attribute,
|
||||
sources: [
|
||||
{
|
||||
key: 'llm.model',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.move,
|
||||
},
|
||||
],
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
interface HarnessProps {
|
||||
initialDraft?: MapperDraft;
|
||||
mode?: MapperDraftMode;
|
||||
onSave?: () => void;
|
||||
onDelete?: () => void;
|
||||
}
|
||||
|
||||
function Harness({
|
||||
initialDraft = EMPTY_MAPPER_DRAFT,
|
||||
mode = 'add',
|
||||
onSave = jest.fn(),
|
||||
onDelete = jest.fn(),
|
||||
}: HarnessProps): JSX.Element {
|
||||
const [draft, setDraft] = useState<MapperDraft>(initialDraft);
|
||||
return (
|
||||
<MapperFormDrawer
|
||||
isOpen
|
||||
mode={mode}
|
||||
draft={draft}
|
||||
setDraft={setDraft}
|
||||
onClose={jest.fn()}
|
||||
onSave={onSave}
|
||||
onDelete={onDelete}
|
||||
isSaving={false}
|
||||
isDeleting={false}
|
||||
saveError={null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('MapperFormDrawer', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.get(FIELDS_ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success', data: { complete: true, keys: {} } }),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('disables Create when the target/sources are empty', () => {
|
||||
render(<Harness />);
|
||||
expect(screen.getByTestId('mapper-form-save')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables Create with a target and a source key, and calls onSave', () => {
|
||||
const onSave = jest.fn();
|
||||
render(<Harness initialDraft={filledDraft} onSave={onSave} />);
|
||||
|
||||
const save = screen.getByTestId('mapper-form-save');
|
||||
expect(save).not.toBeDisabled();
|
||||
|
||||
fireEvent.click(save);
|
||||
expect(onSave).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('adds a source row when "Add another source" is clicked', () => {
|
||||
render(<Harness initialDraft={filledDraft} />);
|
||||
|
||||
expect(screen.queryByTestId('mapper-form-source-1')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByTestId('mapper-form-add-source'));
|
||||
expect(screen.getByTestId('mapper-form-source-1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('makes the target read-only in edit mode and shows delete', () => {
|
||||
const onDelete = jest.fn();
|
||||
render(
|
||||
<Harness
|
||||
initialDraft={{ ...filledDraft, id: 'local-mapper-1' }}
|
||||
mode="edit"
|
||||
onDelete={onDelete}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('mapper-form-target')).toBeDisabled();
|
||||
|
||||
fireEvent.click(screen.getByTestId('mapper-form-delete'));
|
||||
expect(onDelete).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { persistDraft, SaveMutations } from '../saveDraft';
|
||||
import {
|
||||
DraftGroup,
|
||||
DraftMapper,
|
||||
FieldContext,
|
||||
MapperOperation,
|
||||
} from '../types';
|
||||
|
||||
function mapper(over: Partial<DraftMapper>): DraftMapper {
|
||||
return {
|
||||
localId: 'm',
|
||||
serverId: 'm',
|
||||
name: 'm',
|
||||
fieldContext: FieldContext.attribute,
|
||||
sources: [
|
||||
{
|
||||
key: 'x',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.move,
|
||||
},
|
||||
],
|
||||
enabled: true,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function group(over: Partial<DraftGroup>): DraftGroup {
|
||||
return {
|
||||
localId: 'g',
|
||||
serverId: 'g',
|
||||
name: 'g',
|
||||
attributes: [],
|
||||
resource: [],
|
||||
enabled: true,
|
||||
mappers: [],
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
interface RecordedCalls {
|
||||
createGroup: unknown[];
|
||||
updateGroup: [string, unknown][];
|
||||
deleteGroup: string[];
|
||||
createMapper: [string, unknown][];
|
||||
updateMapper: [string, string, unknown][];
|
||||
deleteMapper: [string, string][];
|
||||
}
|
||||
|
||||
function makeMutations(): { calls: RecordedCalls; mutations: SaveMutations } {
|
||||
const calls: RecordedCalls = {
|
||||
createGroup: [],
|
||||
updateGroup: [],
|
||||
deleteGroup: [],
|
||||
createMapper: [],
|
||||
updateMapper: [],
|
||||
deleteMapper: [],
|
||||
};
|
||||
const mutations: SaveMutations = {
|
||||
createGroup: async (data): Promise<string> => {
|
||||
calls.createGroup.push(data);
|
||||
return 'new-group-id';
|
||||
},
|
||||
updateGroup: async (id, data): Promise<void> => {
|
||||
calls.updateGroup.push([id, data]);
|
||||
},
|
||||
deleteGroup: async (id): Promise<void> => {
|
||||
calls.deleteGroup.push(id);
|
||||
},
|
||||
createMapper: async (gid, data): Promise<void> => {
|
||||
calls.createMapper.push([gid, data]);
|
||||
},
|
||||
updateMapper: async (gid, mid, data): Promise<void> => {
|
||||
calls.updateMapper.push([gid, mid, data]);
|
||||
},
|
||||
deleteMapper: async (gid, mid): Promise<void> => {
|
||||
calls.deleteMapper.push([gid, mid]);
|
||||
},
|
||||
};
|
||||
return { calls, mutations };
|
||||
}
|
||||
|
||||
describe('persistDraft', () => {
|
||||
it('issues the minimal set of create/update/delete calls', async () => {
|
||||
const snapshot: DraftGroup[] = [
|
||||
group({
|
||||
localId: 'g1',
|
||||
serverId: 'g1',
|
||||
name: 'G1',
|
||||
mappers: [
|
||||
mapper({ localId: 'm1', serverId: 'm1', name: 'keep' }),
|
||||
mapper({ localId: 'mdel', serverId: 'mdel', name: 'del' }),
|
||||
],
|
||||
}),
|
||||
group({ localId: 'g2', serverId: 'g2', name: 'G2' }),
|
||||
];
|
||||
|
||||
const draft: DraftGroup[] = [
|
||||
group({
|
||||
localId: 'g1',
|
||||
serverId: 'g1',
|
||||
name: 'G1-renamed', // changed -> update
|
||||
mappers: [
|
||||
mapper({ localId: 'm1', serverId: 'm1', name: 'keep' }), // unchanged
|
||||
mapper({ localId: 'local-mapper-x', serverId: null, name: 'fresh' }), // new
|
||||
],
|
||||
}),
|
||||
// g2 removed -> delete
|
||||
group({
|
||||
localId: 'local-group-y',
|
||||
serverId: null,
|
||||
name: 'G3',
|
||||
mappers: [
|
||||
mapper({ localId: 'local-mapper-z', serverId: null, name: 'g3map' }),
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const { calls, mutations } = makeMutations();
|
||||
await persistDraft(snapshot, draft, mutations);
|
||||
|
||||
expect(calls.deleteGroup).toStrictEqual(['g2']);
|
||||
expect(calls.updateGroup.map(([id]) => id)).toStrictEqual(['g1']);
|
||||
expect(calls.deleteMapper).toStrictEqual([['g1', 'mdel']]);
|
||||
// no-op mapper is not updated
|
||||
expect(calls.updateMapper).toStrictEqual([]);
|
||||
// new group created once, then its mapper created under the returned id
|
||||
expect(calls.createGroup).toHaveLength(1);
|
||||
const createMapperGroupIds = calls.createMapper.map(([gid]) => gid).sort();
|
||||
expect(createMapperGroupIds).toStrictEqual(['g1', 'new-group-id']);
|
||||
});
|
||||
|
||||
it('does nothing when the draft equals the snapshot', async () => {
|
||||
const snapshot: DraftGroup[] = [group({ localId: 'g1', serverId: 'g1' })];
|
||||
const draft: DraftGroup[] = [group({ localId: 'g1', serverId: 'g1' })];
|
||||
|
||||
const { calls, mutations } = makeMutations();
|
||||
await persistDraft(snapshot, draft, mutations);
|
||||
|
||||
expect(calls.createGroup).toHaveLength(0);
|
||||
expect(calls.updateGroup).toHaveLength(0);
|
||||
expect(calls.deleteGroup).toHaveLength(0);
|
||||
expect(calls.createMapper).toHaveLength(0);
|
||||
expect(calls.updateMapper).toHaveLength(0);
|
||||
expect(calls.deleteMapper).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,330 @@
|
||||
import {
|
||||
DraftGroup,
|
||||
FieldContext,
|
||||
Mapper,
|
||||
MapperDraft,
|
||||
MapperGroup,
|
||||
MapperOperation,
|
||||
SourceConfig,
|
||||
} from '../types';
|
||||
import {
|
||||
buildDraftGroup,
|
||||
buildDraftMapper,
|
||||
buildPostableGroup,
|
||||
buildPostableMapper,
|
||||
buildUpdatableMapper,
|
||||
cleanKeys,
|
||||
conditionFiltersFromGroup,
|
||||
EMPTY_GROUP_DRAFT,
|
||||
EMPTY_MAPPER_DRAFT,
|
||||
formatTimestamp,
|
||||
getMapperSources,
|
||||
groupDraftFromNode,
|
||||
isGroupDraftValid,
|
||||
isMapperDraftValid,
|
||||
mapperDraftFromNode,
|
||||
nodeFromGroupDraft,
|
||||
nodeFromMapperDraft,
|
||||
} from '../utils';
|
||||
|
||||
function src(
|
||||
key: string,
|
||||
operation = MapperOperation.copy,
|
||||
context = FieldContext.attribute,
|
||||
): SourceConfig {
|
||||
return { key, context, operation };
|
||||
}
|
||||
|
||||
function mapperDraft(over: Partial<MapperDraft>): MapperDraft {
|
||||
return {
|
||||
id: null,
|
||||
name: 'target',
|
||||
fieldContext: FieldContext.attribute,
|
||||
sources: [src('a')],
|
||||
enabled: true,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
const mapper: Mapper = {
|
||||
id: 'm1',
|
||||
group_id: 'g1',
|
||||
name: 'gen_ai.request.model',
|
||||
enabled: true,
|
||||
fieldContext: FieldContext.attribute,
|
||||
config: {
|
||||
sources: [
|
||||
{
|
||||
key: 'low',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.copy,
|
||||
priority: 1,
|
||||
},
|
||||
{
|
||||
key: 'high',
|
||||
context: FieldContext.resource,
|
||||
operation: MapperOperation.move,
|
||||
priority: 3,
|
||||
},
|
||||
{
|
||||
key: 'mid',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.copy,
|
||||
priority: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const group: MapperGroup = {
|
||||
id: 'g1',
|
||||
orgId: 'org1',
|
||||
name: 'OpenAI',
|
||||
enabled: true,
|
||||
condition: { attributes: ['gen_ai.', 'llm.'], resource: [] },
|
||||
};
|
||||
|
||||
describe('attribute-mapping utils', () => {
|
||||
describe('cleanKeys', () => {
|
||||
it('trims, drops empties, and de-duplicates preserving order', () => {
|
||||
expect(cleanKeys([' a ', '', 'b', 'a', ' '])).toStrictEqual(['a', 'b']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMapperSources', () => {
|
||||
it('returns sources sorted by priority descending, preserving context/operation', () => {
|
||||
expect(getMapperSources(mapper)).toStrictEqual([
|
||||
{
|
||||
key: 'high',
|
||||
context: FieldContext.resource,
|
||||
operation: MapperOperation.move,
|
||||
},
|
||||
{
|
||||
key: 'mid',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.copy,
|
||||
},
|
||||
{
|
||||
key: 'low',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.copy,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns empty array when there are no sources', () => {
|
||||
expect(
|
||||
getMapperSources({ ...mapper, config: { sources: null } }),
|
||||
).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('conditionFiltersFromGroup', () => {
|
||||
it('lists attribute clauses first, then resource clauses', () => {
|
||||
expect(
|
||||
conditionFiltersFromGroup({
|
||||
attributes: ['gen_ai.', 'llm.'],
|
||||
resource: ['service.name'],
|
||||
}),
|
||||
).toStrictEqual([
|
||||
{ context: 'attribute', key: 'gen_ai.' },
|
||||
{ context: 'attribute', key: 'llm.' },
|
||||
{ context: 'resource', key: 'service.name' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatTimestamp', () => {
|
||||
it('renders a dash for missing timestamps', () => {
|
||||
expect(formatTimestamp(undefined)).toBe('—');
|
||||
});
|
||||
});
|
||||
|
||||
describe('draft-tree builders', () => {
|
||||
it('builds a draft mapper node carrying server id, fieldContext and sources', () => {
|
||||
expect(buildDraftMapper(mapper)).toStrictEqual({
|
||||
localId: 'm1',
|
||||
serverId: 'm1',
|
||||
name: 'gen_ai.request.model',
|
||||
fieldContext: FieldContext.attribute,
|
||||
sources: [
|
||||
{
|
||||
key: 'high',
|
||||
context: FieldContext.resource,
|
||||
operation: MapperOperation.move,
|
||||
},
|
||||
{
|
||||
key: 'mid',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.copy,
|
||||
},
|
||||
{
|
||||
key: 'low',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.copy,
|
||||
},
|
||||
],
|
||||
enabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('builds a draft group node with nested mappers', () => {
|
||||
const node = buildDraftGroup(group, [mapper]);
|
||||
expect(node.localId).toBe('g1');
|
||||
expect(node.attributes).toStrictEqual(['gen_ai.', 'llm.']);
|
||||
expect(node.mappers).toHaveLength(1);
|
||||
expect(node.mappers[0].localId).toBe('m1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('node <-> form conversions', () => {
|
||||
const node: DraftGroup = {
|
||||
localId: 'g1',
|
||||
serverId: 'g1',
|
||||
name: 'OpenAI',
|
||||
attributes: ['gen_ai.'],
|
||||
resource: ['service.name'],
|
||||
enabled: true,
|
||||
mappers: [],
|
||||
};
|
||||
|
||||
it('builds a form draft from a group node', () => {
|
||||
expect(groupDraftFromNode(node)).toStrictEqual({
|
||||
id: 'g1',
|
||||
name: 'OpenAI',
|
||||
attributes: ['gen_ai.'],
|
||||
resource: ['service.name'],
|
||||
enabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('updates an existing group node, preserving its ids and mappers', () => {
|
||||
const existing = { ...node, mappers: [buildDraftMapper(mapper)] };
|
||||
const updated = nodeFromGroupDraft(
|
||||
{
|
||||
id: 'g1',
|
||||
name: ' Renamed ',
|
||||
attributes: ['a', '', 'a'],
|
||||
resource: ['service.name', ''],
|
||||
enabled: false,
|
||||
},
|
||||
existing,
|
||||
);
|
||||
expect(updated.serverId).toBe('g1');
|
||||
expect(updated.name).toBe('Renamed');
|
||||
expect(updated.attributes).toStrictEqual(['a']);
|
||||
expect(updated.resource).toStrictEqual(['service.name']);
|
||||
expect(updated.mappers).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('round-trips a mapper node through the form and de-dups sources by key', () => {
|
||||
const draft = mapperDraftFromNode(buildDraftMapper(mapper));
|
||||
expect(draft.id).toBe('m1');
|
||||
expect(draft.fieldContext).toBe(FieldContext.attribute);
|
||||
|
||||
const created = nodeFromMapperDraft(
|
||||
mapperDraft({
|
||||
id: null,
|
||||
sources: [src('a', MapperOperation.move), src(' '), src('a'), src('b')],
|
||||
}),
|
||||
);
|
||||
expect(created.serverId).toBeNull();
|
||||
expect(created.localId).toMatch(/^local-mapper-/);
|
||||
expect(created.sources).toStrictEqual([
|
||||
{
|
||||
key: 'a',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.move,
|
||||
},
|
||||
{
|
||||
key: 'b',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.copy,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validation', () => {
|
||||
it('validates a mapper draft (name + at least one keyed source)', () => {
|
||||
expect(isMapperDraftValid(EMPTY_MAPPER_DRAFT)).toBe(false);
|
||||
expect(
|
||||
isMapperDraftValid(mapperDraft({ name: 'x', sources: [src(' ')] })),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isMapperDraftValid(mapperDraft({ name: 'x', sources: [src('a')] })),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('validates a group draft (name only)', () => {
|
||||
expect(isGroupDraftValid(EMPTY_GROUP_DRAFT)).toBe(false);
|
||||
expect(
|
||||
isGroupDraftValid({
|
||||
id: null,
|
||||
name: 'g',
|
||||
attributes: [],
|
||||
resource: [],
|
||||
enabled: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('API payload builders', () => {
|
||||
it('derives descending priorities and carries per-source context/operation', () => {
|
||||
const payload = buildPostableMapper(
|
||||
mapperDraft({
|
||||
name: ' target ',
|
||||
fieldContext: FieldContext.resource,
|
||||
sources: [
|
||||
src('a', MapperOperation.move),
|
||||
src('b', MapperOperation.copy, FieldContext.resource),
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(payload.name).toBe('target');
|
||||
expect(payload.fieldContext).toBe(FieldContext.resource);
|
||||
expect(payload.config.sources).toStrictEqual([
|
||||
{
|
||||
key: 'a',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.move,
|
||||
priority: 2,
|
||||
},
|
||||
{
|
||||
key: 'b',
|
||||
context: FieldContext.resource,
|
||||
operation: MapperOperation.copy,
|
||||
priority: 1,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('omits name on the mapper update payload (immutable target)', () => {
|
||||
const payload = buildUpdatableMapper(
|
||||
mapperDraft({
|
||||
id: 'm1',
|
||||
enabled: false,
|
||||
fieldContext: FieldContext.resource,
|
||||
}),
|
||||
);
|
||||
expect(payload).not.toHaveProperty('name');
|
||||
expect(payload.enabled).toBe(false);
|
||||
expect(payload.fieldContext).toBe(FieldContext.resource);
|
||||
});
|
||||
|
||||
it('cleans both attribute and resource condition keys', () => {
|
||||
const payload = buildPostableGroup({
|
||||
id: null,
|
||||
name: 'g',
|
||||
attributes: ['gen_ai.', '', 'gen_ai.'],
|
||||
resource: ['service.name', ' ', 'service.name'],
|
||||
enabled: true,
|
||||
});
|
||||
expect(payload.condition).toStrictEqual({
|
||||
attributes: ['gen_ai.'],
|
||||
resource: ['service.name'],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import {
|
||||
SpantypesPostableSpanMapperDTO,
|
||||
SpantypesPostableSpanMapperGroupDTO,
|
||||
SpantypesUpdatableSpanMapperDTO,
|
||||
SpantypesUpdatableSpanMapperGroupDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { DraftGroup, DraftMapper, SourceConfig } from './types';
|
||||
import {
|
||||
buildPostableGroup,
|
||||
buildPostableMapper,
|
||||
buildUpdatableGroup,
|
||||
buildUpdatableMapper,
|
||||
} from './utils';
|
||||
|
||||
// Thin persistence surface the store wires to the generated mutations.
|
||||
// createGroup returns the new server id so its mappers can be created under it.
|
||||
export interface SaveMutations {
|
||||
createGroup: (data: SpantypesPostableSpanMapperGroupDTO) => Promise<string>;
|
||||
updateGroup: (
|
||||
groupId: string,
|
||||
data: SpantypesUpdatableSpanMapperGroupDTO,
|
||||
) => Promise<void>;
|
||||
deleteGroup: (groupId: string) => Promise<void>;
|
||||
createMapper: (
|
||||
groupId: string,
|
||||
data: SpantypesPostableSpanMapperDTO,
|
||||
) => Promise<void>;
|
||||
updateMapper: (
|
||||
groupId: string,
|
||||
mapperId: string,
|
||||
data: SpantypesUpdatableSpanMapperDTO,
|
||||
) => Promise<void>;
|
||||
deleteMapper: (groupId: string, mapperId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
function arraysEqual(a: string[], b: string[]): boolean {
|
||||
return a.length === b.length && a.every((value, index) => value === b[index]);
|
||||
}
|
||||
|
||||
function sourcesEqual(a: SourceConfig[], b: SourceConfig[]): boolean {
|
||||
return (
|
||||
a.length === b.length &&
|
||||
a.every(
|
||||
(source, index) =>
|
||||
source.key === b[index].key &&
|
||||
source.context === b[index].context &&
|
||||
source.operation === b[index].operation,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function groupChanged(snapshot: DraftGroup, draft: DraftGroup): boolean {
|
||||
return (
|
||||
snapshot.name !== draft.name ||
|
||||
snapshot.enabled !== draft.enabled ||
|
||||
!arraysEqual(snapshot.attributes, draft.attributes) ||
|
||||
!arraysEqual(snapshot.resource, draft.resource)
|
||||
);
|
||||
}
|
||||
|
||||
function mapperChanged(snapshot: DraftMapper, draft: DraftMapper): boolean {
|
||||
return (
|
||||
snapshot.enabled !== draft.enabled ||
|
||||
snapshot.fieldContext !== draft.fieldContext ||
|
||||
!sourcesEqual(snapshot.sources, draft.sources)
|
||||
);
|
||||
}
|
||||
|
||||
function groupDraftOf(
|
||||
node: DraftGroup,
|
||||
): Parameters<typeof buildPostableGroup>[0] {
|
||||
return {
|
||||
id: node.serverId,
|
||||
name: node.name,
|
||||
attributes: node.attributes,
|
||||
resource: node.resource,
|
||||
enabled: node.enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function mapperDraftOf(
|
||||
node: DraftMapper,
|
||||
): Parameters<typeof buildPostableMapper>[0] {
|
||||
return {
|
||||
id: node.serverId,
|
||||
name: node.name,
|
||||
fieldContext: node.fieldContext,
|
||||
sources: node.sources,
|
||||
enabled: node.enabled,
|
||||
};
|
||||
}
|
||||
|
||||
async function persistMappers(
|
||||
groupServerId: string,
|
||||
snapshotMappers: DraftMapper[],
|
||||
draftMappers: DraftMapper[],
|
||||
m: SaveMutations,
|
||||
): Promise<void> {
|
||||
const snapById = new Map(
|
||||
snapshotMappers
|
||||
.filter((mapper) => mapper.serverId)
|
||||
.map((mapper) => [mapper.serverId as string, mapper]),
|
||||
);
|
||||
const draftServerIds = new Set(
|
||||
draftMappers
|
||||
.filter((mapper) => mapper.serverId)
|
||||
.map((mapper) => mapper.serverId as string),
|
||||
);
|
||||
|
||||
// Deleted mappers.
|
||||
await Promise.all(
|
||||
snapshotMappers
|
||||
.filter((mapper) => mapper.serverId && !draftServerIds.has(mapper.serverId))
|
||||
.map((mapper) => m.deleteMapper(groupServerId, mapper.serverId as string)),
|
||||
);
|
||||
|
||||
// Created + updated mappers (sequential to keep ordering deterministic).
|
||||
for (const mapper of draftMappers) {
|
||||
if (!mapper.serverId) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await m.createMapper(
|
||||
groupServerId,
|
||||
buildPostableMapper(mapperDraftOf(mapper)),
|
||||
);
|
||||
} else {
|
||||
const snap = snapById.get(mapper.serverId);
|
||||
if (!snap || mapperChanged(snap, mapper)) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await m.updateMapper(
|
||||
groupServerId,
|
||||
mapper.serverId,
|
||||
buildUpdatableMapper(mapperDraftOf(mapper)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Diffs the staged tree against the server snapshot and issues the minimal set
|
||||
// of create/update/delete calls to reconcile them.
|
||||
export async function persistDraft(
|
||||
snapshot: DraftGroup[],
|
||||
draft: DraftGroup[],
|
||||
m: SaveMutations,
|
||||
): Promise<void> {
|
||||
const snapById = new Map(
|
||||
snapshot
|
||||
.filter((group) => group.serverId)
|
||||
.map((group) => [group.serverId as string, group]),
|
||||
);
|
||||
const draftServerIds = new Set(
|
||||
draft
|
||||
.filter((group) => group.serverId)
|
||||
.map((group) => group.serverId as string),
|
||||
);
|
||||
|
||||
// Deleted groups (cascades mappers server-side).
|
||||
await Promise.all(
|
||||
snapshot
|
||||
.filter((group) => group.serverId && !draftServerIds.has(group.serverId))
|
||||
.map((group) => m.deleteGroup(group.serverId as string)),
|
||||
);
|
||||
|
||||
for (const group of draft) {
|
||||
if (!group.serverId) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const newId = await m.createGroup(buildPostableGroup(groupDraftOf(group)));
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await persistMappers(newId, [], group.mappers, m);
|
||||
continue;
|
||||
}
|
||||
|
||||
const snap = snapById.get(group.serverId);
|
||||
if (!snap || groupChanged(snap, group)) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await m.updateGroup(
|
||||
group.serverId,
|
||||
buildUpdatableGroup(groupDraftOf(group)),
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await persistMappers(group.serverId, snap?.mappers ?? [], group.mappers, m);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
SpantypesFieldContextDTO,
|
||||
SpantypesSpanMapperConfigDTO,
|
||||
SpantypesSpanMapperDTO,
|
||||
SpantypesSpanMapperGroupConditionDTO,
|
||||
SpantypesSpanMapperGroupDTO,
|
||||
SpantypesSpanMapperOperationDTO,
|
||||
SpantypesSpanMapperSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export type MapperGroup = SpantypesSpanMapperGroupDTO;
|
||||
export type MapperGroupCondition =
|
||||
NonNullable<SpantypesSpanMapperGroupConditionDTO>;
|
||||
export type Mapper = SpantypesSpanMapperDTO;
|
||||
export type MapperConfig = SpantypesSpanMapperConfigDTO;
|
||||
export type MapperSource = SpantypesSpanMapperSourceDTO;
|
||||
|
||||
export const FieldContext = SpantypesFieldContextDTO;
|
||||
export const MapperOperation = SpantypesSpanMapperOperationDTO;
|
||||
|
||||
export type FieldContextValue = SpantypesFieldContextDTO;
|
||||
export type MapperOperationValue = SpantypesSpanMapperOperationDTO;
|
||||
|
||||
// A single human-readable condition clause shown in the group's Filters column.
|
||||
export interface ConditionFilter {
|
||||
context: 'attribute' | 'resource';
|
||||
key: string;
|
||||
}
|
||||
|
||||
export type MapperDraftMode = 'add' | 'edit';
|
||||
|
||||
// One source candidate. `context` is where the key is read from (span
|
||||
// attribute or resource); `operation` is move (delete source) or copy (keep).
|
||||
// Priority is implicit in list order (top wins), derived on save.
|
||||
export interface SourceConfig {
|
||||
key: string;
|
||||
context: SpantypesFieldContextDTO;
|
||||
operation: SpantypesSpanMapperOperationDTO;
|
||||
}
|
||||
|
||||
// Editable form state for a mapper. `sources` is ordered highest priority
|
||||
// first; `fieldContext` is where the standardized target is written.
|
||||
export interface MapperDraft {
|
||||
id: string | null;
|
||||
name: string;
|
||||
fieldContext: SpantypesFieldContextDTO;
|
||||
sources: SourceConfig[];
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
// Editable form state for a group. The group runs when a span carries a
|
||||
// span-attribute key matching `attributes` OR a resource key matching
|
||||
// `resource` (plain substring match).
|
||||
export interface GroupDraft {
|
||||
id: string | null;
|
||||
name: string;
|
||||
attributes: string[];
|
||||
resource: string[];
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
// Working-copy node for a mapper. `localId` is a stable client key (the server
|
||||
// id once persisted, or a temporary id for not-yet-saved rows). `serverId` is
|
||||
// null until the row has been persisted.
|
||||
export interface DraftMapper {
|
||||
localId: string;
|
||||
serverId: string | null;
|
||||
name: string;
|
||||
fieldContext: SpantypesFieldContextDTO;
|
||||
sources: SourceConfig[];
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
// Working-copy node for a group, holding its mappers inline so the whole tree
|
||||
// can be staged locally and diffed against the server snapshot on save.
|
||||
export interface DraftGroup {
|
||||
localId: string;
|
||||
serverId: string | null;
|
||||
name: string;
|
||||
attributes: string[];
|
||||
resource: string[];
|
||||
enabled: boolean;
|
||||
mappers: DraftMapper[];
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { useQueries, useQueryClient } from 'react-query';
|
||||
import {
|
||||
getListSpanMappersQueryOptions,
|
||||
useCreateSpanMapper,
|
||||
useCreateSpanMapperGroup,
|
||||
useDeleteSpanMapper,
|
||||
useDeleteSpanMapperGroup,
|
||||
useListSpanMapperGroups,
|
||||
useUpdateSpanMapper,
|
||||
useUpdateSpanMapperGroup,
|
||||
} from 'api/generated/services/spanmapper';
|
||||
|
||||
import { persistDraft, SaveMutations } from './saveDraft';
|
||||
import {
|
||||
DraftGroup,
|
||||
GroupDraft,
|
||||
Mapper,
|
||||
MapperDraft,
|
||||
MapperGroup,
|
||||
} from './types';
|
||||
import {
|
||||
buildDraftGroup,
|
||||
nodeFromGroupDraft,
|
||||
nodeFromMapperDraft,
|
||||
} from './utils';
|
||||
|
||||
const GROUPS_KEY_PREFIX = '/api/v1/span_mapper_groups';
|
||||
|
||||
function clone(groups: DraftGroup[]): DraftGroup[] {
|
||||
return JSON.parse(JSON.stringify(groups)) as DraftGroup[];
|
||||
}
|
||||
|
||||
export interface AttributeMappingStore {
|
||||
groups: DraftGroup[];
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
isDirty: boolean;
|
||||
isSaving: boolean;
|
||||
saveError: string | null;
|
||||
upsertGroup: (draft: GroupDraft) => void;
|
||||
removeGroup: (localId: string) => void;
|
||||
toggleGroup: (localId: string, enabled: boolean) => void;
|
||||
upsertMapper: (groupLocalId: string, draft: MapperDraft) => void;
|
||||
removeMapper: (groupLocalId: string, mapperLocalId: string) => void;
|
||||
toggleMapper: (
|
||||
groupLocalId: string,
|
||||
mapperLocalId: string,
|
||||
enabled: boolean,
|
||||
) => void;
|
||||
save: () => Promise<void>;
|
||||
discard: () => void;
|
||||
}
|
||||
|
||||
export function useAttributeMappingStore(): AttributeMappingStore {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const groupsQuery = useListSpanMapperGroups();
|
||||
const serverGroups: MapperGroup[] = useMemo(
|
||||
() => groupsQuery.data?.data?.items ?? [],
|
||||
[groupsQuery.data],
|
||||
);
|
||||
|
||||
const mapperQueries = useQueries(
|
||||
serverGroups.map((group) =>
|
||||
getListSpanMappersQueryOptions({ groupId: group.id }),
|
||||
),
|
||||
);
|
||||
|
||||
const mappersReady = mapperQueries.every((query) => !query.isLoading);
|
||||
const ready = !groupsQuery.isLoading && mappersReady;
|
||||
|
||||
// Stable signature so the snapshot only rebuilds when server data changes.
|
||||
const dataSignature = useMemo(
|
||||
() =>
|
||||
JSON.stringify(serverGroups) +
|
||||
JSON.stringify(mapperQueries.map((query) => query.data?.data?.items ?? [])),
|
||||
[serverGroups, mapperQueries],
|
||||
);
|
||||
|
||||
const snapshot = useMemo<DraftGroup[]>(() => {
|
||||
if (!ready) {
|
||||
return [];
|
||||
}
|
||||
return serverGroups.map((group, index) =>
|
||||
buildDraftGroup(
|
||||
group,
|
||||
(mapperQueries[index]?.data?.data?.items ?? []) as unknown as Mapper[],
|
||||
),
|
||||
);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [ready, dataSignature]);
|
||||
|
||||
const [draft, setDraft] = useState<DraftGroup[] | null>(null);
|
||||
|
||||
// Initialise the working copy once data is ready (and re-init after a save
|
||||
// clears it). Never clobbers in-flight edits — only runs when draft is null.
|
||||
useEffect(() => {
|
||||
if (ready && draft === null) {
|
||||
setDraft(clone(snapshot));
|
||||
}
|
||||
}, [ready, draft, snapshot]);
|
||||
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
|
||||
const { mutateAsync: createGroup } = useCreateSpanMapperGroup();
|
||||
const { mutateAsync: updateGroup } = useUpdateSpanMapperGroup();
|
||||
const { mutateAsync: deleteGroup } = useDeleteSpanMapperGroup();
|
||||
const { mutateAsync: createMapper } = useCreateSpanMapper();
|
||||
const { mutateAsync: updateMapper } = useUpdateSpanMapper();
|
||||
const { mutateAsync: deleteMapper } = useDeleteSpanMapper();
|
||||
|
||||
const mutations: SaveMutations = useMemo(
|
||||
() => ({
|
||||
createGroup: async (data): Promise<string> => {
|
||||
const result = await createGroup({ data });
|
||||
return result.data.id;
|
||||
},
|
||||
updateGroup: async (groupId, data): Promise<void> => {
|
||||
await updateGroup({ pathParams: { groupId }, data });
|
||||
},
|
||||
deleteGroup: async (groupId): Promise<void> => {
|
||||
await deleteGroup({ pathParams: { groupId } });
|
||||
},
|
||||
createMapper: async (groupId, data): Promise<void> => {
|
||||
await createMapper({ pathParams: { groupId }, data });
|
||||
},
|
||||
updateMapper: async (groupId, mapperId, data): Promise<void> => {
|
||||
await updateMapper({ pathParams: { groupId, mapperId }, data });
|
||||
},
|
||||
deleteMapper: async (groupId, mapperId): Promise<void> => {
|
||||
await deleteMapper({ pathParams: { groupId, mapperId } });
|
||||
},
|
||||
}),
|
||||
[
|
||||
createGroup,
|
||||
updateGroup,
|
||||
deleteGroup,
|
||||
createMapper,
|
||||
updateMapper,
|
||||
deleteMapper,
|
||||
],
|
||||
);
|
||||
|
||||
const upsertGroup = useCallback((groupDraft: GroupDraft): void => {
|
||||
setDraft((prev) => {
|
||||
const groups = prev ?? [];
|
||||
if (groupDraft.id) {
|
||||
return groups.map((group) =>
|
||||
group.localId === groupDraft.id
|
||||
? nodeFromGroupDraft(groupDraft, group)
|
||||
: group,
|
||||
);
|
||||
}
|
||||
return [...groups, nodeFromGroupDraft(groupDraft)];
|
||||
});
|
||||
}, []);
|
||||
|
||||
const removeGroup = useCallback((localId: string): void => {
|
||||
setDraft((prev) => (prev ?? []).filter((group) => group.localId !== localId));
|
||||
}, []);
|
||||
|
||||
const toggleGroup = useCallback((localId: string, enabled: boolean): void => {
|
||||
setDraft((prev) =>
|
||||
(prev ?? []).map((group) =>
|
||||
group.localId === localId ? { ...group, enabled } : group,
|
||||
),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const upsertMapper = useCallback(
|
||||
(groupLocalId: string, mapperDraft: MapperDraft): void => {
|
||||
setDraft((prev) =>
|
||||
(prev ?? []).map((group) => {
|
||||
if (group.localId !== groupLocalId) {
|
||||
return group;
|
||||
}
|
||||
if (mapperDraft.id) {
|
||||
return {
|
||||
...group,
|
||||
mappers: group.mappers.map((mapper) =>
|
||||
mapper.localId === mapperDraft.id
|
||||
? nodeFromMapperDraft(mapperDraft, mapper)
|
||||
: mapper,
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
...group,
|
||||
mappers: [...group.mappers, nodeFromMapperDraft(mapperDraft)],
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const removeMapper = useCallback(
|
||||
(groupLocalId: string, mapperLocalId: string): void => {
|
||||
setDraft((prev) =>
|
||||
(prev ?? []).map((group) =>
|
||||
group.localId === groupLocalId
|
||||
? {
|
||||
...group,
|
||||
mappers: group.mappers.filter(
|
||||
(mapper) => mapper.localId !== mapperLocalId,
|
||||
),
|
||||
}
|
||||
: group,
|
||||
),
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const toggleMapper = useCallback(
|
||||
(groupLocalId: string, mapperLocalId: string, enabled: boolean): void => {
|
||||
setDraft((prev) =>
|
||||
(prev ?? []).map((group) =>
|
||||
group.localId === groupLocalId
|
||||
? {
|
||||
...group,
|
||||
mappers: group.mappers.map((mapper) =>
|
||||
mapper.localId === mapperLocalId ? { ...mapper, enabled } : mapper,
|
||||
),
|
||||
}
|
||||
: group,
|
||||
),
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const discard = useCallback((): void => {
|
||||
setSaveError(null);
|
||||
setDraft(clone(snapshot));
|
||||
}, [snapshot]);
|
||||
|
||||
const save = useCallback(async (): Promise<void> => {
|
||||
if (!draft) {
|
||||
return;
|
||||
}
|
||||
setIsSaving(true);
|
||||
setSaveError(null);
|
||||
try {
|
||||
await persistDraft(snapshot, draft, mutations);
|
||||
await queryClient.invalidateQueries({
|
||||
predicate: (query) =>
|
||||
typeof query.queryKey?.[0] === 'string' &&
|
||||
(query.queryKey[0] as string).startsWith(GROUPS_KEY_PREFIX),
|
||||
});
|
||||
// Re-initialise the working copy from the freshly-fetched server data.
|
||||
setDraft(null);
|
||||
toast.success('Attribute mapping changes saved');
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Save failed';
|
||||
setSaveError(message);
|
||||
toast.error(`Failed to save changes: ${message}`);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}, [draft, snapshot, mutations, queryClient]);
|
||||
|
||||
const isDirty = useMemo(
|
||||
() => draft !== null && JSON.stringify(draft) !== JSON.stringify(snapshot),
|
||||
[draft, snapshot],
|
||||
);
|
||||
|
||||
return {
|
||||
groups: draft ?? [],
|
||||
isLoading: !ready || draft === null,
|
||||
isError: groupsQuery.isError,
|
||||
isDirty,
|
||||
isSaving,
|
||||
saveError,
|
||||
upsertGroup,
|
||||
removeGroup,
|
||||
toggleGroup,
|
||||
upsertMapper,
|
||||
removeMapper,
|
||||
toggleMapper,
|
||||
save,
|
||||
discard,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
import { DraftGroup, GroupDraft, MapperDraftMode } from './types';
|
||||
import { EMPTY_GROUP_DRAFT, groupDraftFromNode } from './utils';
|
||||
|
||||
interface UseGroupFormDrawerResult {
|
||||
isOpen: boolean;
|
||||
mode: MapperDraftMode;
|
||||
draft: GroupDraft;
|
||||
setDraft: (next: GroupDraft) => void;
|
||||
openForAdd: () => void;
|
||||
openForEdit: (group: DraftGroup) => void;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
// Form state for the group drawer. Persistence is staged through the store,
|
||||
// so this hook only owns open/draft/mode.
|
||||
export function useGroupFormDrawer(): UseGroupFormDrawerResult {
|
||||
const [isOpen, setIsOpen] = useState<boolean>(false);
|
||||
const [mode, setMode] = useState<MapperDraftMode>('add');
|
||||
const [draft, setDraft] = useState<GroupDraft>(EMPTY_GROUP_DRAFT);
|
||||
|
||||
const openForAdd = useCallback((): void => {
|
||||
setMode('add');
|
||||
setDraft(EMPTY_GROUP_DRAFT);
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
const openForEdit = useCallback((group: DraftGroup): void => {
|
||||
setMode('edit');
|
||||
setDraft(groupDraftFromNode(group));
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
const close = useCallback((): void => {
|
||||
setIsOpen(false);
|
||||
}, []);
|
||||
|
||||
return { isOpen, mode, draft, setDraft, openForAdd, openForEdit, close };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
import { DraftMapper, MapperDraft, MapperDraftMode } from './types';
|
||||
import { EMPTY_MAPPER_DRAFT, mapperDraftFromNode } from './utils';
|
||||
|
||||
interface UseMapperFormDrawerResult {
|
||||
isOpen: boolean;
|
||||
mode: MapperDraftMode;
|
||||
draft: MapperDraft;
|
||||
setDraft: (next: MapperDraft) => void;
|
||||
openForAdd: () => void;
|
||||
openForEdit: (mapper: DraftMapper) => void;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
// Form state for the mapper drawer. Persistence is staged through the store,
|
||||
// so this hook only owns open/draft/mode.
|
||||
export function useMapperFormDrawer(): UseMapperFormDrawerResult {
|
||||
const [isOpen, setIsOpen] = useState<boolean>(false);
|
||||
const [mode, setMode] = useState<MapperDraftMode>('add');
|
||||
const [draft, setDraft] = useState<MapperDraft>(EMPTY_MAPPER_DRAFT);
|
||||
|
||||
const openForAdd = useCallback((): void => {
|
||||
setMode('add');
|
||||
setDraft(EMPTY_MAPPER_DRAFT);
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
const openForEdit = useCallback((mapper: DraftMapper): void => {
|
||||
setMode('edit');
|
||||
setDraft(mapperDraftFromNode(mapper));
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
const close = useCallback((): void => {
|
||||
setIsOpen(false);
|
||||
}, []);
|
||||
|
||||
return { isOpen, mode, draft, setDraft, openForAdd, openForEdit, close };
|
||||
}
|
||||
262
frontend/src/container/LLMObservabilityAttributeMapping/utils.ts
Normal file
262
frontend/src/container/LLMObservabilityAttributeMapping/utils.ts
Normal file
@@ -0,0 +1,262 @@
|
||||
import {
|
||||
SpantypesPostableSpanMapperDTO,
|
||||
SpantypesPostableSpanMapperGroupDTO,
|
||||
SpantypesUpdatableSpanMapperDTO,
|
||||
SpantypesUpdatableSpanMapperGroupDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import dayjs from 'dayjs';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
import {
|
||||
ConditionFilter,
|
||||
DraftGroup,
|
||||
DraftMapper,
|
||||
FieldContext,
|
||||
GroupDraft,
|
||||
Mapper,
|
||||
MapperDraft,
|
||||
MapperGroup,
|
||||
MapperOperation,
|
||||
SourceConfig,
|
||||
} from './types';
|
||||
|
||||
// Client-side id for not-yet-persisted rows. Prefixed so it never collides
|
||||
// with a server UUID and is easy to spot in logs.
|
||||
export function genLocalId(prefix: 'group' | 'mapper'): string {
|
||||
return `local-${prefix}-${uuid()}`;
|
||||
}
|
||||
|
||||
// Trimmed, de-duplicated, non-empty keys preserving input order.
|
||||
export function cleanKeys(keys: string[]): string[] {
|
||||
const seen = new Set<string>();
|
||||
const result: string[] = [];
|
||||
keys.forEach((raw) => {
|
||||
const key = raw.trim();
|
||||
if (key && !seen.has(key)) {
|
||||
seen.add(key);
|
||||
result.push(key);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
// Display clauses for a group's staged condition keys (span attribute keys
|
||||
// first, then resource keys).
|
||||
export function conditionFiltersFromGroup(group: {
|
||||
attributes: string[];
|
||||
resource: string[];
|
||||
}): ConditionFilter[] {
|
||||
return [
|
||||
...group.attributes.map((key) => ({ context: 'attribute' as const, key })),
|
||||
...group.resource.map((key) => ({ context: 'resource' as const, key })),
|
||||
];
|
||||
}
|
||||
|
||||
// Source configs for a mapper, highest priority first (first match wins at
|
||||
// evaluation time).
|
||||
export function getMapperSources(mapper: Mapper): SourceConfig[] {
|
||||
const sources = mapper.config?.sources ?? [];
|
||||
return [...sources]
|
||||
.sort((a, b) => b.priority - a.priority)
|
||||
.map((source) => ({
|
||||
key: source.key,
|
||||
context: source.context,
|
||||
operation: source.operation,
|
||||
}));
|
||||
}
|
||||
|
||||
// A blank source row. New sources default to `move` so the original key is
|
||||
// removed once standardized (the PRD default — minimizes duplication).
|
||||
export function createEmptySource(): SourceConfig {
|
||||
return {
|
||||
key: '',
|
||||
context: FieldContext.attribute,
|
||||
operation: MapperOperation.move,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatTimestamp(iso?: string): string {
|
||||
if (!iso) {
|
||||
return '—';
|
||||
}
|
||||
return dayjs(iso).format('MMM D, YYYY HH:mm');
|
||||
}
|
||||
|
||||
export const EMPTY_MAPPER_DRAFT: MapperDraft = {
|
||||
id: null,
|
||||
name: '',
|
||||
fieldContext: FieldContext.attribute,
|
||||
sources: [createEmptySource()],
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
// Trimmed, de-duplicated (by key), non-empty sources in priority order,
|
||||
// preserving each source's context and operation.
|
||||
export function getCleanSources(draft: MapperDraft): SourceConfig[] {
|
||||
const seen = new Set<string>();
|
||||
const result: SourceConfig[] = [];
|
||||
draft.sources.forEach((source) => {
|
||||
const key = source.key.trim();
|
||||
if (key && !seen.has(key)) {
|
||||
seen.add(key);
|
||||
result.push({ ...source, key });
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
export function isMapperDraftValid(draft: MapperDraft): boolean {
|
||||
return draft.name.trim().length > 0 && getCleanSources(draft).length > 0;
|
||||
}
|
||||
|
||||
// Priority is derived from list order so the first row wins.
|
||||
function buildSources(
|
||||
draft: MapperDraft,
|
||||
): SpantypesPostableSpanMapperDTO['config']['sources'] {
|
||||
const sources = getCleanSources(draft);
|
||||
return sources.map((source, index) => ({
|
||||
key: source.key,
|
||||
context: source.context,
|
||||
operation: source.operation,
|
||||
priority: sources.length - index,
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildPostableMapper(
|
||||
draft: MapperDraft,
|
||||
): SpantypesPostableSpanMapperDTO {
|
||||
return {
|
||||
name: draft.name.trim(),
|
||||
fieldContext: draft.fieldContext,
|
||||
enabled: draft.enabled,
|
||||
config: { sources: buildSources(draft) },
|
||||
};
|
||||
}
|
||||
|
||||
// The target name is immutable on update (UpdatableSpanMapper has no name).
|
||||
export function buildUpdatableMapper(
|
||||
draft: MapperDraft,
|
||||
): SpantypesUpdatableSpanMapperDTO {
|
||||
return {
|
||||
fieldContext: draft.fieldContext,
|
||||
enabled: draft.enabled,
|
||||
config: { sources: buildSources(draft) },
|
||||
};
|
||||
}
|
||||
|
||||
export const EMPTY_GROUP_DRAFT: GroupDraft = {
|
||||
id: null,
|
||||
name: '',
|
||||
attributes: [''],
|
||||
resource: [],
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
export function isGroupDraftValid(draft: GroupDraft): boolean {
|
||||
return draft.name.trim().length > 0;
|
||||
}
|
||||
|
||||
export function buildPostableGroup(
|
||||
draft: GroupDraft,
|
||||
): SpantypesPostableSpanMapperGroupDTO {
|
||||
return {
|
||||
name: draft.name.trim(),
|
||||
enabled: draft.enabled,
|
||||
condition: {
|
||||
attributes: cleanKeys(draft.attributes),
|
||||
resource: cleanKeys(draft.resource),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// A full group payload is also a valid partial-update payload (all updatable
|
||||
// fields are present), so we reuse the postable builder.
|
||||
export function buildUpdatableGroup(
|
||||
draft: GroupDraft,
|
||||
): SpantypesUpdatableSpanMapperGroupDTO {
|
||||
return buildPostableGroup(draft);
|
||||
}
|
||||
|
||||
// ---- working-copy (draft tree) helpers ----
|
||||
|
||||
export function buildDraftMapper(mapper: Mapper): DraftMapper {
|
||||
return {
|
||||
localId: mapper.id,
|
||||
serverId: mapper.id,
|
||||
name: mapper.name,
|
||||
fieldContext: mapper.fieldContext,
|
||||
sources: getMapperSources(mapper),
|
||||
enabled: mapper.enabled,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildDraftGroup(
|
||||
group: MapperGroup,
|
||||
mappers: Mapper[],
|
||||
): DraftGroup {
|
||||
return {
|
||||
localId: group.id,
|
||||
serverId: group.id,
|
||||
name: group.name,
|
||||
attributes: group.condition?.attributes ?? [],
|
||||
resource: group.condition?.resource ?? [],
|
||||
enabled: group.enabled,
|
||||
mappers: mappers.map(buildDraftMapper),
|
||||
};
|
||||
}
|
||||
|
||||
// DraftGroup -> editable form state (id carries the localId).
|
||||
export function groupDraftFromNode(group: DraftGroup): GroupDraft {
|
||||
return {
|
||||
id: group.localId,
|
||||
name: group.name,
|
||||
attributes: group.attributes.length > 0 ? group.attributes : [''],
|
||||
resource: group.resource,
|
||||
enabled: group.enabled,
|
||||
};
|
||||
}
|
||||
|
||||
// DraftMapper -> editable form state (id carries the localId).
|
||||
export function mapperDraftFromNode(mapper: DraftMapper): MapperDraft {
|
||||
return {
|
||||
id: mapper.localId,
|
||||
name: mapper.name,
|
||||
fieldContext: mapper.fieldContext,
|
||||
sources:
|
||||
mapper.sources.length > 0
|
||||
? mapper.sources.map((source) => ({ ...source }))
|
||||
: [createEmptySource()],
|
||||
enabled: mapper.enabled,
|
||||
};
|
||||
}
|
||||
|
||||
// Form state -> working-copy node. Reuses cleanKeys/getCleanSourceKeys so the
|
||||
// staged tree already holds normalized values.
|
||||
export function nodeFromGroupDraft(
|
||||
draft: GroupDraft,
|
||||
existing?: DraftGroup,
|
||||
): DraftGroup {
|
||||
return {
|
||||
localId: existing?.localId ?? genLocalId('group'),
|
||||
serverId: existing?.serverId ?? null,
|
||||
name: draft.name.trim(),
|
||||
attributes: cleanKeys(draft.attributes),
|
||||
resource: cleanKeys(draft.resource),
|
||||
enabled: draft.enabled,
|
||||
mappers: existing?.mappers ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export function nodeFromMapperDraft(
|
||||
draft: MapperDraft,
|
||||
existing?: DraftMapper,
|
||||
): DraftMapper {
|
||||
return {
|
||||
localId: existing?.localId ?? genLocalId('mapper'),
|
||||
serverId: existing?.serverId ?? null,
|
||||
name: draft.name.trim(),
|
||||
fieldContext: draft.fieldContext,
|
||||
sources: getCleanSources(draft),
|
||||
enabled: draft.enabled,
|
||||
};
|
||||
}
|
||||
@@ -206,6 +206,7 @@ export const routesToSkip = [
|
||||
ROUTES.METER,
|
||||
ROUTES.METER_EXPLORER_VIEWS,
|
||||
ROUTES.SOMETHING_WENT_WRONG,
|
||||
ROUTES.LLM_OBSERVABILITY_ATTRIBUTE_MAPPING,
|
||||
];
|
||||
|
||||
export const routesToDisable = [ROUTES.LOGS_EXPLORER, ROUTES.LIVE_LOGS];
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import LLMObservabilityAttributeMapping from 'container/LLMObservabilityAttributeMapping/LLMObservabilityAttributeMapping';
|
||||
|
||||
function LLMObservabilityAttributeMappingPage(): JSX.Element {
|
||||
return <LLMObservabilityAttributeMapping />;
|
||||
}
|
||||
|
||||
export default LLMObservabilityAttributeMappingPage;
|
||||
@@ -136,4 +136,5 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
|
||||
AI_ASSISTANT_ICON_PREVIEW: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
MCP_SERVER: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
AI_ASSISTANT_BASE: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
LLM_OBSERVABILITY_ATTRIBUTE_MAPPING: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user