The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
feat: add filtering for an endpoint attributes (#402)
Vuk6f46624a5c34
diff --git a/backend/app/controllers/endpoint.controller.go b/backend/app/controllers/endpoint.controller.goindex 737c5be9..30e60976 100644--- a/backend/app/controllers/endpoint.controller.go+++ b/backend/app/controllers/endpoint.controller.go@@ -30,11 +30,13 @@ type EndpointSearchRequest struct {}type EndpointInstancesRequest struct {- FromDate time.Time `json:"fromDate"`- ToDate time.Time `json:"toDate"`- OrderBy string `json:"orderBy"`- SortDirection string `json:"sortDirection"`- Pagination PaginationParams `json:"pagination"`+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ OrderBy string `json:"orderBy"`+ SortDirection string `json:"sortDirection"`+ Search string `json:"search"`+ AttributeFilters []SessionAttributeFilter `json:"attributeFilters"`+ Pagination PaginationParams `json:"pagination"`}type EndpointInstancesResponse struct {@@ -163,8 +165,16 @@ func (e endpointController) FindByEndpoint(c *gin.Context) {return}+ filters := make([]telemetry.SessionAttributeFilter, 0, len(request.AttributeFilters))+ for _, f := range request.AttributeFilters {+ if f.Key == "" {+ continue+ }+ filters = append(filters, telemetry.SessionAttributeFilter{Key: f.Key, Value: f.Value, Exclude: f.Exclude, Contains: f.Contains})+ }+span := traceway.StartSpan(c, "loading endpoint instances")- endpoints, total, err := telemetry.EndpointRepository.FindByEndpoint(c, projectId, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)+ endpoints, total, err := telemetry.EndpointRepository.FindByEndpoint(c, projectId, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, request.Search, filters)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading endpoints: %w", err))diff --git a/backend/app/repositories/telemetry/clickhouse/endpoint.repository.go b/backend/app/repositories/telemetry/clickhouse/endpoint.repository.goindex f068219f..36c4d160 100644--- a/backend/app/repositories/telemetry/clickhouse/endpoint.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/endpoint.repository.go@@ -7,6 +7,7 @@ import ("database/sql""encoding/json""errors"+ "strings""time""github.com/tracewayapp/traceway/backend/app/chdb"@@ -295,9 +296,12 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectIreturn stats, int64(count), nil}-func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.UUID, endpoint string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Endpoint, int64, error) {+func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.UUID, endpoint string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, attributeFilters []shared.SessionAttributeFilter) ([]models.Endpoint, int64, error) {+ whereExtra, extraArgs := buildEndpointFilterClause(search, attributeFilters)+ whereArgs := append([]interface{}{projectId, endpoint, fromDate, toDate}, extraArgs...)+var count uint64- err := chdb.Conn.QueryRow(ctx, "SELECT count() FROM endpoints_v2 WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, endpoint, fromDate, toDate).Scan(&count)+ err := chdb.Conn.QueryRow(ctx, "SELECT count() FROM endpoints_v2 WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?"+whereExtra, whereArgs...).Scan(&count)if err != nil {return nil, 0, err}@@ -321,8 +325,8 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.sortDir = "ASC"}- query := "SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, trace_id, span_id, parent_span_id FROM endpoints_v2 WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " " + sortDir + " LIMIT ? OFFSET ?"- rows, err := chdb.Conn.Query(ctx, query, projectId, endpoint, fromDate, toDate, pageSize, offset)+ query := "SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, trace_id, span_id, parent_span_id FROM endpoints_v2 WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?" + whereExtra + " ORDER BY " + orderBy + " " + sortDir + " LIMIT ? OFFSET ?"+ rows, err := chdb.Conn.Query(ctx, query, append(whereArgs, pageSize, offset)...)if err != nil {return nil, 0, err}@@ -346,6 +350,34 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.return endpoints, int64(count), nil}+func buildEndpointFilterClause(search string, filters []shared.SessionAttributeFilter) (string, []interface{}) {+ // attributes is a JSON string on endpoints_v2, read as a map so it filters like session attributes.+ const attributes = "JSONExtract(attributes, 'Map(String, String)')"+ var sb strings.Builder+ args := []interface{}{}+ if s := strings.TrimSpace(search); s != "" {+ sb.WriteString(" AND arrayExists(v -> positionCaseInsensitiveUTF8(v, ?) > 0, mapValues(" + attributes + "))")+ args = append(args, s)+ }+ for _, f := range filters {+ if f.Key == "" {+ continue+ }+ sb.WriteString(" AND ")+ if f.Exclude {+ sb.WriteString("NOT ")+ }+ sb.WriteString("(mapContains(" + attributes + ", ?) AND ")+ if f.Contains {+ sb.WriteString("positionCaseInsensitiveUTF8(" + attributes + "[?], ?) > 0)")+ } else {+ sb.WriteString(attributes + "[?] = ?)")+ }+ args = append(args, f.Key, f.Key, f.Value)+ }+ return sb.String(), args+}+// FindById returns a single endpoint by IDfunc (e *endpointRepository) FindById(ctx context.Context, projectId, endpointId uuid.UUID, recordedAt *time.Time) (*models.Endpoint, error) {query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, trace_id, span_id, parent_span_id, is_rootdiff --git a/backend/app/repositories/telemetry/duckdb/endpoint.repository.go b/backend/app/repositories/telemetry/duckdb/endpoint.repository.goindex 1cbaf391..c3975786 100644--- a/backend/app/repositories/telemetry/duckdb/endpoint.repository.go+++ b/backend/app/repositories/telemetry/duckdb/endpoint.repository.go@@ -339,11 +339,12 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectIreturn stats[start:endIdx], totalEndpoints, nil}-func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.UUID, endpointName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Endpoint, int64, error) {+func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.UUID, endpointName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, attributeFilters []shared.SessionAttributeFilter) ([]models.Endpoint, int64, error) {params := lit.P{"project_id": projectId, "endpoint": endpointName, "from": fromDate.UTC(), "to": toDate.UTC()}+ whereExtra := buildEndpointFilterClauseDuckDB(search, attributeFilters, params)countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,- "SELECT COUNT(*) AS count FROM endpoints_v2 WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to",+ "SELECT COUNT(*) AS count FROM endpoints_v2 WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to"+whereExtra,params)if err != nil {return nil, 0, err@@ -353,7 +354,8 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.count = int64(countResult.Count)}- offset := (page - 1) * pageSize+ params["limit"] = pageSize+ params["offset"] = (page - 1) * pageSizeallowedOrderBy := map[string]bool{"recorded_at": true, "duration": true, "status_code": true, "body_size": true}if !allowedOrderBy[orderBy] {@@ -367,9 +369,9 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.rows, err := lit.SelectNamed[endpoint](db.TelemetryDB,fmt.Sprintf(`SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, trace_id, span_id, parent_span_id- FROM endpoints_v2 WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to- ORDER BY %s %s LIMIT :limit OFFSET :offset`, orderBy, sortDir),- lit.P{"project_id": projectId, "endpoint": endpointName, "from": fromDate.UTC(), "to": toDate.UTC(), "limit": pageSize, "offset": offset})+ FROM endpoints_v2 WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to%s+ ORDER BY %s %s LIMIT :limit OFFSET :offset`, whereExtra, orderBy, sortDir),+ params)if err != nil {return nil, 0, err}@@ -382,6 +384,34 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.return endpoints, count, nil}+func buildEndpointFilterClauseDuckDB(search string, filters []shared.SessionAttributeFilter, params lit.P) string {+ var sb strings.Builder+ if s := strings.TrimSpace(search); s != "" {+ sb.WriteString(" AND EXISTS (SELECT 1 FROM json_each(endpoints_v2.attributes) AS attr WHERE instr(lower(json_extract_string(attr.value, '$')), lower(:search)) > 0)")+ params["search"] = s+ }+ for i, f := range filters {+ if f.Key == "" {+ continue+ }+ keyParam := fmt.Sprintf("attr_k_%d", i)+ valParam := fmt.Sprintf("attr_v_%d", i)+ sb.WriteString(" AND ")+ if f.Exclude {+ sb.WriteString("NOT ")+ }+ sb.WriteString("EXISTS (SELECT 1 FROM json_each(endpoints_v2.attributes) AS attr WHERE attr.key = :" + keyParam + " AND ")+ if f.Contains {+ sb.WriteString("instr(lower(json_extract_string(attr.value, '$')), lower(:" + valParam + ")) > 0)")+ } else {+ sb.WriteString("json_extract_string(attr.value, '$') = :" + valParam + ")")+ }+ params[keyParam] = f.Key+ params[valParam] = f.Value+ }+ return sb.String()+}+func (e *endpointRepository) FindById(ctx context.Context, projectId, endpointId uuid.UUID, recordedAt *time.Time) (*models.Endpoint, error) {query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, trace_id, span_id, parent_span_id, is_root, is_streamFROM endpoints_v2 WHERE project_id = :project_id AND id = :id`diff --git a/backend/app/repositories/telemetry/endpoint_repository_test.go b/backend/app/repositories/telemetry/endpoint_repository_test.goindex ad572d6b..15d58716 100644--- a/backend/app/repositories/telemetry/endpoint_repository_test.go+++ b/backend/app/repositories/telemetry/endpoint_repository_test.go@@ -322,7 +322,7 @@ func TestEndpointRepository_FindByEndpoint(t *testing.T) {t.Fatalf("InsertAsync failed: %v", err)}- found, total, err := EndpointRepository.FindByEndpoint(ctx, projectId, "GET /api/users", now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "recorded_at", "desc")+ found, total, err := EndpointRepository.FindByEndpoint(ctx, projectId, "GET /api/users", now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "recorded_at", "desc", "", nil)if err != nil {t.Fatalf("FindByEndpoint failed: %v", err)}@@ -340,6 +340,58 @@ func TestEndpointRepository_FindByEndpoint(t *testing.T) {}}+func TestEndpointRepository_FindByEndpoint_FiltersAttributes(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ alice := makeEndpoint(projectId, "GET /api/users", 100*time.Millisecond, 200, now)+ alice.Attributes = map[string]string{"user.id": "u_42", "email": "[email protected]", "tenant": "acme", "empty": ""}+ bob := makeEndpoint(projectId, "GET /api/users", 100*time.Millisecond, 200, now.Add(time.Minute))+ bob.Attributes = map[string]string{"user.id": "u_43", "email": "[email protected]", "tenant": "other"}+ anonymous := makeEndpoint(projectId, "GET /api/users", 100*time.Millisecond, 200, now.Add(2*time.Minute))+ otherEndpoint := makeEndpoint(projectId, "POST /api/users", 100*time.Millisecond, 201, now)+ otherEndpoint.Attributes = alice.Attributes+ if err := EndpointRepository.InsertAsync(ctx, []models.Endpoint{alice, bob, anonymous, otherEndpoint}); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ cases := []struct {+ name, search string+ filters []SessionAttributeFilter+ want int64+ }{+ {name: "unfiltered", want: 3},+ {name: "search value", search: "u_42", want: 1},+ {name: "case insensitive search", search: "ALICE@EXAMPLE", want: 1},+ {name: "search ignores keys", search: "tenant", want: 0},+ {name: "exact dotted key", filters: []SessionAttributeFilter{{Key: "user.id", Value: "u_42"}}, want: 1},+ {name: "case sensitive equals", filters: []SessionAttributeFilter{{Key: "email", Value: "[email protected]"}}, want: 0},+ {name: "contains", filters: []SessionAttributeFilter{{Key: "email", Value: "ALICE@", Contains: true}}, want: 1},+ {name: "exclude includes absent", filters: []SessionAttributeFilter{{Key: "user.id", Value: "u_42", Exclude: true}}, want: 2},+ {name: "not contains", filters: []SessionAttributeFilter{{Key: "email", Value: "EXAMPLE", Contains: true, Exclude: true}}, want: 1},+ {name: "empty differs from missing", filters: []SessionAttributeFilter{{Key: "empty", Value: ""}}, want: 1},+ {name: "SQL in key", filters: []SessionAttributeFilter{{Key: `' OR 1=1 --`, Value: ""}}, want: 0},+ {name: "AND filters", filters: []SessionAttributeFilter{{Key: "user.id", Value: "u_42"}, {Key: "tenant", Value: "other"}}, want: 0},+ {name: "search AND filter", search: "bob", filters: []SessionAttributeFilter{{Key: "tenant", Value: "acme"}}, want: 0},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ rows, total, err := EndpointRepository.FindByEndpoint(ctx, projectId, "GET /api/users", now.Add(-time.Hour), now.Add(time.Hour), 1, 1, "recorded_at", "desc", tc.search, tc.filters)+ if err != nil {+ t.Fatal(err)+ }+ if total != tc.want {+ t.Fatalf("total = %d, want %d", total, tc.want)+ }+ if len(rows) != int(min(tc.want, 1)) {+ t.Fatalf("page length = %d, total = %d", len(rows), total)+ }+ })+ }+}+func TestEndpointRepository_FindById(t *testing.T) {setupTestDB(t)ctx := context.Background()diff --git a/backend/app/repositories/telemetry/sqlite/endpoint.repository.go b/backend/app/repositories/telemetry/sqlite/endpoint.repository.goindex 33e2445b..7caca52d 100644--- a/backend/app/repositories/telemetry/sqlite/endpoint.repository.go+++ b/backend/app/repositories/telemetry/sqlite/endpoint.repository.go@@ -356,11 +356,12 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectIreturn stats[start:endIdx], totalEndpoints, nil}-func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.UUID, endpointName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Endpoint, int64, error) {+func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.UUID, endpointName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, attributeFilters []shared.SessionAttributeFilter) ([]models.Endpoint, int64, error) {params := lit.P{"project_id": projectId, "endpoint": endpointName, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}+ whereExtra := buildEndpointFilterClauseSQLite(search, attributeFilters, params)countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,- "SELECT COUNT(*) AS count FROM endpoints_v2 WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to",+ "SELECT COUNT(*) AS count FROM endpoints_v2 WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to"+whereExtra,params)if err != nil {return nil, 0, err@@ -370,7 +371,8 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.count = int64(countResult.Count)}- offset := (page - 1) * pageSize+ params["limit"] = pageSize+ params["offset"] = (page - 1) * pageSizeallowedOrderBy := map[string]bool{"recorded_at": true, "duration": true, "status_code": true, "body_size": true}if !allowedOrderBy[orderBy] {@@ -384,9 +386,9 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.rows, err := lit.SelectNamed[endpoint](db.TelemetryDB,fmt.Sprintf(`SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, trace_id, span_id, parent_span_id- FROM endpoints_v2 WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to- ORDER BY %s %s LIMIT :limit OFFSET :offset`, orderBy, sortDir),- lit.P{"project_id": projectId, "endpoint": endpointName, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})+ FROM endpoints_v2 WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to%s+ ORDER BY %s %s LIMIT :limit OFFSET :offset`, whereExtra, orderBy, sortDir),+ params)if err != nil {return nil, 0, err}@@ -399,6 +401,34 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.return endpoints, count, nil}+func buildEndpointFilterClauseSQLite(search string, filters []shared.SessionAttributeFilter, params lit.P) string {+ var sb strings.Builder+ if s := strings.TrimSpace(search); s != "" {+ sb.WriteString(" AND EXISTS (SELECT 1 FROM json_each(endpoints_v2.attributes) AS attr WHERE instr(lower(attr.value), lower(:search)) > 0)")+ params["search"] = s+ }+ for i, f := range filters {+ if f.Key == "" {+ continue+ }+ keyParam := fmt.Sprintf("attr_k_%d", i)+ valParam := fmt.Sprintf("attr_v_%d", i)+ sb.WriteString(" AND ")+ if f.Exclude {+ sb.WriteString("NOT ")+ }+ sb.WriteString("EXISTS (SELECT 1 FROM json_each(endpoints_v2.attributes) AS attr WHERE attr.key = :" + keyParam + " AND ")+ if f.Contains {+ sb.WriteString("instr(lower(attr.value), lower(:" + valParam + ")) > 0)")+ } else {+ sb.WriteString("attr.value = :" + valParam + ")")+ }+ params[keyParam] = f.Key+ params[valParam] = f.Value+ }+ return sb.String()+}+func (e *endpointRepository) FindById(ctx context.Context, projectId, endpointId uuid.UUID, recordedAt *time.Time) (*models.Endpoint, error) {query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, trace_id, span_id, parent_span_id, is_root, is_streamFROM endpoints_v2 WHERE project_id = :project_id AND id = :id`diff --git a/frontend/src/routes/endpoints/[endpoint]/+page.svelte b/frontend/src/routes/endpoints/[endpoint]/+page.svelteindex 6a4db86c..c818929e 100644--- a/frontend/src/routes/endpoints/[endpoint]/+page.svelte+++ b/frontend/src/routes/endpoints/[endpoint]/+page.svelte@@ -17,7 +17,9 @@import { Button } from '$lib/components/ui/button';import { LoadingCircle } from '$lib/components/ui/loading-circle';import { TimeRangePicker } from '$lib/components/ui/time-range-picker';- import { Check, Snail } from '@lucide/svelte';+ import { SearchBar } from '$lib/components/ui/search-bar';+ import * as Select from '$lib/components/ui/select';+ import { Check, Plus, Snail, X } from '@lucide/svelte';import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';import { TableEmptyState } from '$lib/components/ui/table-empty-state';import { CalendarDate } from '@internationalized/date';@@ -54,6 +56,12 @@handleSortClick,type SortDirection} from '$lib/utils/sort-storage';+ import {+ parseAttributeFilter,+ filterOperator,+ type AttributeFilter,+ type FilterOperator+ } from '$lib/utils/session-filters';const timezone = $derived(getTimezone());const initialTimezone = getTimezone();@@ -131,11 +139,108 @@let fromTime = $state(dateToTimeString(initialRange.from, initialTimezone));let toTime = $state(dateToTimeString(initialRange.to, initialTimezone));- function updateTimeRangeUrl(pushToHistory = true) {+ function parseFilterUrlParams() {+ const params = new URLSearchParams(window.location.search);+ const attrs: AttributeFilter[] = [];+ for (const raw of params.getAll('attr')) {+ const parsed = parseAttributeFilter(raw);+ if (parsed) attrs.push(parsed);+ }+ return { search: params.get('search') ?? '', attributeFilters: attrs };+ }++ let searchQuery = $state('');+ let attributeFilters = $state<AttributeFilter[]>([]);++ let addFilterOpen = $state(false);+ let dialogKey = $state('');+ let dialogValue = $state('');+ let dialogError = $state('');+ let dialogOperator = $state<FilterOperator>('=');+ let dialogEditIndex = $state<number | null>(null);+ const operatorOptions: { value: FilterOperator; label: string }[] = [+ { value: '=', label: 'Equals' },+ { value: '!=', label: 'Not equals' },+ { value: '~=', label: 'Contains' },+ { value: '!~=', label: 'Not contains' }+ ];++ function openAddFilterDialog() {+ dialogKey = '';+ dialogValue = '';+ dialogOperator = '=';+ dialogEditIndex = null;+ dialogError = '';+ addFilterOpen = true;+ }++ function openEditFilterDialog(index: number) {+ const filter = attributeFilters[index];+ dialogKey = filter.key;+ dialogValue = filter.value;+ dialogOperator = filterOperator(filter);+ dialogEditIndex = index;+ dialogError = '';+ addFilterOpen = true;+ }++ function submitDialogFilter() {+ const key = dialogKey.trim();+ if (!key) {+ dialogError = 'Attribute key is required';+ return;+ }+ const filter: AttributeFilter = {+ key,+ value: dialogValue,+ exclude: dialogOperator.startsWith('!'),+ contains: dialogOperator.includes('~')+ };+ const others = attributeFilters.filter((_, i) => i !== dialogEditIndex);+ const duplicate = others.some(+ (f) =>+ f.key === filter.key &&+ f.value === filter.value &&+ f.exclude === filter.exclude &&+ f.contains === filter.contains+ );+ attributeFilters = duplicate+ ? others+ : dialogEditIndex === null+ ? [...others, filter]+ : attributeFilters.map((f, i) => (i === dialogEditIndex ? filter : f));+ addFilterOpen = false;+ page = 1;+ loadData(true);+ }++ function handleDialogKeydown(e: KeyboardEvent) {+ if (e.key === 'Enter') {+ e.preventDefault();+ submitDialogFilter();+ }+ }++ function removeAttributeFilter(index: number) {+ attributeFilters = attributeFilters.filter((_, i) => i !== index);+ page = 1;+ loadData(true);+ }++ function handleSearch() {+ page = 1;+ loadData(true);+ }++ function updateEndpointUrl(pushToHistory = true) {updateUrl(- selectedPreset- ? { preset: selectedPreset }- : { from: getFromDateTimeUTC(), to: getToDateTimeUTC() },+ {+ preset: selectedPreset || null,+ from: selectedPreset ? null : getFromDateTimeUTC(),+ to: selectedPreset ? null : getToDateTimeUTC(),+ search: searchQuery.trim() || null,+ attr: attributeFilters.map((f) => `${f.key}${filterOperator(f)}${f.value}`)+ },{ pushToHistory });}@@ -231,7 +336,7 @@toTime = dateToTimeString(range.to, timezone);}- updateTimeRangeUrl(pushToHistory);+ updateEndpointUrl(pushToHistory);try {const requestBody = {@@ -239,6 +344,8 @@toDate: getToDateTimeUTC(),orderBy: orderBy,sortDirection: sortDirection,+ search: searchQuery.trim(),+ attributeFilters,pagination: {page: page,pageSize: pageSize@@ -344,6 +451,9 @@toDate = dateToCalendarDate(range.to, timezone);fromTime = dateToTimeString(range.from, timezone);toTime = dateToTimeString(range.to, timezone);+ const filterParams = parseFilterUrlParams();+ searchQuery = filterParams.search;+ attributeFilters = filterParams.attributeFilters;page = 1;loadData(false);}@@ -371,6 +481,9 @@toDate = dateToCalendarDate(range.to, timezone);fromTime = dateToTimeString(range.from, timezone);toTime = dateToTimeString(range.to, timezone);+ const filterParams = parseFilterUrlParams();+ searchQuery = filterParams.search;+ attributeFilters = filterParams.attributeFilters;loadData(false);offsetMs = 0;reason = '';@@ -498,6 +611,49 @@</div>{/if}+ <SearchBar+ placeholder="Search attribute values..."+ bind:value={searchQuery}+ onSearch={handleSearch}+ disabled={loading}+ />++ <div class="flex flex-wrap items-center gap-2">+ <button+ type="button"+ class="inline-flex items-center gap-1 rounded-full border border-dashed px-3 py-0.5 text-xs font-medium text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground"+ onclick={openAddFilterDialog}+ disabled={loading}+ >+ <Plus class="h-3 w-3" />+ Add filter+ </button>+ {#each attributeFilters as f, i (i)}+ <span+ class="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 font-mono text-xs"+ >+ <button+ type="button"+ aria-label="Edit filter"+ class="inline-flex cursor-pointer items-center gap-1 hover:text-primary"+ onclick={() => openEditFilterDialog(i)}+ >+ <span class="text-muted-foreground">{f.key}</span>+ <span class={f.exclude ? 'text-red-500' : ''}>{filterOperator(f)}</span>+ <span class="max-w-64 truncate" title={f.value}>{f.value || '""'}</span>+ </button>+ <button+ type="button"+ aria-label="Remove filter"+ class="ml-1 text-muted-foreground hover:text-foreground"+ onclick={() => removeAttributeFilter(i)}+ >+ <X class="h-3 w-3" />+ </button>+ </span>+ {/each}+ </div>+<!-- Traces Table --><TableContainer minWidth="960px" empty={!loading && transactions.length === 0}><Table.Root>@@ -553,7 +709,12 @@</Table.Cell></Table.Row>{:else if transactions.length === 0}- <TableEmptyState colspan={8} message="No traces found in this time range." />+ <TableEmptyState+ colspan={8}+ message={searchQuery.trim() || attributeFilters.length+ ? 'No traces match your search and filters.'+ : 'No traces found in this time range.'}+ />{:else}{#each transactions as transaction, __index (__index)}<Table.Row@@ -659,3 +820,57 @@</AlertDialog.Footer></AlertDialog.Content></AlertDialog.Root>++<AlertDialog.Root open={addFilterOpen} onOpenChange={(open) => (addFilterOpen = open)}>+ <AlertDialog.Content>+ <AlertDialog.Header>+ <AlertDialog.Title+ >{dialogEditIndex === null+ ? 'Add attribute filter'+ : 'Edit attribute filter'}</AlertDialog.Title+ >+ <AlertDialog.Description>+ Filter traces by attributes such as <code class="font-mono">user.id</code> or+ <code class="font-mono">tenant</code>. All filters must match. Contains ignores case;+ excluded filters also include traces without the attribute.+ </AlertDialog.Description>+ </AlertDialog.Header>+ <div class="flex flex-col gap-3">+ <FormField label="Attribute key">+ <Input placeholder="user.id" bind:value={dialogKey} onkeydown={handleDialogKeydown} />+ </FormField>+ <FormField label="Operator">+ <Select.Root+ type="single"+ value={dialogOperator}+ onValueChange={(v) => (dialogOperator = v as FilterOperator)}+ >+ <Select.Trigger class="w-full"+ >{operatorOptions.find((o) => o.value === dialogOperator)?.label}</Select.Trigger+ >+ <Select.Content>+ {#each operatorOptions as option (option.value)}+ <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </FormField>+ <FormField label="Value">+ <Input placeholder="u_42" bind:value={dialogValue} onkeydown={handleDialogKeydown} />+ </FormField>+ {#if dialogError}+ <p class="text-xs text-red-500">{dialogError}</p>+ {/if}+ </div>+ <AlertDialog.Footer>+ <Button variant="outline" onclick={() => (addFilterOpen = false)}>Cancel</Button>+ <Button onclick={submitDialogFilter}>+ {#if dialogEditIndex === null}+ <Plus class="h-4 w-4" /> Add filter+ {:else}+ <Check class="h-4 w-4" /> Update filter+ {/if}+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+</AlertDialog.Root>