This repository was archived by the owner on Dec 30, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearcher.go
More file actions
1456 lines (1203 loc) · 38.4 KB
/
searcher.go
File metadata and controls
1456 lines (1203 loc) · 38.4 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
package stuber
import (
"errors"
"fmt"
"iter"
"maps"
"sort"
"strings"
"sync"
"sync/atomic"
"unicode"
"github.com/google/uuid"
)
// PriorityMultiplier is used to boost stub priority in ranking calculations.
// Higher values give more weight to explicit priority settings.
const PriorityMultiplier = 10.0
// Specificity calculation constants.
const (
// EmptySpecificity is returned when no fields match.
EmptySpecificity = 0
// MinStreamLength is the minimum length for stream calculations.
MinStreamLength = 0
// defaultStubCapacity is the default capacity for stub slices.
defaultStubCapacity = 16
// parallelProcessingThreshold is the threshold for using parallel processing.
parallelProcessingThreshold = 100
)
// ErrServiceNotFound is returned when the service is not found.
var ErrServiceNotFound = errors.New("service not found")
// ErrMethodNotFound is returned when the method is not found.
var ErrMethodNotFound = errors.New("method not found")
// ErrStubNotFound is returned when the stub is not found.
var ErrStubNotFound = errors.New("stub not found")
// searcher is a struct that manages the storage of search results.
//
// It contains a mutex for concurrent access, a map to store and retrieve
// used stubs by their UUID, and a pointer to the storage struct.
type searcher struct {
mu sync.RWMutex // mutex for concurrent access
stubUsed map[uuid.UUID]struct{}
// map to store and retrieve used stubs by their UUID
storage *storage // pointer to the storage struct
// V2 optimization: pool for temporary slices to reduce allocations
v2Pool sync.Pool // Pool for temporary slices to reduce allocations
// Additional pools for memory optimization
stubPool sync.Pool // Pool for Stub objects
inputDataPool sync.Pool // Pool for InputData objects
}
// newSearcher creates a new instance of the searcher struct.
//
// It initializes the stubUsed map and the storage pointer.
//
// Returns a pointer to the newly created searcher struct.
func newSearcher() *searcher {
s := &searcher{
storage: newStorage(),
stubUsed: make(map[uuid.UUID]struct{}),
}
// Initialize sync.Pool for temporary slices
s.v2Pool.New = func() any {
return make([]*Stub, 0, defaultStubCapacity) // Pre-allocate with reasonable capacity
}
// Initialize sync.Pool for Stub objects
s.stubPool.New = func() any {
return &Stub{
Headers: InputHeader{},
Input: InputData{},
Output: Output{},
}
}
// Initialize sync.Pool for InputData objects
s.inputDataPool.New = func() any {
return InputData{
Equals: make(map[string]any),
Contains: make(map[string]any),
Matches: make(map[string]any),
}
}
return s
}
// Result represents the result of a search operation.
//
// It contains two fields: found and similar. Found represents the exact
// match found in the search, while similar represents the most similar match
// found.
type Result struct {
found *Stub // The exact match found in the search
similar *Stub // The most similar match found
}
// Found returns the exact match found in the search.
//
// Returns a pointer to the Stub struct representing the found match.
func (r *Result) Found() *Stub {
return r.found
}
// Similar returns the most similar match found in the search.
//
// Returns a pointer to the Stub struct representing the similar match.
func (r *Result) Similar() *Stub {
return r.similar
}
// BidiResult represents the result of a bidirectional streaming search operation.
// For bidirectional streaming, we maintain a list of matching stubs and filter them as messages arrive.
type BidiResult struct {
searcher *searcher
query QueryBidi
matchingStubs []*Stub // Stubs that match the current message pattern
messageCount atomic.Int32 // Number of messages processed so far
mu sync.RWMutex // Thread safety for concurrent access
}
// Next processes the next message in the bidirectional stream and returns the matching stub.
//
//nolint:gocognit,cyclop,funlen
func (br *BidiResult) Next(messageData map[string]any) (*Stub, error) {
br.mu.Lock()
defer br.mu.Unlock()
// Validate input
if messageData == nil {
return nil, ErrStubNotFound
}
// If this is the first call, initialize matching stubs
if len(br.matchingStubs) == 0 {
// Get all stubs for this service/method
allStubs, err := br.searcher.findBy(br.query.Service, br.query.Method)
if err != nil {
return nil, ErrStubNotFound
}
// Find stubs that match the first message
for _, stub := range allStubs {
if br.stubMatchesMessage(stub, messageData) {
br.matchingStubs = append(br.matchingStubs, stub)
}
}
} else {
// Advance message index first for current message processing
br.messageCount.Add(1)
// Filter existing matching stubs - remove those that don't match the new message
var filteredStubs []*Stub
for _, stub := range br.matchingStubs {
if br.stubMatchesMessage(stub, messageData) {
filteredStubs = append(filteredStubs, stub)
}
}
br.matchingStubs = filteredStubs
}
// If no matching stubs remain, return error
if len(br.matchingStubs) == 0 {
return nil, ErrStubNotFound
}
// Find the best matching stub among candidates
var (
bestStub *Stub
bestRank float64
candidatesWithSameRank []*Stub
)
messageIndex := int(br.messageCount.Load())
for _, stub := range br.matchingStubs {
// For bidirectional streaming, rank based on the specific message index
var rank float64
if stub.IsBidirectional() && len(stub.Inputs) > 0 {
// Check if we have a stream element for this message index
if messageIndex < len(stub.Inputs) {
streamElement := stub.Inputs[messageIndex]
rank = br.rankInputData(streamElement, messageData)
} else {
// Message index out of bounds - very low rank
rank = 0.1
}
} else {
// For other types, use the old ranking method
query := QueryV2{
Service: br.query.Service,
Method: br.query.Method,
Headers: br.query.Headers,
Input: []map[string]any{messageData},
toggles: br.query.toggles,
}
rank = br.rankStub(stub, query)
}
// Add priority to ranking with higher multiplier
priorityBonus := float64(stub.Priority) * PriorityMultiplier
totalRank := rank + priorityBonus
if totalRank > bestRank {
bestStub = stub
bestRank = totalRank
candidatesWithSameRank = []*Stub{stub}
} else if totalRank == bestRank {
// Collect candidates with same rank for stable sorting
candidatesWithSameRank = append(candidatesWithSameRank, stub)
}
}
// If we have multiple candidates with same rank, sort by ID for stability
if len(candidatesWithSameRank) > 1 {
sortStubsByID(candidatesWithSameRank)
bestStub = candidatesWithSameRank[0]
}
if bestStub != nil {
// Mark the stub as used
query := QueryV2{
Service: br.query.Service,
Method: br.query.Method,
Headers: br.query.Headers,
Input: []map[string]any{messageData},
toggles: br.query.toggles,
}
// For non-client streaming calls (unary or pure server-stream), reset state after the first message.
// Do NOT reset for client-streaming or bidirectional streaming, where message index must advance.
if !bestStub.IsClientStream() && br.messageCount.Load() == 0 {
br.matchingStubs = br.matchingStubs[:0]
br.messageCount.Store(0)
}
br.searcher.markV2(query, bestStub.ID)
return bestStub, nil
}
return nil, ErrStubNotFound
}
// GetMessageIndex returns the current message index in the bidirectional stream.
func (br *BidiResult) GetMessageIndex() int {
return int(br.messageCount.Load())
}
// stubMatchesMessage checks if a stub matches the given message.
// For bidirectional streaming, we check if the message matches any of the stream elements.
func (br *BidiResult) stubMatchesMessage(stub *Stub, messageData map[string]any) bool {
// For bidirectional streaming stubs, check if message matches any stream element
if stub.IsBidirectional() {
// New format: use Inputs for input matching
if len(stub.Inputs) > 0 {
for _, streamElement := range stub.Inputs {
if br.matchInputData(streamElement, messageData) {
return true
}
}
return false
}
// Old format: use Input for matching (backward compatibility)
return br.matchInputData(stub.Input, messageData)
}
// For client streaming stubs, check if message matches any stream element
if stub.IsClientStream() {
for _, streamElement := range stub.Inputs {
if br.matchInputData(streamElement, messageData) {
return true
}
}
return false
}
// For unary stubs, use Input matching
if stub.IsUnary() {
return br.matchInputData(stub.Input, messageData)
}
// For server streaming stubs, use Input matching
if stub.IsServerStream() {
return br.matchInputData(stub.Input, messageData)
}
return false
}
// rankInputData ranks how well messageData matches the given InputData.
//
//nolint:cyclop
func (br *BidiResult) rankInputData(inputData InputData, messageData map[string]any) float64 {
// Early exit if InputData is empty
if len(inputData.Equals) == 0 && len(inputData.Contains) == 0 && len(inputData.Matches) == 0 {
return 1.0 // Perfect match for empty matchers
}
var totalRank float64
// Rank Equals - each match gives high weight
if len(inputData.Equals) > 0 {
equalsRank := 0.0
for key, expectedValue := range inputData.Equals {
if actualValue, exists := br.findValueWithVariations(messageData, key); exists && deepEqual(actualValue, expectedValue) {
equalsRank += 100.0 // High weight for exact matches
}
}
totalRank += equalsRank
}
// Rank Contains - each match gives medium weight
if len(inputData.Contains) > 0 {
containsRank := 0.0
for key, expectedValue := range inputData.Contains {
actualValue, exists := messageData[key]
if exists {
// Create minimal map for contains check
tempMap := map[string]any{key: expectedValue}
if contains(tempMap, actualValue, false) {
containsRank += 10.0 // Medium weight for contains matches
}
}
}
totalRank += containsRank
}
// Rank Matches - each match gives medium weight
if len(inputData.Matches) > 0 {
matchesRank := 0.0
for key, expectedValue := range inputData.Matches {
actualValue, exists := messageData[key]
if exists {
// Create minimal map for matches check
tempMap := map[string]any{key: expectedValue}
if matches(tempMap, actualValue, false) {
matchesRank += 10.0 // Medium weight for matches
}
}
}
totalRank += matchesRank
}
return totalRank
}
// matchInputData checks if messageData matches the given InputData.
//
//nolint:cyclop
func (br *BidiResult) matchInputData(inputData InputData, messageData map[string]any) bool {
// Early exit if InputData is empty
if len(inputData.Equals) == 0 && len(inputData.Contains) == 0 && len(inputData.Matches) == 0 {
return true
}
// Check Equals
if len(inputData.Equals) > 0 {
for key, expectedValue := range inputData.Equals {
if actualValue, exists := br.findValueWithVariations(messageData, key); !exists || !deepEqual(actualValue, expectedValue) {
return false
}
}
}
// Check Contains - avoid creating temporary maps
if len(inputData.Contains) > 0 {
for key, expectedValue := range inputData.Contains {
actualValue, exists := messageData[key]
if !exists {
return false
}
// Create minimal map for contains check
tempMap := map[string]any{key: expectedValue}
if !contains(tempMap, actualValue, false) {
return false
}
}
}
// Check Matches - avoid creating temporary maps
if len(inputData.Matches) > 0 {
for key, expectedValue := range inputData.Matches {
actualValue, exists := messageData[key]
if !exists {
return false
}
// Create minimal map for matches check
tempMap := map[string]any{key: expectedValue}
if !matches(tempMap, actualValue, false) {
return false
}
}
}
return true
}
// findValueWithVariations tries to find a value using different field name conventions.
func (br *BidiResult) findValueWithVariations(messageData map[string]any, key string) (any, bool) {
// Try exact match first
if value, exists := messageData[key]; exists {
return value, true
}
// Try camelCase variations
camelKey := toCamelCase(key)
if value, exists := messageData[camelKey]; exists {
return value, true
}
// Try snake_case variations
snakeKey := toSnakeCase(key)
if value, exists := messageData[snakeKey]; exists {
return value, true
}
return nil, false
}
// toCamelCase converts snake_case to camelCase.
func toCamelCase(s string) string {
parts := strings.Split(s, "_")
if len(parts) == 1 {
return s
}
result := parts[0]
for i := 1; i < len(parts); i++ {
if len(parts[i]) > 0 {
result += strings.ToUpper(parts[i][:1]) + parts[i][1:]
}
}
return result
}
// toSnakeCase converts camelCase to snake_case.
func toSnakeCase(s string) string {
if s == "" {
return ""
}
var result strings.Builder
for i, r := range s {
if i > 0 && unicode.IsUpper(r) {
result.WriteByte('_')
}
result.WriteRune(unicode.ToLower(r))
}
return result.String()
}
// deepEqual performs deep equality check with better implementation.
//
//nolint:cyclop,gocognit,nestif
func deepEqual(a, b any) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
// Try direct comparison first (only for comparable types)
switch a.(type) {
case string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool:
return a == b
}
// For maps, compare keys and values
if aMap, aOk := a.(map[string]any); aOk {
if bMap, bOk := b.(map[string]any); bOk {
if len(aMap) != len(bMap) {
return false
}
for k, v := range aMap {
if bv, exists := bMap[k]; !exists || !deepEqual(v, bv) {
return false
}
}
return true
}
}
// For slices, compare elements
if aSlice, aOk := a.([]any); aOk {
if bSlice, bOk := b.([]any); bOk {
if len(aSlice) != len(bSlice) {
return false
}
for i, v := range aSlice {
if !deepEqual(v, bSlice[i]) {
return false
}
}
return true
}
}
// Fallback to string comparison
return fmt.Sprintf("%v", a) == fmt.Sprintf("%v", b)
}
// sortStubsByID sorts stubs by ID for stable ordering when ranks are equal
// This ensures consistent results across multiple runs.
func sortStubsByID(stubs []*Stub) {
sort.Slice(stubs, func(i, j int) bool {
// Compare UUIDs directly for better performance
return stubs[i].ID.String() < stubs[j].ID.String()
})
}
// rankStub calculates the ranking score for a stub.
func (br *BidiResult) rankStub(stub *Stub, query QueryV2) float64 {
// Use the existing V2 ranking logic
// Rank headers first
headersRank := rankHeaders(query.Headers, stub.Headers)
// Priority to Inputs (newer functionality) over Input (legacy)
if len(stub.Inputs) > 0 {
// Streaming case
return headersRank + rankStreamElements(query.Input, stub.Inputs)
}
// Handle Input (legacy) - check if query has input data
if len(query.Input) == 0 {
// Empty query - return header rank only
return headersRank
}
if len(query.Input) == 1 {
// Unary case
return headersRank + rankInput(query.Input[0], stub.Input)
}
return headersRank
}
// upsert inserts the given stub values into the searcher. If a stub value
// already exists with the same key, it is updated.
//
// The function returns a slice of UUIDs representing the keys of the
// inserted or updated values.
func (s *searcher) upsert(values ...*Stub) []uuid.UUID {
return s.storage.upsert(s.castToValue(values)...)
}
// del deletes the stub values with the given UUIDs from the searcher.
//
// Returns the number of stub values that were successfully deleted.
func (s *searcher) del(ids ...uuid.UUID) int {
return s.storage.del(ids...)
}
// findByID retrieves the stub value associated with the given ID from the
// searcher.
//
// Returns a pointer to the Stub struct associated with the given ID, or nil
// if not found.
func (s *searcher) findByID(id uuid.UUID) *Stub {
if v, ok := s.storage.findByID(id).(*Stub); ok {
return v
}
return nil
}
// findBy retrieves all Stub values that match the given service and method
// from the searcher, sorted by score in descending order.
func (s *searcher) findBy(service, method string) ([]*Stub, error) {
seq, err := s.storage.findAll(service, method)
if err != nil {
return nil, s.wrap(err)
}
return collectStubs(seq), nil
}
// clear resets the searcher.
//
// It clears the stubUsed map and calls the storage clear method.
func (s *searcher) clear() {
s.mu.Lock()
defer s.mu.Unlock()
// Clear the stubUsed map.
s.stubUsed = make(map[uuid.UUID]struct{})
// Clear the storage.
s.storage.clear()
}
// all returns all Stub values stored in the searcher.
//
// Returns:
// - []*Stub: The Stub values stored in the searcher.
func (s *searcher) all() []*Stub {
return collectStubs(s.storage.values())
}
// used returns all Stub values that have been used by the searcher.
//
// Returns:
// - []*Stub: The Stub values that have been used by the searcher.
func (s *searcher) used() []*Stub {
s.mu.RLock()
defer s.mu.RUnlock()
return collectStubs(s.storage.findByIDs(maps.Keys(s.stubUsed)))
}
// unused returns all Stub values that have not been used by the searcher.
//
// Returns:
// - []*Stub: The Stub values that have not been used by the searcher.
func (s *searcher) unused() []*Stub {
s.mu.RLock()
defer s.mu.RUnlock()
unused := make([]*Stub, 0)
for stub := range s.iterAll() {
if _, exists := s.stubUsed[stub.ID]; !exists {
unused = append(unused, stub)
}
}
return unused
}
// searchCommon is a common search function that can be used by both search and searchV2.
func (s *searcher) searchCommon(
service, method string,
matchFunc func(*Stub) bool,
rankFunc func(*Stub) float64,
markFunc func(uuid.UUID),
) (*Result, error) {
var (
found *Stub
foundRank float64
similar *Stub
similarRank float64
)
seq, err := s.storage.findAll(service, method)
if err != nil {
return nil, s.wrap(err)
}
// Collect all stubs first for stable sorting
stubs := make([]*Stub, 0)
for v := range seq {
stub, ok := v.(*Stub)
if !ok {
continue
}
stubs = append(stubs, stub)
}
// Sort stubs by ID for stable ordering when ranks are equal
sortStubsByID(stubs)
// Process stubs in sorted order
for _, stub := range stubs {
current := rankFunc(stub)
// Add priority to ranking with higher multiplier
priorityBonus := float64(stub.Priority) * PriorityMultiplier
totalRank := current + priorityBonus
// For exact matches, prefer the one with higher rank
if matchFunc(stub) {
if totalRank > foundRank {
found, foundRank = stub, totalRank
}
} else {
if totalRank > similarRank {
// For similar matches, also track the best one
similar, similarRank = stub, totalRank
}
}
}
if found != nil {
markFunc(found.ID)
return &Result{found: found}, nil
}
if similar != nil {
return &Result{similar: similar}, nil
}
return nil, ErrStubNotFound
}
// find retrieves the Stub value associated with the given Query from the searcher.
//
// Parameters:
// - query: The Query used to search for a Stub value.
//
// Returns:
// - *Result: The Result containing the found Stub value (if any), or nil.
// - error: An error if the search fails.
func (s *searcher) find(query Query) (*Result, error) {
// Check if the Query has an ID field.
if query.ID != nil {
// Search for the Stub value with the given ID.
return s.searchByID(query)
}
// Search for the Stub value with the given service and method.
return s.search(query)
}
// searchByID retrieves the Stub value associated with the given ID from the searcher.
//
// Parameters:
// - query: The Query used to search for a Stub value.
//
// Returns:
// - *Result: The Result containing the found Stub value (if any), or nil.
// - error: An error if the search fails.
func (s *searcher) searchByID(query Query) (*Result, error) {
// Check if the given service and method are valid.
_, err := s.storage.posByPN(query.Service, query.Method)
if err != nil {
return nil, s.wrap(err)
}
// Search for the Stub value with the given ID.
if found := s.findByID(*query.ID); found != nil {
// Mark the Stub value as used.
s.mark(query, *query.ID)
// Return the found Stub value.
return &Result{found: found}, nil
}
// Return an error if the Stub value is not found.
return nil, ErrServiceNotFound
}
// search retrieves the Stub value associated with the given Query from the searcher.
//
// Parameters:
// - query: The Query used to search for a Stub value.
//
// Returns:
// - *Result: The Result containing the found Stub value (if any), or nil.
// - error: An error if the search fails.
func (s *searcher) search(query Query) (*Result, error) {
return s.searchCommon(query.Service, query.Method,
func(stub *Stub) bool { return match(query, stub) },
func(stub *Stub) float64 { return rankMatch(query, stub) },
func(id uuid.UUID) { s.mark(query, id) })
}
// mark marks the given Stub value as used in the searcher.
//
// If the query's RequestInternal flag is set, the mark is skipped.
//
// Parameters:
// - query: The query used to mark the Stub value.
// - id: The UUID of the Stub value to mark.
func (s *searcher) mark(query Query, id uuid.UUID) {
// If the query's RequestInternal flag is set, skip the mark.
if query.RequestInternal() {
return
}
// Lock the mutex to ensure concurrent access.
s.mu.Lock()
defer s.mu.Unlock()
// Mark the Stub value as used by adding it to the stubUsed map.
s.stubUsed[id] = struct{}{}
}
// findV2 retrieves the Stub value associated with the given QueryV2 from the searcher.
func (s *searcher) findV2(query QueryV2) (*Result, error) {
// Check if the QueryV2 has an ID field
if query.ID != nil {
// Search for the Stub value with the given ID
return s.searchByIDV2(query)
}
// Search for the Stub value with the given service and method
return s.searchV2(query)
}
// searchByIDV2 retrieves the Stub value associated with the given ID from the searcher.
func (s *searcher) searchByIDV2(query QueryV2) (*Result, error) {
// Check if the given service and method are valid
_, err := s.storage.posByPN(query.Service, query.Method)
if err != nil {
return nil, s.wrap(err)
}
// Search for the Stub value with the given ID
if found := s.findByID(*query.ID); found != nil {
// Mark the Stub value as used
s.markV2(query, *query.ID)
// Return the found Stub value
return &Result{found: found}, nil
}
// Return an error if the Stub value is not found
return nil, ErrServiceNotFound
}
// findBidi retrieves a BidiResult for bidirectional streaming with the given QueryBidi.
// For bidirectional streaming, each message is treated as a separate unary request.
func (s *searcher) findBidi(query QueryBidi) (*BidiResult, error) {
// Check if the QueryBidi has an ID field
if query.ID != nil {
// For ID-based queries, we can't use bidirectional streaming - fallback to regular search
return s.searchByIDBidi(query)
}
// Check if the given service and method are valid
_, err := s.storage.posByPN(query.Service, query.Method)
if err != nil {
return nil, s.wrap(err)
}
// Fetch all stubs for this service/method
seq, err := s.storage.findAll(query.Service, query.Method)
if err != nil {
return nil, s.wrap(err)
}
var allStubs []*Stub
for v := range seq {
if stub, ok := v.(*Stub); ok {
allStubs = append(allStubs, stub)
}
}
return &BidiResult{
searcher: s,
query: query,
matchingStubs: make([]*Stub, 0),
}, nil
}
// searchByIDBidi handles ID-based queries for bidirectional streaming.
// Since we can't use bidirectional streaming for ID-based queries, we fallback to regular search.
func (s *searcher) searchByIDBidi(query QueryBidi) (*BidiResult, error) {
// Check if the given service and method are valid
_, err := s.storage.posByPN(query.Service, query.Method)
if err != nil {
return nil, s.wrap(err)
}
// Search for the Stub value with the given ID
if found := s.findByID(*query.ID); found != nil {
return &BidiResult{
searcher: s,
query: query,
matchingStubs: []*Stub{found},
}, nil
}
// Return an error if the Stub value is not found
return nil, ErrServiceNotFound
}
// searchV2 retrieves the Stub value associated with the given QueryV2 from the searcher.
func (s *searcher) searchV2(query QueryV2) (*Result, error) {
return s.searchV2Optimized(query)
}
// searchV2Optimized performs ultra-fast search with minimal allocations.
func (s *searcher) searchV2Optimized(query QueryV2) (*Result, error) {
// Get stubs from storage (single call - optimized)
seq, err := s.storage.findAll(query.Service, query.Method)
if err != nil {
return nil, s.wrap(err)
}
// Collect all stubs in a single pass
var stubs []*Stub
for v := range seq {
if stub, ok := v.(*Stub); ok {
stubs = append(stubs, stub)
}
}
// Process collected stubs
return s.processStubs(query, stubs)
}
// processStubs processes the collected stubs with ultra-fast paths.
func (s *searcher) processStubs(query QueryV2, stubs []*Stub) (*Result, error) {
if len(stubs) == 0 {
return nil, ErrStubNotFound
}
if len(stubs) == 1 {
stub := stubs[0]
if s.fastMatchV2(query, stub) {
s.markV2(query, stub.ID)
return &Result{found: stub}, nil
}
return &Result{similar: stub}, nil
}
// Parallel processing for multiple stubs
if len(stubs) >= parallelProcessingThreshold {
return s.processStubsParallel(query, stubs)
}
// Single-threaded processing for small sets
return s.processStubsSequential(query, stubs)
}
// processStubsSequential processes stubs sequentially (original logic).
func (s *searcher) processStubsSequential(query QueryV2, stubs []*Stub) (*Result, error) {
var (
bestMatch *Stub
bestScore float64
bestSpecificity int
mostSimilar *Stub
highestRank float64
)
for _, stub := range stubs {
rank := s.fastRankV2(query, stub)
priorityBonus := float64(stub.Priority) * PriorityMultiplier
specificity := s.calcSpecificity(stub, query)
totalScore := rank + priorityBonus
if s.fastMatchV2(query, stub) {
if specificity > bestSpecificity || (specificity == bestSpecificity && totalScore > bestScore) {
bestMatch, bestScore, bestSpecificity = stub, totalScore, specificity
}
}
if totalScore > highestRank { // Track most similar even if not exact match
mostSimilar, highestRank = stub, totalScore
}
}
if bestMatch != nil {
s.markV2(query, bestMatch.ID)
return &Result{found: bestMatch}, nil
}
if mostSimilar != nil {
return &Result{similar: mostSimilar}, nil
}
return nil, ErrStubNotFound
}
// processStubsParallel processes stubs in parallel using goroutines.
//
//nolint:gocognit,cyclop,funlen
func (s *searcher) processStubsParallel(query QueryV2, stubs []*Stub) (*Result, error) {
const chunkSize = 50 // Process stubs in chunks of 50
numChunks := (len(stubs) + chunkSize - 1) / chunkSize