-
Notifications
You must be signed in to change notification settings - Fork 272
Expand file tree
/
Copy pathtransactions_v4.go
More file actions
2485 lines (2305 loc) · 93.2 KB
/
Copy pathtransactions_v4.go
File metadata and controls
2485 lines (2305 loc) · 93.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2025 Homer Server Contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
package handlers
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/ijt/go-anytime/v2"
"github.com/labstack/echo/v4"
"github.com/sipcapture/homer-core/src/coordinator/services"
"github.com/sipcapture/homer-core/src/coordinator/sqlvalidator"
"github.com/sipcapture/homer-core/src/pcapwriter"
logger "github.com/sipcapture/homer-core/src/utils/logging"
)
// b2bSuffixRe matches B2BUA suffixes appended to Call-IDs by SIP proxies
// (e.g. _b2b-1, _b2b-2). RTCP/RTP packets typically use the raw Call-ID.
var b2bSuffixRe = regexp.MustCompile(`_b2b-\d+$`)
// stripB2BSuffix removes B2BUA leg suffix from a session ID so that it can
// match RTCP/RTP records which store the original Call-ID.
func stripB2BSuffix(sid string) string {
return b2bSuffixRe.ReplaceAllString(sid, "")
}
// sipFilterMethodValues merges filter.method (including comma-separated tokens),
// filter.methods, trims and dedupes. Matches Homer UI multi-select + custom SIP methods.
func sipFilterMethodValues(method string, methods []string) []string {
seen := make(map[string]struct{})
out := make([]string, 0)
add := func(s string) {
s = strings.TrimSpace(s)
if s == "" {
return
}
if _, ok := seen[s]; ok {
return
}
seen[s] = struct{}{}
out = append(out, s)
}
for _, m := range methods {
add(m)
}
if method != "" {
for _, part := range strings.Split(method, ",") {
add(strings.TrimSpace(part))
}
}
return out
}
// sipFilterResponseValues merges filter.response_code (comma-separated allowed),
// filter.response_codes — for multi-select + custom SIP response codes.
func sipFilterResponseValues(code string, codes []string) []string {
seen := make(map[string]struct{})
out := make([]string, 0)
add := func(s string) {
s = strings.TrimSpace(s)
if s == "" {
return
}
if _, ok := seen[s]; ok {
return
}
seen[s] = struct{}{}
out = append(out, s)
}
for _, c := range codes {
add(c)
}
if code != "" {
for _, part := range strings.Split(code, ",") {
add(strings.TrimSpace(part))
}
}
return out
}
type TransactionListResponseV4 struct {
Data struct {
Items []map[string]interface{} `json:"items"`
Keys []string `json:"keys,omitempty"`
} `json:"data"`
Meta Meta `json:"meta"`
}
type MessageListResponseV4 struct {
Data struct {
Items []map[string]interface{} `json:"items"`
} `json:"data"`
Meta Meta `json:"meta"`
}
type MessageResponseV4 struct {
Data map[string]interface{} `json:"data"`
Meta Meta `json:"meta"`
}
type MessageDecodedResponseV4 struct {
Data struct {
Data []map[string]interface{} `json:"data"`
} `json:"data"`
Meta Meta `json:"meta"`
}
type QosResponseV4 struct {
Data map[string]interface{} `json:"data"`
Meta Meta `json:"meta"`
}
type LogListResponseV4 struct {
Data struct {
Items []map[string]interface{} `json:"items"`
} `json:"data"`
Meta Meta `json:"meta"`
}
type SearchObjectV4 struct {
Filter struct {
ProtoType int `json:"proto_type"`
EventType string `json:"event_type"`
Method string `json:"method"` // legacy single value; comma-separated OK; merged with methods
Methods []string `json:"methods,omitempty"` // multi-select + custom methods → SQL IN (...)
ResponseCode string `json:"response_code,omitempty"` // comma-separated OK; merged with response_codes
ResponseCodes []string `json:"response_codes,omitempty"` // multi-select + custom codes → SQL IN (...)
CallID string `json:"call_id"`
SessionID string `json:"session_id,omitempty"` // alias for call_id (matches DuckLake column name)
CID string `json:"cid,omitempty"` // search in cid column only
RuriUser string `json:"ruri_user"`
FromUser string `json:"from_user"`
Caller string `json:"caller,omitempty"` // alias for from_user
ToUser string `json:"to_user"`
Callee string `json:"callee,omitempty"` // alias for to_user
UserAgent string `json:"user_agent"`
SrcIP string `json:"src_ip"`
DstIP string `json:"dst_ip"`
SrcPort int `json:"src_port"`
DstPort int `json:"dst_port"`
CaptureID int `json:"capture_id"`
Node string `json:"node"`
NodeID string `json:"node_id,omitempty"` // alias for node
Aor string `json:"aor,omitempty"` // SIP registration column
Contact string `json:"contact,omitempty"` // SIP registration column
Expires string `json:"expires,omitempty"` // SIP registration column
CseqMethod string `json:"cseq_method,omitempty"` // SIP call column cseq_method
Payload string `json:"payload,omitempty"` // full-text search in payload (LOG)
// OTLP metrics (proto_type 201) — Protocol Search form + metric-name picker.
Name string `json:"name,omitempty"` // exact metric name (preferred over call_id→name LIKE)
Type string `json:"type,omitempty"` // single OTLP metric kind (gauge, sum, …)
Types []string `json:"types,omitempty"` // multi-select → IN ("type", …)
ServiceName string `json:"service_name,omitempty"` // LIKE on service_name (narrowing)
// Virtual carries structured-search values for fields_mapping[].virtual (data_extra JSON, etc.).
// Keys are field ids; only keys declared in the active mapping row are applied.
Virtual map[string]string `json:"virtual,omitempty"`
// VirtualAbsent lists field ids (mapping virtual.match=absent) when the UI checkbox is on.
VirtualAbsent []string `json:"virtual_absent,omitempty"`
// VirtualPresent lists field ids (mapping virtual.match=present) when the UI checkbox is on.
VirtualPresent []string `json:"virtual_present,omitempty"`
} `json:"filter"`
Param struct {
Limit int `json:"limit"`
Select string `json:"select,omitempty"` // custom SELECT columns/aggregations (e.g. "method, count(*) as cnt")
GroupBy string `json:"group_by,omitempty"` // GROUP BY clause (e.g. "method")
OrderBy string `json:"order_by,omitempty"` // custom ORDER BY (e.g. "cnt DESC")
} `json:"param"`
Timestamp struct {
From int64 `json:"from"`
To int64 `json:"to"`
} `json:"timestamp"`
}
// maxTransactionSessionIDs caps OR-clauses for multi-session message queries.
const maxTransactionSessionIDs = 50
// maxOTLPTraceSpansPerQuery caps rows returned for a single trace_id via
// POST /transactions/messages on otlp_traces (no uuid / session_id column).
const maxOTLPTraceSpansPerQuery = 5000
// maxOTLPLogsPerQuery caps log rows for a single trace_id on otlp_logs.
const maxOTLPLogsPerQuery = 5000
// maxOTLPMetricsPerQuery caps metric points for a single metric name on otlp_metrics.
const maxOTLPMetricsPerQuery = 5000
// maxOTLPMetricNamesDistinct caps rows returned for POST /transactions/otlp-metric-names.
const maxOTLPMetricNamesDistinct = 2000
// normalizeTransactionSessionIDs trims, deduplicates, and caps session id list for SQL IN/OR use.
func normalizeTransactionSessionIDs(ids []string) []string {
if len(ids) == 0 {
return nil
}
seen := make(map[string]struct{}, len(ids))
out := make([]string, 0, len(ids))
for _, raw := range ids {
s := strings.TrimSpace(raw)
if s == "" {
continue
}
if _, ok := seen[s]; ok {
continue
}
seen[s] = struct{}{}
out = append(out, s)
if len(out) >= maxTransactionSessionIDs {
break
}
}
return out
}
func buildSessionIDOrWhere(sessionIDs []string) string {
parts := make([]string, len(sessionIDs))
for i, sid := range sessionIDs {
parts[i] = fmt.Sprintf("session_id = '%s'", sqlvalidator.SafeString(sid))
}
return "(" + strings.Join(parts, " OR ") + ")"
}
// sessionMatchOneSQL matches one Call-ID on session_id, including B2B leg suffix stripping for RTCP/RTP correlation.
func sessionMatchOneSQL(sid string) string {
safe := sqlvalidator.SafeString(strings.TrimSpace(sid))
if safe == "" {
return ""
}
base := stripB2BSuffix(safe)
baseSafe := sqlvalidator.SafeString(base)
if baseSafe != safe {
return fmt.Sprintf("(session_id = '%s' OR session_id = '%s')", safe, baseSafe)
}
return fmt.Sprintf("session_id = '%s'", safe)
}
// buildSessionIDMatchOrChain ORs B2B-aware session_id clauses for multiple Call-IDs (QoS, logs, callinfo, etc.).
func buildSessionIDMatchOrChain(sessionIDs []string) string {
parts := make([]string, 0, len(sessionIDs))
for _, sid := range sessionIDs {
if p := sessionMatchOneSQL(sid); p != "" {
parts = append(parts, p)
}
}
if len(parts) == 0 {
return "FALSE"
}
return "(" + strings.Join(parts, " OR ") + ")"
}
// buildExactColumnMatchOrChain builds (col = 'a' OR col = 'b') with escaped
// string values. Used for OTLP trace_id (no B2B Call-ID suffix stripping).
func buildExactColumnMatchOrChain(column string, ids []string) string {
switch column {
case "trace_id", "name":
default:
return "FALSE"
}
parts := make([]string, 0, len(ids))
for _, raw := range ids {
s := strings.TrimSpace(raw)
if s == "" {
continue
}
parts = append(parts, fmt.Sprintf("%s = '%s'", column, sqlvalidator.SafeString(s)))
}
if len(parts) == 0 {
return "FALSE"
}
return "(" + strings.Join(parts, " OR ") + ")"
}
func isOTLPTracesDuckLakeTable(table string) bool {
return strings.HasSuffix(strings.TrimSpace(table), "otlp_traces")
}
func isOTLPLogsDuckLakeTable(table string) bool {
return strings.HasSuffix(strings.TrimSpace(table), "otlp_logs")
}
func isOTLPTableCorrelatedByTraceID(table string) bool {
return isOTLPTracesDuckLakeTable(table) || isOTLPLogsDuckLakeTable(table)
}
func isOTLPMetricsDuckLakeTable(table string) bool {
return strings.HasSuffix(strings.TrimSpace(table), "otlp_metrics")
}
// buildSubMatchOrChain matches SUB/NOTIFY traffic: (session_id OR cid) per Call-ID, B2B-aware.
func buildSubMatchOrChain(sessionIDs []string) string {
parts := make([]string, 0, len(sessionIDs))
for _, sid := range sessionIDs {
safe := sqlvalidator.SafeString(strings.TrimSpace(sid))
if safe == "" {
continue
}
base := stripB2BSuffix(safe)
baseSafe := sqlvalidator.SafeString(base)
if baseSafe != safe {
parts = append(parts, fmt.Sprintf("((session_id = '%s' OR session_id = '%s') OR (cid = '%s' OR cid = '%s'))", safe, baseSafe, safe, baseSafe))
} else {
parts = append(parts, fmt.Sprintf("(session_id = '%s' OR cid = '%s')", safe, safe))
}
}
if len(parts) == 0 {
return "FALSE"
}
return "(" + strings.Join(parts, " OR ") + ")"
}
// resolvedSessionIDList returns normalized ids from session_ids (priority) or a single session_id.
func resolvedSessionIDList(req *TransactionSessionRequestV4) ([]string, error) {
multi := normalizeTransactionSessionIDs(req.SessionIDs)
if len(multi) > 0 {
return multi, nil
}
s := strings.TrimSpace(req.SessionID)
if s == "" {
return nil, fmt.Errorf("session_id or non-empty session_ids is required")
}
return []string{s}, nil
}
type TransactionSessionRequestV4 struct {
SessionID string `json:"session_id"`
SessionIDs []string `json:"session_ids,omitempty"`
ProtoType int `json:"proto_type"`
EventType string `json:"event_type"`
// Whitelist lists IPs to exclude from PCAP/text export (legacy Homer 7 name; not an allow-list).
Whitelist []string `json:"whitelist,omitempty"`
Timestamp struct {
From int64 `json:"from,omitempty"`
To int64 `json:"to,omitempty"`
} `json:"timestamp,omitempty"`
}
// TransactionOtlpLogsRequestV4 searches otlp_logs for rows containing call_id in body / JSON blobs within an optional time window.
type TransactionOtlpLogsRequestV4 struct {
SessionID string `json:"session_id"`
SessionIDs []string `json:"session_ids,omitempty"`
Timestamp struct {
From int64 `json:"from,omitempty"`
To int64 `json:"to,omitempty"`
} `json:"timestamp,omitempty"`
CallID string `json:"call_id"` // substring match; if empty, first resolved session id is used
}
// TransactionOtlpLogsTraceRequestV4 loads all otlp_logs rows for one trace_id in the optional time window (session context required).
type TransactionOtlpLogsTraceRequestV4 struct {
SessionID string `json:"session_id"`
SessionIDs []string `json:"session_ids,omitempty"`
Timestamp struct {
From int64 `json:"from,omitempty"`
To int64 `json:"to,omitempty"`
} `json:"timestamp,omitempty"`
TraceID string `json:"trace_id"`
}
// TransactionOtlpMetricNamesRequestV4 lists distinct metric names in otlp_metrics for a time window.
type TransactionOtlpMetricNamesRequestV4 struct {
Timestamp struct {
From int64 `json:"from,omitempty"`
To int64 `json:"to,omitempty"`
} `json:"timestamp"`
ServiceName string `json:"service_name,omitempty"` // optional LIKE narrow on service_name
}
func buildOTLPMetricNamesSQL(lake string, fromMs, toMs int64, serviceFilter string) string {
conds := []string{
fmt.Sprintf("timestamp >= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')", fromMs),
fmt.Sprintf("timestamp <= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')", toMs),
"name IS NOT NULL",
"CAST(name AS VARCHAR) != ''",
}
if s := strings.TrimSpace(serviceFilter); s != "" {
conds = append(conds, fmt.Sprintf("service_name LIKE '%%%s%%'", sqlvalidator.SafeString(s)))
}
table := fmt.Sprintf("%s.otlp_metrics", lake)
return fmt.Sprintf(
"SELECT DISTINCT name FROM %s WHERE %s ORDER BY name LIMIT %d",
table,
strings.Join(conds, " AND "),
maxOTLPMetricNamesDistinct,
)
}
// MessageGetRequestV4 is the body for POST /api/v4/messages and POST /api/v4/messages/decoded.
type MessageGetRequestV4 struct {
UUID string `json:"uuid"`
ProtoType int `json:"proto_type"`
EventType string `json:"event_type"`
Timestamp struct {
From int64 `json:"from,omitempty"`
To int64 `json:"to,omitempty"`
} `json:"timestamp,omitempty"`
}
// RawQueryRequest is the body for POST /api/v4/query (raw SQL passthrough).
type RawQueryRequest struct {
SQL string `json:"sql"`
Limit int `json:"limit,omitempty"` // safety cap, default 1000
}
// MCPQueryRequest is the body for POST /api/v4/mcp/query.
// It converts natural language query into structured or SQL execution.
type MCPQueryRequest struct {
QueryText string `json:"query_text"`
Mode string `json:"mode,omitempty"` // auto|structured|sql
Parser string `json:"parser,omitempty"` // auto|llm|regex (default: auto)
Limit int `json:"limit,omitempty"`
Timestamp struct {
From int64 `json:"from,omitempty"`
To int64 `json:"to,omitempty"`
} `json:"timestamp,omitempty"`
NowUTCUnixMS int64 `json:"now_utc_unix_ms,omitempty"`
}
// normalizeParserHint sanitizes the user-supplied parser strategy. Unknown or
// empty values map to "auto" so old clients keep their previous behavior.
func normalizeParserHint(s string) string {
switch strings.ToLower(strings.TrimSpace(s)) {
case "llm":
return "llm"
case "regex", "rule", "rules":
return "regex"
default:
return "auto"
}
}
func (h *SearchHandler) V4TransactionsList(c echo.Context) error {
req := SimpleSearchRequest{
TransactionType: c.QueryParam("filter[event_type]"),
CallID: c.QueryParam("filter[transaction_id]"),
SrcIP: c.QueryParam("filter[src_ip]"),
DstIP: c.QueryParam("filter[dst_ip]"),
Method: c.QueryParam("filter[method]"),
NodeID: c.QueryParam("filter[node]"),
}
if proto := c.QueryParam("filter[protocol]"); proto != "" {
if v, err := strconv.Atoi(proto); err == nil {
req.ProtoType = v
}
}
req.From = c.QueryParam("from")
req.To = c.QueryParam("to")
limit := 0
if limitStr := c.QueryParam("page[limit]"); limitStr != "" {
if v, err := strconv.Atoi(limitStr); err == nil {
limit = v
}
}
req.Limit = limit
sql, err := h.buildSimpleSearchSQL(&req)
if err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", err.Error())
}
results, err := h.flightService.Query(c.Request().Context(), sql)
if err != nil {
return writeError(c, http.StatusInternalServerError, "Server Error", "Query failed")
}
h.enrichRowsWithIPAliases(c.Request().Context(), results)
resp := TransactionListResponseV4{}
resp.Data.Items = results
resp.Data.Keys = getColumns(results)
resp.Meta = buildMeta(c, "")
resp.Meta.Pagination = &Pagination{Limit: req.Limit, Total: len(results)}
return c.JSON(http.StatusOK, resp)
}
func (h *SearchHandler) V4TransactionsSearch(c echo.Context) error {
var req SearchObjectV4
if err := c.Bind(&req); err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", "Invalid request body")
}
virtualRules := h.loadVirtualRulesForReq(c.Request().Context(), &req)
sql, err := buildSearchSQLV4(h.flightService.LakeName(), &req, virtualRules)
if err != nil {
logger.Error(fmt.Sprintf("V4TransactionsSearch: SQL validation failed: %v", err))
return writeError(c, http.StatusBadRequest, "Bad Request", fmt.Sprintf("SQL validation failed: %v", err))
}
logger.Info("V4TransactionsSearch", "proto", req.Filter.ProtoType, "event", req.Filter.EventType, "sql", sql)
results, err := h.flightService.Query(c.Request().Context(), sql)
if err != nil {
logger.Error(fmt.Sprintf("V4TransactionsSearch: query error: %v", err))
return writeError(c, http.StatusInternalServerError, "Server Error", "Query failed")
}
logger.Info("V4TransactionsSearch: got results", "count", len(results))
h.enrichRowsWithIPAliases(c.Request().Context(), results)
resp := TransactionListResponseV4{}
resp.Data.Items = results
resp.Data.Keys = getColumns(results)
resp.Meta = buildMeta(c, "")
resp.Meta.Pagination = &Pagination{Limit: req.Param.Limit, Total: len(results)}
if req.Timestamp.From > 0 && req.Timestamp.To > 0 {
resp.Meta.TimeRange = &TimeRangeMeta{From: req.Timestamp.From, To: req.Timestamp.To}
}
return c.JSON(http.StatusOK, resp)
}
// queryTransactionMessages loads SIP (or other proto) rows for a transaction session request (same rules as POST /transactions/messages).
//
// When a Lua correlation script is registered for (proto_type, event_type) the
// function runs two phases:
// 1. Query the base session_id set (as before).
// 2. Pass the base rows into the script; if the script returns extra
// session_ids, reissue the query on the expanded set and return the
// merged result. Any script/SQL failure is non-fatal — the handler falls
// back to the base rows and logs a warning.
func (h *SearchHandler) queryTransactionMessages(ctx context.Context, req *TransactionSessionRequestV4) ([]map[string]interface{}, error) {
multi := normalizeTransactionSessionIDs(req.SessionIDs)
if len(multi) == 0 {
if strings.TrimSpace(req.SessionID) == "" {
return nil, fmt.Errorf("session_id or non-empty session_ids is required")
}
multi = []string{strings.TrimSpace(req.SessionID)}
}
protoType := req.ProtoType
if protoType == 0 {
protoType = 1
}
eventType := req.EventType
if eventType == "" {
eventType = "call"
}
table := getTableName(h.flightService.LakeName(), protoType, eventType)
baseRows, err := h.executeTransactionMessagesSQL(ctx, table, multi, req.Timestamp.From, req.Timestamp.To)
if err != nil {
return nil, err
}
sortTransactionMessageRowsByTimestampAsc(baseRows)
if h.correlation == nil || !h.correlation.Has(protoType, eventType) {
return baseRows, nil
}
corrRes := h.correlation.Correlate(ctx, CorrelationInput{
HepID: protoType,
Profile: eventType,
ProtoType: protoType,
EventType: eventType,
BaseRows: baseRows,
SessionIDs: multi,
TimeFrom: req.Timestamp.From,
TimeTo: req.Timestamp.To,
})
if corrRes == nil || len(corrRes.ExtraSessionIDs) == 0 {
return baseRows, nil
}
expanded := mergeSessionIDs(multi, corrRes.ExtraSessionIDs)
if len(expanded) == len(multi) {
return baseRows, nil
}
expandedRows, err := h.executeTransactionMessagesSQL(ctx, table, expanded, req.Timestamp.From, req.Timestamp.To)
if err != nil {
// Fail-open: log and return base rows so a broken correlation path
// never manifests as a user-visible 500.
logger.Warn("V4TransactionMessages: correlated requery failed, returning base rows",
"err", err.Error(), "proto", protoType, "event", eventType)
return baseRows, nil
}
sortTransactionMessageRowsByTimestampAsc(expandedRows)
return expandedRows, nil
}
// transactionMessagesSelectSQL builds the SELECT used by POST /transactions/messages.
// Package tests assert OTLP trace/log tables filter on trace_id and apply a row cap.
func transactionMessagesSelectSQL(table string, sessionIDs []string, from, to int64) string {
var where string
switch {
case isOTLPTableCorrelatedByTraceID(table):
where = buildExactColumnMatchOrChain("trace_id", sessionIDs)
case isOTLPMetricsDuckLakeTable(table):
where = buildExactColumnMatchOrChain("name", sessionIDs)
default:
where = buildSessionIDMatchOrChain(sessionIDs)
}
if from > 0 && to > 0 {
where += fmt.Sprintf(" AND timestamp >= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC') AND timestamp <= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')",
from, to)
}
limit := ""
switch {
case isOTLPTracesDuckLakeTable(table):
limit = fmt.Sprintf(" LIMIT %d", maxOTLPTraceSpansPerQuery)
case isOTLPLogsDuckLakeTable(table):
limit = fmt.Sprintf(" LIMIT %d", maxOTLPLogsPerQuery)
case isOTLPMetricsDuckLakeTable(table):
limit = fmt.Sprintf(" LIMIT %d", maxOTLPMetricsPerQuery)
}
return fmt.Sprintf("SELECT * FROM %s WHERE %s ORDER BY timestamp ASC NULLS LAST%s", table, where, limit)
}
// executeTransactionMessagesSQL builds and runs the B2B-aware SELECT for a
// given session_id list. Broken out of queryTransactionMessages so the
// correlation second pass can reuse it without recursion.
func (h *SearchHandler) executeTransactionMessagesSQL(ctx context.Context, table string, sessionIDs []string, from, to int64) ([]map[string]interface{}, error) {
if len(sessionIDs) == 0 {
return nil, fmt.Errorf("no session_id provided")
}
sql := transactionMessagesSelectSQL(table, sessionIDs, from, to)
return h.flightService.Query(ctx, sql)
}
// mergeSessionIDs returns base ∪ extras with order preserved, whitespace
// trimmed and empty strings dropped. The returned slice is the cap-bounded
// input to the expanded SELECT (capped by buildSessionIDMatchOrChain).
func mergeSessionIDs(base, extras []string) []string {
seen := make(map[string]struct{}, len(base)+len(extras))
out := make([]string, 0, len(base)+len(extras))
for _, s := range base {
s = strings.TrimSpace(s)
if s == "" {
continue
}
if _, ok := seen[s]; ok {
continue
}
seen[s] = struct{}{}
out = append(out, s)
}
for _, s := range extras {
if len(out) >= maxTransactionSessionIDs {
break
}
s = strings.TrimSpace(s)
if s == "" {
continue
}
if _, ok := seen[s]; ok {
continue
}
seen[s] = struct{}{}
out = append(out, s)
}
return out
}
// sortTransactionMessageRowsByTimestampAsc orders messages for transaction view / API:
// oldest capture time first (ASC), null or unparseable timestamps last, stable tie-break on ids.
func sortTransactionMessageRowsByTimestampAsc(rows []map[string]interface{}) {
if len(rows) < 2 {
return
}
sort.SliceStable(rows, func(i, j int) bool {
ni := transactionRowSortNanos(rows[i])
nj := transactionRowSortNanos(rows[j])
if ni != nj {
return ni < nj
}
return transactionRowSortTie(rows[i]) < transactionRowSortTie(rows[j])
})
}
func transactionRowSortNanos(row map[string]interface{}) int64 {
for _, key := range []string{"timestamp", "time"} {
if t, ok := pcapwriter.RowTimeOptional(row, key); ok {
return t.UnixNano()
}
}
return math.MaxInt64
}
func transactionRowSortTie(row map[string]interface{}) string {
for _, k := range []string{"uuid", "span_id", "trace_id", "name"} {
if v, ok := row[k]; ok && v != nil {
s := strings.TrimSpace(fmt.Sprint(v))
if s != "" {
return s
}
}
}
return ""
}
func (h *SearchHandler) V4TransactionMessages(c echo.Context) error {
var req TransactionSessionRequestV4
if err := c.Bind(&req); err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", "Invalid request body")
}
results, err := h.queryTransactionMessages(c.Request().Context(), &req)
if err != nil {
if strings.Contains(err.Error(), "session_id") {
return writeError(c, http.StatusBadRequest, "Bad Request", err.Error())
}
return writeError(c, http.StatusInternalServerError, "Server Error", "Query failed")
}
h.enrichRowsWithIPAliases(c.Request().Context(), results)
resp := MessageListResponseV4{}
resp.Data.Items = results
resp.Meta = buildMeta(c, "")
return c.JSON(http.StatusOK, resp)
}
func (h *SearchHandler) V4MessageGet(c echo.Context) error {
var req MessageGetRequestV4
if err := c.Bind(&req); err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", "Invalid request body")
}
if strings.TrimSpace(req.UUID) == "" {
return writeError(c, http.StatusBadRequest, "Bad Request", "uuid is required")
}
protoType := req.ProtoType
if protoType == 0 {
protoType = 1
}
eventType := req.EventType
if eventType == "" {
eventType = "call"
}
table := getTableName(h.flightService.LakeName(), protoType, eventType)
where := fmt.Sprintf("uuid = '%s'", sqlvalidator.SafeString(req.UUID))
if req.Timestamp.From > 0 && req.Timestamp.To > 0 {
where += fmt.Sprintf(" AND timestamp >= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC') AND timestamp <= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')",
req.Timestamp.From, req.Timestamp.To)
}
sql := fmt.Sprintf("SELECT * FROM %s WHERE %s LIMIT 1", table, where)
results, err := h.flightService.Query(c.Request().Context(), sql)
if err != nil {
return writeError(c, http.StatusInternalServerError, "Server Error", "Query failed")
}
if len(results) == 0 {
return writeError(c, http.StatusNotFound, "Not Found", "Message not found")
}
h.enrichRowsWithIPAliases(c.Request().Context(), results)
resp := MessageResponseV4{
Data: results[0],
Meta: buildMeta(c, ""),
}
return c.JSON(http.StatusOK, resp)
}
func (h *SearchHandler) V4MessageDecoded(c echo.Context) error {
var req MessageGetRequestV4
if err := c.Bind(&req); err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", "Invalid request body")
}
if strings.TrimSpace(req.UUID) == "" {
return writeError(c, http.StatusBadRequest, "Bad Request", "uuid is required")
}
protoType := req.ProtoType
if protoType == 0 {
protoType = 1
}
eventType := req.EventType
if eventType == "" {
eventType = "call"
}
table := getTableName(h.flightService.LakeName(), protoType, eventType)
where := fmt.Sprintf("uuid = '%s'", sqlvalidator.SafeString(req.UUID))
if req.Timestamp.From > 0 && req.Timestamp.To > 0 {
where += fmt.Sprintf(" AND timestamp >= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC') AND timestamp <= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')",
req.Timestamp.From, req.Timestamp.To)
}
sql := fmt.Sprintf("SELECT * FROM %s WHERE %s LIMIT 1", table, where)
results, err := h.flightService.Query(c.Request().Context(), sql)
if err != nil {
return writeError(c, http.StatusInternalServerError, "Server Error", "Query failed")
}
decoded := make([]map[string]interface{}, 0)
if len(results) > 0 {
decoded = append(decoded, results[0])
}
h.enrichRowsWithIPAliases(c.Request().Context(), decoded)
resp := MessageDecodedResponseV4{}
resp.Data.Data = decoded
resp.Meta = buildMeta(c, "")
return c.JSON(http.StatusOK, resp)
}
func (h *SearchHandler) V4TransactionQos(c echo.Context) error {
var req TransactionSessionRequestV4
if err := c.Bind(&req); err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", "Invalid request body")
}
ids, err := resolvedSessionIDList(&req)
if err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", err.Error())
}
sidCondition := buildSessionIDMatchOrChain(ids)
tsCondition := ""
if req.Timestamp.From > 0 && req.Timestamp.To > 0 {
tsCondition = fmt.Sprintf(" AND timestamp >= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC') AND timestamp <= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')",
req.Timestamp.From, req.Timestamp.To)
}
rtcpTable := getTableName(h.flightService.LakeName(), 5, "default")
rtcpSQL := fmt.Sprintf(
"SELECT * FROM %s WHERE %s%s ORDER BY timestamp ASC",
rtcpTable, sidCondition, tsCondition,
)
rtcpResults, rtcpErr := h.flightService.Query(c.Request().Context(), rtcpSQL)
if rtcpErr != nil {
rtcpResults = []map[string]interface{}{}
}
h.enrichRowsWithIPAliases(c.Request().Context(), rtcpResults)
rtpTable := getTableName(h.flightService.LakeName(), 35, "default")
rtpSQL := fmt.Sprintf(
"SELECT * FROM %s WHERE %s%s ORDER BY timestamp ASC",
rtpTable, sidCondition, tsCondition,
)
rtpResults, rtpErr := h.flightService.Query(c.Request().Context(), rtpSQL)
if rtpErr != nil {
rtpResults = []map[string]interface{}{}
}
h.enrichRowsWithIPAliases(c.Request().Context(), rtpResults)
resp := QosResponseV4{
Data: map[string]interface{}{
"rtcp": map[string]interface{}{"data": rtcpResults},
"rtp": map[string]interface{}{"data": rtpResults},
},
Meta: buildMeta(c, ""),
}
return c.JSON(http.StatusOK, resp)
}
// V4TransactionCallInfo returns an aggregated summary for a call session.
// POST /api/v4/transactions/callinfo
func (h *SearchHandler) V4TransactionCallInfo(c echo.Context) error {
var req TransactionSessionRequestV4
if err := c.Bind(&req); err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", "Invalid request body")
}
ids, err := resolvedSessionIDList(&req)
if err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", err.Error())
}
protoType := req.ProtoType
if protoType == 0 {
protoType = 1
}
eventType := req.EventType
if eventType == "" {
eventType = "call"
}
sipEvent := strings.ToLower(strings.TrimSpace(eventType))
switch sipEvent {
case "calls":
sipEvent = "call"
case "registrations", "register":
sipEvent = "registration"
}
table := getTableName(h.flightService.LakeName(), protoType, eventType)
sessionWhere := buildSessionIDMatchOrChain(ids)
tsFilter := ""
if req.Timestamp.From > 0 && req.Timestamp.To > 0 {
tsFilter = fmt.Sprintf(
" AND timestamp >= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC') AND timestamp <= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')",
req.Timestamp.From, req.Timestamp.To,
)
}
var results []map[string]interface{}
if protoType == 1 && sipEvent == "call" {
detailSQL := fmt.Sprintf(
`SELECT session_id, timestamp, method, response_code, cseq_method, caller, callee,
src_ip, CAST(src_port AS VARCHAR) AS src_port, dst_ip, CAST(dst_port AS VARCHAR) AS dst_port,
payload, data_extra, uuid
FROM %s WHERE %s%s ORDER BY timestamp ASC LIMIT %d`,
table, sessionWhere, tsFilter, callInfoMaxRows,
)
rows, err := h.flightService.Query(c.Request().Context(), detailSQL)
if err != nil {
return writeError(c, http.StatusInternalServerError, "Server Error", "Query failed")
}
results = computeSIPCallInfoRows(rows)
if results == nil {
results = []map[string]interface{}{}
}
} else {
sql := fmt.Sprintf(`SELECT
session_id,
MAX(caller) AS caller,
MAX(callee) AS callee,
CAST(MIN(timestamp) AS VARCHAR) AS first_seen,
CAST(MAX(timestamp) AS VARCHAR) AS last_seen,
date_diff('second', MIN(timestamp), MAX(timestamp)) AS duration_sec,
COUNT(*) AS message_count,
string_agg(DISTINCT method, ', ' ORDER BY method) AS methods,
string_agg(DISTINCT CAST(response_code AS VARCHAR), ', ' ORDER BY response_code)
FILTER (WHERE response_code > 0) AS response_codes,
string_agg(DISTINCT src_ip, ', ') AS src_ips,
string_agg(DISTINCT dst_ip, ', ') AS dst_ips,
string_agg(DISTINCT CAST(node_id AS VARCHAR), ', ') AS nodes
FROM %s WHERE %s%s GROUP BY session_id`,
table, sessionWhere, tsFilter)
var err error
results, err = h.flightService.Query(c.Request().Context(), sql)
if err != nil {
return writeError(c, http.StatusInternalServerError, "Server Error", "Query failed")
}
}
resp := LogListResponseV4{}
resp.Data.Items = results
resp.Meta = buildMeta(c, "")
return c.JSON(http.StatusOK, resp)
}
// V4TransactionEvents returns application log rows (HEP proto 100) correlated to a session.
// POST /api/v4/transactions/events
func (h *SearchHandler) V4TransactionEvents(c echo.Context) error {
var req TransactionSessionRequestV4
if err := c.Bind(&req); err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", "Invalid request body")
}
ids, err := resolvedSessionIDList(&req)
if err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", err.Error())
}
table := getTableName(h.flightService.LakeName(), 100, "default")
where := buildSessionIDMatchOrChain(ids)
if req.Timestamp.From > 0 && req.Timestamp.To > 0 {
where += fmt.Sprintf(
" AND timestamp >= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC') AND timestamp <= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')",
req.Timestamp.From, req.Timestamp.To,
)
}
sql := fmt.Sprintf("SELECT * FROM %s WHERE %s ORDER BY timestamp ASC LIMIT 5000", table, where)
results, err := h.flightService.Query(c.Request().Context(), sql)
if err != nil {
return writeError(c, http.StatusInternalServerError, "Server Error", "Query failed")
}
resp := LogListResponseV4{}
resp.Data.Items = results
resp.Meta = buildMeta(c, "")
return c.JSON(http.StatusOK, resp)
}
// V4TransactionSub returns SIP messages from the default table (SUBSCRIBE/NOTIFY/OPTIONS)
// correlated to a session by Call-ID.
// POST /api/v4/transactions/sub
func (h *SearchHandler) V4TransactionSub(c echo.Context) error {
var req TransactionSessionRequestV4
if err := c.Bind(&req); err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", "Invalid request body")
}
ids, err := resolvedSessionIDList(&req)
if err != nil {
return writeError(c, http.StatusBadRequest, "Bad Request", err.Error())
}
table := getTableName(h.flightService.LakeName(), 1, "default")
where := buildSubMatchOrChain(ids)
if req.Timestamp.From > 0 && req.Timestamp.To > 0 {
where += fmt.Sprintf(
" AND timestamp >= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC') AND timestamp <= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')",
req.Timestamp.From, req.Timestamp.To,
)
}
sql := fmt.Sprintf(
"SELECT timestamp, src_ip, src_port, dst_ip, dst_port, method, response_code, caller, callee, node_id FROM %s WHERE %s ORDER BY timestamp ASC LIMIT 5000",
table, where,
)
results, err := h.flightService.Query(c.Request().Context(), sql)
if err != nil {
return writeError(c, http.StatusInternalServerError, "Server Error", "Query failed")
}
resp := LogListResponseV4{}
resp.Data.Items = results
resp.Meta = buildMeta(c, "")