-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
5533 lines (4672 loc) · 234 KB
/
coverage.html
File metadata and controls
5533 lines (4672 loc) · 234 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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>distributed: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">digital.vasic.translator/pkg/distributed/coordinator.go (42.5%)</option>
<option value="file1">digital.vasic.translator/pkg/distributed/fallback.go (85.7%)</option>
<option value="file2">digital.vasic.translator/pkg/distributed/manager.go (72.0%)</option>
<option value="file3">digital.vasic.translator/pkg/distributed/pairing.go (40.2%)</option>
<option value="file4">digital.vasic.translator/pkg/distributed/performance.go (69.7%)</option>
<option value="file5">digital.vasic.translator/pkg/distributed/performance_test_extended.go (0.0%)</option>
<option value="file6">digital.vasic.translator/pkg/distributed/security.go (61.7%)</option>
<option value="file7">digital.vasic.translator/pkg/distributed/ssh_pool.go (50.4%)</option>
<option value="file8">digital.vasic.translator/pkg/distributed/version_manager.go (26.2%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">no coverage</span>
<span class="cov1">low coverage</span>
<span class="cov2">*</span>
<span class="cov3">*</span>
<span class="cov4">*</span>
<span class="cov5">*</span>
<span class="cov6">*</span>
<span class="cov7">*</span>
<span class="cov8">*</span>
<span class="cov9">*</span>
<span class="cov10">high coverage</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package distributed
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"digital.vasic.translator/pkg/deployment"
"digital.vasic.translator/pkg/events"
"digital.vasic.translator/pkg/translator"
"digital.vasic.translator/pkg/translator/llm"
)
// RemoteLLMInstance represents a remote LLM instance
type RemoteLLMInstance struct {
ID string
WorkerID string
Provider string
Model string
Priority int
Available bool
LastUsed time.Time
mu sync.Mutex
}
// DistributedCoordinator manages distributed LLM instances across remote workers
type DistributedCoordinator struct {
localCoordinator interface{} // Will be *coordination.MultiLLMCoordinator
remoteInstances []*RemoteLLMInstance
sshPool *SSHPool
pairingManager *PairingManager
fallbackManager *FallbackManager
versionManager *VersionManager
eventBus *events.EventBus
apiLogger *deployment.APICommunicationLogger
currentIndex int
maxRetries int
retryDelay time.Duration
mu sync.RWMutex
}
// NewDistributedCoordinator creates a new distributed coordinator
func NewDistributedCoordinator(
localCoordinator interface{},
sshPool *SSHPool,
pairingManager *PairingManager,
fallbackManager *FallbackManager,
versionManager *VersionManager,
eventBus *events.EventBus,
apiLogger *deployment.APICommunicationLogger,
) *DistributedCoordinator <span class="cov10" title="64">{
return &DistributedCoordinator{
localCoordinator: localCoordinator,
remoteInstances: make([]*RemoteLLMInstance, 0),
sshPool: sshPool,
pairingManager: pairingManager,
fallbackManager: fallbackManager,
versionManager: versionManager,
eventBus: eventBus,
apiLogger: apiLogger,
currentIndex: 0,
maxRetries: 3,
retryDelay: 2 * time.Second,
}
}</span>
// DiscoverRemoteInstances discovers LLM instances on paired remote workers
func (dc *DistributedCoordinator) DiscoverRemoteInstances(ctx context.Context) error <span class="cov1" title="1">{
pairedServices := dc.pairingManager.GetPairedServices()
dc.mu.Lock()
defer dc.mu.Unlock()
// Clear existing remote instances
dc.remoteInstances = make([]*RemoteLLMInstance, 0)
instanceID := 1
for workerID, service := range pairedServices </span><span class="cov0" title="0">{
// Query remote service for available providers
providers, err := dc.queryRemoteProviders(ctx, service)
if err != nil </span><span class="cov0" title="0">{
dc.emitWarning(fmt.Sprintf("Failed to query providers from worker %s: %v", workerID, err))
continue</span>
}
// Create instances based on provider capabilities
<span class="cov0" title="0">for provider, config := range providers </span><span class="cov0" title="0">{
// Determine priority based on provider type
priority := dc.getPriorityForProvider(provider)
// Get first model from models array, or use provider name as fallback
model := provider // default
if models, ok := config["models"].([]interface{}); ok && len(models) > 0 </span><span class="cov0" title="0">{
if firstModel, ok := models[0].(string); ok </span><span class="cov0" title="0">{
model = firstModel
}</span>
}
// Create multiple instances based on priority
<span class="cov0" title="0">instanceCount := dc.getInstanceCountForPriority(priority, service.Capabilities.MaxConcurrent)
for i := 0; i < instanceCount; i++ </span><span class="cov0" title="0">{
instance := &RemoteLLMInstance{
ID: fmt.Sprintf("remote-%s-%d", provider, instanceID),
WorkerID: workerID,
Provider: provider,
Model: model,
Priority: priority,
Available: true,
LastUsed: time.Time{},
}
dc.remoteInstances = append(dc.remoteInstances, instance)
instanceID++
}</span>
}
}
<span class="cov0" title="0">dc.emitEvent(events.Event{
Type: "distributed_instances_discovered",
SessionID: "system",
Message: fmt.Sprintf("Discovered %d remote LLM instances across %d workers", len(dc.remoteInstances), len(pairedServices)),
Data: map[string]interface{}{
"remote_instances": len(dc.remoteInstances),
"workers": len(pairedServices),
},
})
return nil</span>
}
// queryRemoteProviders queries a remote service for available providers
func (dc *DistributedCoordinator) queryRemoteProviders(ctx context.Context, service *RemoteService) (map[string]map[string]interface{}, error) <span class="cov1" title="1">{
url := fmt.Sprintf("%s://%s:%d/api/v1/providers", service.Protocol, service.Host, service.Port)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
// Log outgoing request if logger is available
<span class="cov1" title="1">var logEntry *deployment.APICommunicationLog
if dc.apiLogger != nil </span><span class="cov1" title="1">{
logEntry = dc.apiLogger.LogRequest(service.Host, 8443, service.Host, service.Port, "GET", "/api/v1/providers", 0)
}</span>
// Use HTTP client that accepts self-signed certificates
<span class="cov1" title="1">client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
startTime := time.Now()
resp, err := client.Do(req)
duration := time.Since(startTime)
if err != nil </span><span class="cov1" title="1">{
// Log failed response if logger is available
if dc.apiLogger != nil && logEntry != nil </span><span class="cov1" title="1">{
dc.apiLogger.LogResponse(logEntry, 0, 0, duration, err)
}</span>
<span class="cov1" title="1">return nil, err</span>
}
<span class="cov0" title="0">defer resp.Body.Close()
// Read response body
body, err := io.ReadAll(resp.Body)
if err != nil </span><span class="cov0" title="0">{
// Log failed response if logger is available
if dc.apiLogger != nil && logEntry != nil </span><span class="cov0" title="0">{
dc.apiLogger.LogResponse(logEntry, resp.StatusCode, 0, duration, err)
}</span>
<span class="cov0" title="0">return nil, err</span>
}
// Log successful response if logger is available
<span class="cov0" title="0">if dc.apiLogger != nil && logEntry != nil </span><span class="cov0" title="0">{
dc.apiLogger.LogResponse(logEntry, resp.StatusCode, int64(len(body)), duration, nil)
}</span>
<span class="cov0" title="0">if resp.StatusCode != http.StatusOK </span><span class="cov0" title="0">{
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
}</span>
<span class="cov0" title="0">var response map[string]interface{}
if err := json.Unmarshal(body, &response); err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">providers := make(map[string]map[string]interface{})
// Extract providers from response - handle both array and map formats
if providersList, ok := response["providers"].([]interface{}); ok </span><span class="cov0" title="0">{
// Array format: [{"name": "ollama", "models": [...], ...}, ...]
for _, item := range providersList </span><span class="cov0" title="0">{
if providerMap, ok := item.(map[string]interface{}); ok </span><span class="cov0" title="0">{
if name, ok := providerMap["name"].(string); ok </span><span class="cov0" title="0">{
providers[name] = providerMap
}</span>
}
}
} else<span class="cov0" title="0"> if providersMap, ok := response["providers"].(map[string]interface{}); ok </span><span class="cov0" title="0">{
// Map format: {"ollama": {...}, ...}
for provider, config := range providersMap </span><span class="cov0" title="0">{
if configMap, ok := config.(map[string]interface{}); ok </span><span class="cov0" title="0">{
providers[provider] = configMap
}</span>
}
}
<span class="cov0" title="0">return providers, nil</span>
}
// getPriorityForProvider determines priority based on provider type
func (dc *DistributedCoordinator) getPriorityForProvider(provider string) int <span class="cov5" title="7">{
switch provider </span>{
case "openai", "anthropic", "zhipu", "deepseek":<span class="cov4" title="4">
return 10</span> // API key providers - highest priority
case "ollama", "llamacpp":<span class="cov2" title="2">
return 5</span> // Local LLM providers - medium priority
default:<span class="cov1" title="1">
return 1</span> // Default priority
}
}
// getInstanceCountForPriority determines how many instances to create based on priority and max concurrent
func (dc *DistributedCoordinator) getInstanceCountForPriority(priority int, maxConcurrent int) int <span class="cov4" title="4">{
baseCount := 1
switch </span>{
case priority >= 10:<span class="cov2" title="2"> // API key providers
baseCount = 3</span>
case priority >= 5:<span class="cov1" title="1"> // OAuth providers
baseCount = 2</span>
default:<span class="cov1" title="1"> // Free/local providers
baseCount = 1</span>
}
// Don't exceed max concurrent capacity
<span class="cov4" title="4">if baseCount > maxConcurrent </span><span class="cov1" title="1">{
baseCount = maxConcurrent
}</span>
<span class="cov4" title="4">return baseCount</span>
}
// TranslateWithDistributedRetry translates using distributed instances with comprehensive fallback
func (dc *DistributedCoordinator) TranslateWithDistributedRetry(
ctx context.Context,
text string,
contextHint string,
) (string, error) <span class="cov1" title="1">{
var result string
var resultMu sync.Mutex
// Define fallback strategies
fallbacks := []FallbackStrategy{
{
Name: "remote_instances",
Function: func() error </span><span class="cov4" title="4">{
translated, err := dc.translateWithRemoteInstances(ctx, text, contextHint)
if err != nil </span><span class="cov4" title="4">{
return err
}</span>
<span class="cov0" title="0">resultMu.Lock()
result = translated
resultMu.Unlock()
return nil</span>
},
Priority: 1,
},
{
Name: "local_coordinator",
Function: func() error <span class="cov4" title="4">{
// Use local translation as fallback
// Create a simple local translator using available providers
config := translator.TranslationConfig{
SourceLang: "auto",
TargetLang: "en", // Default to English for fallback
Provider: "openai",
Model: "gpt-3.5-turbo",
}
localTranslator, err := llm.NewLLMTranslator(config)
if err != nil </span><span class="cov4" title="4">{
// Try with a different provider
config.Provider = "anthropic"
config.Model = "claude-3-haiku-20240307"
localTranslator, err = llm.NewLLMTranslator(config)
if err != nil </span><span class="cov4" title="4">{
return fmt.Errorf("failed to create local fallback translator: %w", err)
}</span>
}
<span class="cov0" title="0">translated, err := localTranslator.Translate(ctx, text, contextHint)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("local fallback translation failed: %w", err)
}</span>
<span class="cov0" title="0">resultMu.Lock()
result = translated
resultMu.Unlock()
return nil</span>
},
Priority: 2,
},
{
Name: "reduced_quality",
Function: func() error <span class="cov1" title="1">{
// Implement reduced quality fallback using basic word replacement
// This is a very simple translation for emergency fallback
fallbackTranslations := map[string]string{
"hello": "hola",
"goodbye": "adiós",
"thank you": "gracias",
"please": "por favor",
"sorry": "lo siento",
"yes": "sí",
"no": "no",
"good": "bueno",
"bad": "malo",
"big": "grande",
"small": "pequeño",
"hot": "caliente",
"cold": "frío",
"day": "día",
"night": "noche",
"water": "agua",
"food": "comida",
"house": "casa",
"car": "coche",
"book": "libro",
"computer": "computadora",
}
// Simple word-by-word replacement
words := strings.Fields(strings.ToLower(text))
var translatedWords []string
for _, word := range words </span><span class="cov2" title="2">{
if translation, exists := fallbackTranslations[word]; exists </span><span class="cov1" title="1">{
translatedWords = append(translatedWords, translation)
}</span> else<span class="cov1" title="1"> {
// Keep original word if no translation available
translatedWords = append(translatedWords, word)
}</span>
}
<span class="cov1" title="1">result := strings.Join(translatedWords, " ")
resultMu.Lock()
result = result
resultMu.Unlock()
return nil</span>
},
Priority: 3,
},
}
// Use FallbackManager for comprehensive fallback handling
<span class="cov1" title="1">componentID := "distributed_translator"
err := dc.fallbackManager.ExecuteWithFallback(ctx, componentID, func() error </span><span class="cov4" title="4">{
translated, err := dc.translateWithRemoteInstances(ctx, text, contextHint)
if err != nil </span><span class="cov4" title="4">{
return err
}</span>
<span class="cov0" title="0">resultMu.Lock()
result = translated
resultMu.Unlock()
return nil</span>
}, fallbacks...)
<span class="cov1" title="1">resultMu.Lock()
finalResult := result
resultMu.Unlock()
if err != nil </span><span class="cov0" title="0">{
return "", err
}</span>
<span class="cov1" title="1">return finalResult, nil</span>
}
// translateWithRemoteInstances attempts translation using remote instances
func (dc *DistributedCoordinator) translateWithRemoteInstances(
ctx context.Context,
text string,
contextHint string,
) (string, error) <span class="cov5" title="9">{
if len(dc.remoteInstances) == 0 </span><span class="cov5" title="9">{
return "", fmt.Errorf("no remote instances available")
}</span>
<span class="cov0" title="0">var lastErr error
triedInstances := make(map[string]bool)
for attempt := 0; attempt < dc.maxRetries*len(dc.remoteInstances); attempt++ </span><span class="cov0" title="0">{
instance := dc.getNextRemoteInstance()
if instance == nil </span><span class="cov0" title="0">{
break</span>
}
<span class="cov0" title="0">if triedInstances[instance.ID] </span><span class="cov0" title="0">{
continue</span>
}
<span class="cov0" title="0">triedInstances[instance.ID] = true
// Validate worker version before attempting translation
if err := dc.validateWorkerForWork(ctx, instance.WorkerID); err != nil </span><span class="cov0" title="0">{
dc.emitWarning(fmt.Sprintf("Worker %s validation failed: %v", instance.WorkerID, err))
continue</span>
}
<span class="cov0" title="0">dc.emitEvent(events.Event{
Type: "distributed_translation_attempt",
SessionID: "system",
Message: fmt.Sprintf("Attempting distributed translation with %s on worker %s", instance.ID, instance.WorkerID),
Data: map[string]interface{}{
"instance_id": instance.ID,
"worker_id": instance.WorkerID,
"provider": instance.Provider,
"attempt": attempt + 1,
},
})
result, err := dc.translateWithRemoteInstance(ctx, instance, text, contextHint)
if err == nil && result != "" </span><span class="cov0" title="0">{
instance.LastUsed = time.Now()
dc.emitEvent(events.Event{
Type: "distributed_translation_success",
SessionID: "system",
Message: fmt.Sprintf("Distributed translation successful with %s", instance.ID),
Data: map[string]interface{}{
"instance_id": instance.ID,
"worker_id": instance.WorkerID,
},
})
return result, nil
}</span>
<span class="cov0" title="0">lastErr = err
dc.emitWarning(fmt.Sprintf("Distributed translation attempt %d failed: %v", attempt+1, err))</span>
}
<span class="cov0" title="0">return "", fmt.Errorf("all distributed translation attempts failed, last error: %w", lastErr)</span>
}
// validateWorkerForWork validates that a worker is ready for work
func (dc *DistributedCoordinator) validateWorkerForWork(ctx context.Context, workerID string) error <span class="cov1" title="1">{
if dc.versionManager == nil </span><span class="cov1" title="1">{
// Version manager not available, skip validation
return nil
}</span>
// Get the service for this worker
<span class="cov0" title="0">services := dc.pairingManager.GetPairedServices()
service, exists := services[workerID]
if !exists </span><span class="cov0" title="0">{
return fmt.Errorf("worker %s not found in paired services", workerID)
}</span>
// Validate worker version and health
<span class="cov0" title="0">return dc.versionManager.ValidateWorkerForWork(ctx, service)</span>
}
// getNextRemoteInstance returns the next remote instance in round-robin fashion
func (dc *DistributedCoordinator) getNextRemoteInstance() *RemoteLLMInstance <span class="cov4" title="5">{
dc.mu.Lock()
defer dc.mu.Unlock()
if len(dc.remoteInstances) == 0 </span><span class="cov1" title="1">{
return nil
}</span>
// Use round-robin selection
<span class="cov4" title="4">instance := dc.remoteInstances[dc.currentIndex]
dc.currentIndex = (dc.currentIndex + 1) % len(dc.remoteInstances)
return instance</span>
}
// translateWithRemoteInstance performs translation using a specific remote instance
func (dc *DistributedCoordinator) translateWithRemoteInstance(
ctx context.Context,
instance *RemoteLLMInstance,
text string,
contextHint string,
) (string, error) <span class="cov1" title="1">{
// Get the service for this worker
services := dc.pairingManager.GetPairedServices()
service, exists := services[instance.WorkerID]
if !exists </span><span class="cov0" title="0">{
return "", fmt.Errorf("service not found for worker %s", instance.WorkerID)
}</span>
// Prepare translation request
<span class="cov0" title="0">translateURL := fmt.Sprintf("%s://%s:%d/api/v1/translate", service.Protocol, service.Host, service.Port)
requestBody := map[string]interface{}{
"text": text,
"context_hint": contextHint,
"provider": instance.Provider,
"model": instance.Model,
}
jsonData, err := json.Marshal(requestBody)
if err != nil </span><span class="cov0" title="0">{
return "", fmt.Errorf("failed to marshal request: %w", err)
}</span>
<span class="cov0" title="0">req, err := http.NewRequestWithContext(ctx, "POST", translateURL, strings.NewReader(string(jsonData)))
if err != nil </span><span class="cov0" title="0">{
return "", fmt.Errorf("failed to create request: %w", err)
}</span>
<span class="cov0" title="0">req.Header.Set("Content-Type", "application/json")
// Log outgoing request
var logEntry *deployment.APICommunicationLog
if dc.apiLogger != nil </span><span class="cov0" title="0">{
logEntry = dc.apiLogger.LogRequest(service.Host, 8443, service.Host, service.Port, "POST", "/api/v1/translate", int64(len(jsonData)))
}</span>
// Use HTTP client that accepts self-signed certificates
<span class="cov0" title="0">client := &http.Client{
Timeout: 60 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
startTime := time.Now()
resp, err := client.Do(req)
duration := time.Since(startTime)
if err != nil </span><span class="cov0" title="0">{
// Log failed response
if dc.apiLogger != nil && logEntry != nil </span><span class="cov0" title="0">{
dc.apiLogger.LogResponse(logEntry, 0, 0, duration, err)
}</span>
<span class="cov0" title="0">return "", fmt.Errorf("translation request failed: %w", err)</span>
}
<span class="cov0" title="0">defer resp.Body.Close()
// Read response body
body, err := io.ReadAll(resp.Body)
if err != nil </span><span class="cov0" title="0">{
// Log failed response
if dc.apiLogger != nil && logEntry != nil </span><span class="cov0" title="0">{
dc.apiLogger.LogResponse(logEntry, resp.StatusCode, 0, duration, err)
}</span>
<span class="cov0" title="0">return "", fmt.Errorf("failed to read response: %w", err)</span>
}
// Log successful response
<span class="cov0" title="0">if dc.apiLogger != nil && logEntry != nil </span><span class="cov0" title="0">{
dc.apiLogger.LogResponse(logEntry, resp.StatusCode, int64(len(body)), duration, nil)
}</span>
<span class="cov0" title="0">if resp.StatusCode != http.StatusOK </span><span class="cov0" title="0">{
return "", fmt.Errorf("translation failed with status %d: %s", resp.StatusCode, string(body))
}</span>
// Parse response
<span class="cov0" title="0">var response map[string]interface{}
if err := json.Unmarshal(body, &response); err != nil </span><span class="cov0" title="0">{
return "", fmt.Errorf("failed to parse response: %w", err)
}</span>
// Extract translated text
<span class="cov0" title="0">translated, ok := response["translated_text"].(string)
if !ok </span><span class="cov0" title="0">{
return "", fmt.Errorf("invalid response format: missing translated_text")
}</span>
<span class="cov0" title="0">return translated, nil</span>
}
// GetRemoteInstanceCount returns the number of remote instances
func (dc *DistributedCoordinator) GetRemoteInstanceCount() int <span class="cov4" title="4">{
dc.mu.RLock()
defer dc.mu.RUnlock()
return len(dc.remoteInstances)
}</span>
// emitEvent emits an event if event bus is available
func (dc *DistributedCoordinator) emitEvent(event events.Event) <span class="cov1" title="1">{
if dc.eventBus != nil </span><span class="cov1" title="1">{
dc.eventBus.Publish(event)
}</span>
}
// emitWarning emits a warning event
func (dc *DistributedCoordinator) emitWarning(message string) <span class="cov1" title="1">{
if dc.eventBus != nil </span><span class="cov1" title="1">{
dc.eventBus.Publish(events.Event{
Type: "distributed_warning",
SessionID: "system",
Message: message,
})
}</span>
}
</pre>
<pre class="file" id="file1" style="display: none">package distributed
import (
"context"
"fmt"
"sync"
"time"
"digital.vasic.translator/pkg/events"
)
// FallbackConfig holds fallback and recovery configuration
type FallbackConfig struct {
// Graceful Degradation
EnableGracefulDegradation bool
DegradationThreshold float64 // Percentage of failed requests before degrading
// Retry Configuration
MaxRetries int
RetryBackoffBase time.Duration
RetryBackoffMax time.Duration
RetryJitter bool
// Timeout Configuration
RequestTimeout time.Duration
ConnectionTimeout time.Duration
HealthCheckTimeout time.Duration
// Recovery Configuration
RecoveryCheckInterval time.Duration
RecoverySuccessThreshold int
RecoveryWindow time.Duration
// Fallback Strategies
EnableLocalFallback bool
EnableReducedQuality bool
EnableCachingFallback bool
// Monitoring
FailureTrackingWindow time.Duration
AlertThreshold float64
}
// DefaultFallbackConfig returns secure default fallback configuration
func DefaultFallbackConfig() *FallbackConfig <span class="cov10" title="63">{
return &FallbackConfig{
EnableGracefulDegradation: true,
DegradationThreshold: 0.5, // 50% failure rate triggers degradation
MaxRetries: 3,
RetryBackoffBase: 100 * time.Millisecond,
RetryBackoffMax: 30 * time.Second,
RetryJitter: true,
RequestTimeout: 30 * time.Second,
ConnectionTimeout: 10 * time.Second,
HealthCheckTimeout: 5 * time.Second,
RecoveryCheckInterval: 10 * time.Second,
RecoverySuccessThreshold: 3,
RecoveryWindow: 60 * time.Second,
EnableLocalFallback: true,
EnableReducedQuality: true,
EnableCachingFallback: true,
FailureTrackingWindow: 5 * time.Minute,
AlertThreshold: 0.8, // 80% failure rate triggers alerts
}
}</span>
// FallbackManager manages fallback and recovery strategies
type FallbackManager struct {
config *FallbackConfig
performance *PerformanceConfig
eventBus EventBusInterface
logger Logger
// State tracking
failureCounts map[string]*FailureTracker
recoveryState map[string]*RecoveryTracker
degradedMode bool
mu sync.RWMutex
}
// FailureTracker tracks failures for a component
type FailureTracker struct {
ComponentID string
Failures int
TotalRequests int
LastFailure time.Time
WindowStart time.Time
mu sync.Mutex
}
// RecoveryTracker tracks recovery progress
type RecoveryTracker struct {
ComponentID string
ConsecutiveSuccesses int
LastSuccess time.Time
InRecovery bool
mu sync.Mutex
}
// NewFallbackManager creates a new fallback manager
func NewFallbackManager(config *FallbackConfig, performance *PerformanceConfig, eventBus EventBusInterface, logger Logger) *FallbackManager <span class="cov9" title="62">{
fm := &FallbackManager{
config: config,
performance: performance,
eventBus: eventBus,
logger: logger,
failureCounts: make(map[string]*FailureTracker),
recoveryState: make(map[string]*RecoveryTracker),
degradedMode: false,
}
// Only start monitoring goroutines if not in test environment
// In tests, goroutines would cause issues with zero intervals
if config != nil && config.RecoveryCheckInterval > 0 </span><span class="cov9" title="52">{
go fm.monitorFailures()
go fm.monitorRecovery()
}</span>
<span class="cov9" title="62">return fm</span>
}
// ExecuteWithFallback executes a function with comprehensive fallback strategies
func (fm *FallbackManager) ExecuteWithFallback(ctx context.Context, componentID string, operation func() error, fallbacks ...FallbackStrategy) error <span class="cov7" title="20">{
// Track the operation
startTime := time.Now()
defer fm.trackOperation(componentID, startTime)
// Try primary operation with retries
err := fm.executeWithRetries(ctx, operation)
if err == nil </span><span class="cov4" title="4">{
fm.recordSuccess(componentID)
return nil
}</span>
<span class="cov7" title="16">fm.recordFailure(componentID, err)
// Try fallback strategies
for _, fallback := range fallbacks </span><span class="cov4" title="5">{
if fm.shouldExecuteFallback(fallback) </span><span class="cov4" title="5">{
fm.logger.Log("info", "Executing fallback strategy", map[string]interface{}{
"component_id": componentID,
"strategy": fallback.Name,
"error": err.Error(),
})
fallbackErr := fm.executeWithRetries(ctx, fallback.Function)
if fallbackErr == nil </span><span class="cov2" title="2">{
fm.emitEvent(events.Event{
Type: "distributed_fallback_success",
SessionID: "system",
Message: fmt.Sprintf("Fallback strategy '%s' succeeded for %s", fallback.Name, componentID),
Data: map[string]interface{}{
"component_id": componentID,
"strategy": fallback.Name,
"duration": time.Since(startTime),
},
})
return nil
}</span>
<span class="cov3" title="3">fm.logger.Log("warning", "Fallback strategy failed", map[string]interface{}{
"component_id": componentID,
"strategy": fallback.Name,
"error": fallbackErr.Error(),
})</span>
}
}
// All strategies failed
<span class="cov6" title="14">fm.emitEvent(events.Event{
Type: "distributed_all_fallbacks_failed",
SessionID: "system",
Message: fmt.Sprintf("All fallback strategies failed for %s", componentID),
Data: map[string]interface{}{
"component_id": componentID,
"error": err.Error(),
"duration": time.Since(startTime),
},
})
return fmt.Errorf("all operations and fallbacks failed for %s: %w", componentID, err)</span>
}
// FallbackStrategy represents a fallback strategy
type FallbackStrategy struct {
Name string
Function func() error
Priority int // Lower number = higher priority
}
// executeWithRetries executes a function with retry logic
func (fm *FallbackManager) executeWithRetries(ctx context.Context, operation func() error) error <span class="cov7" title="25">{
var lastErr error
for attempt := 0; attempt <= fm.config.MaxRetries; attempt++ </span><span class="cov9" title="48">{
// Check if context is cancelled
select </span>{
case <-ctx.Done():<span class="cov1" title="1">
return ctx.Err()</span>
default:<span class="cov9" title="47"></span>
}
// Execute operation with timeout
<span class="cov9" title="47">opCtx, cancel := context.WithTimeout(ctx, fm.config.RequestTimeout)
done := make(chan error, 1)
go func() </span><span class="cov9" title="47">{
done <- operation()
}</span>()
<span class="cov9" title="47">select </span>{
case err := <-done:<span class="cov9" title="47">
cancel()
if err == nil </span><span class="cov4" title="6">{
return nil
}</span>
<span class="cov9" title="41">lastErr = err</span>
case <-opCtx.Done():<span class="cov0" title="0">
cancel()
lastErr = opCtx.Err()</span>
}
// Don't retry on context cancellation
<span class="cov9" title="41">if ctx.Err() != nil </span><span class="cov0" title="0">{
return ctx.Err()
}</span>
// Calculate backoff delay
<span class="cov9" title="41">if attempt < fm.config.MaxRetries </span><span class="cov7" title="23">{
delay := fm.calculateBackoff(attempt)
select </span>{
case <-time.After(delay):<span class="cov7" title="23"></span>
case <-ctx.Done():<span class="cov0" title="0">
return ctx.Err()</span>
}
}
}
<span class="cov7" title="18">return lastErr</span>
}
// calculateBackoff calculates exponential backoff delay
func (fm *FallbackManager) calculateBackoff(attempt int) time.Duration <span class="cov8" title="28">{
delay := time.Duration(attempt+1) * fm.config.RetryBackoffBase
// Apply exponential backoff
if attempt > 0 </span><span class="cov7" title="19">{
multiplier := 1
for i := 0; i < attempt-1; i++ </span><span class="cov7" title="19">{
multiplier *= 2
}</span>
<span class="cov7" title="19">delay = time.Duration(float64(delay) * float64(multiplier))</span>
}
// Cap at maximum
<span class="cov8" title="28">if delay > fm.config.RetryBackoffMax </span><span class="cov1" title="1">{
delay = fm.config.RetryBackoffMax
}</span>
// Add jitter if enabled
<span class="cov8" title="28">if fm.config.RetryJitter </span><span class="cov7" title="21">{
delay = time.Duration(float64(delay) * (0.5 + 0.5*float64(time.Now().UnixNano()%1000)/1000))
}</span>
<span class="cov8" title="28">return delay</span>
}
// shouldExecuteFallback determines if a fallback should be executed
func (fm *FallbackManager) shouldExecuteFallback(fallback FallbackStrategy) bool <span class="cov6" title="11">{
fm.mu.RLock()
defer fm.mu.RUnlock()
// In degraded mode, execute all fallbacks
if fm.degradedMode </span><span class="cov4" title="6">{
return true
}</span>
// Check if fallback is enabled in config
<span class="cov4" title="5">switch fallback.Name </span>{
case "local_fallback":<span class="cov2" title="2">
return fm.config.EnableLocalFallback</span>
case "reduced_quality":<span class="cov1" title="1">
return fm.config.EnableReducedQuality</span>