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
|
// Package transport - Multi-transport failover for war zones
package transport
import (
"fmt"
"net"
"sync"
"time"
)
// FailoverTransport implements automatic failover between multiple transports
// Critical for war zones: Tor → Mesh → Bluetooth → Direct
type FailoverTransport struct {
transports []Transport // Ordered list of transports to try
currentIndex int // Currently active transport
mu sync.RWMutex
healthCheck map[TransportType]time.Time // Last successful connection
retryInterval time.Duration
maxRetries int
onFailover func(from, to TransportType) // Callback when failing over
}
// FailoverConfig holds failover configuration
type FailoverConfig struct {
RetryInterval time.Duration // Time between retry attempts
MaxRetries int // Max retries per transport before failing over
HealthCheckInterval time.Duration // How often to health check transports
}
// NewFailoverTransport creates a new failover transport
func NewFailoverTransport(transports []Transport, config *FailoverConfig) *FailoverTransport {
if config == nil {
config = &FailoverConfig{
RetryInterval: 5 * time.Second,
MaxRetries: 3,
HealthCheckInterval: 30 * time.Second,
}
}
ft := &FailoverTransport{
transports: transports,
currentIndex: 0,
healthCheck: make(map[TransportType]time.Time),
retryInterval: config.RetryInterval,
maxRetries: config.MaxRetries,
}
// Start health checking
go ft.healthCheckLoop(config.HealthCheckInterval)
return ft
}
// Connect attempts to connect using transports in priority order
func (ft *FailoverTransport) Connect(address string) (net.Conn, error) {
// Try each transport in order
for attempt := 0; attempt < len(ft.transports)*ft.maxRetries; attempt++ {
ft.mu.Lock()
index := ft.currentIndex
transport := ft.transports[index]
ft.mu.Unlock()
transportType := transport.Type()
// Attempt connection
conn, err := transport.Connect(address)
if err == nil {
// Success!
ft.mu.Lock()
ft.healthCheck[transportType] = time.Now()
ft.mu.Unlock()
fmt.Printf("✓ Connected via %s\n", transportType)
return conn, nil
}
fmt.Printf("✗ %s connection failed: %v\n", transportType, err)
// Move to next transport
ft.mu.Lock()
oldIndex := ft.currentIndex
ft.currentIndex = (ft.currentIndex + 1) % len(ft.transports)
newTransport := ft.transports[ft.currentIndex]
ft.mu.Unlock()
// Notify failover
if ft.onFailover != nil && oldIndex != ft.currentIndex {
go ft.onFailover(transport.Type(), newTransport.Type())
}
// Wait before retry
time.Sleep(ft.retryInterval)
}
return nil, fmt.Errorf("all transports failed after %d attempts", len(ft.transports)*ft.maxRetries)
}
// Listen starts listening on the highest priority available transport
func (ft *FailoverTransport) Listen(address string) (net.Listener, error) {
ft.mu.RLock()
defer ft.mu.RUnlock()
// Try each transport
for _, transport := range ft.transports {
listener, err := transport.Listen(address)
if err == nil {
fmt.Printf("✓ Listening on %s\n", transport.Type())
return listener, nil
}
fmt.Printf("✗ Listen failed on %s: %v\n", transport.Type(), err)
}
return nil, fmt.Errorf("all transports failed to listen")
}
// Type returns the currently active transport type
func (ft *FailoverTransport) Type() TransportType {
ft.mu.RLock()
defer ft.mu.RUnlock()
if ft.currentIndex < len(ft.transports) {
return ft.transports[ft.currentIndex].Type()
}
return TransportType(-1)
}
// Close closes all transports
func (ft *FailoverTransport) Close() error {
ft.mu.Lock()
defer ft.mu.Unlock()
var lastErr error
for _, transport := range ft.transports {
if err := transport.Close(); err != nil {
lastErr = err
}
}
return lastErr
}
// GetCurrentTransport returns the currently active transport
func (ft *FailoverTransport) GetCurrentTransport() Transport {
ft.mu.RLock()
defer ft.mu.RUnlock()
if ft.currentIndex < len(ft.transports) {
return ft.transports[ft.currentIndex]
}
return nil
}
// GetTransports returns all available transports
func (ft *FailoverTransport) GetTransports() []Transport {
ft.mu.RLock()
defer ft.mu.RUnlock()
return ft.transports
}
// SetTransportPriority reorders transports by priority
func (ft *FailoverTransport) SetTransportPriority(types []TransportType) error {
ft.mu.Lock()
defer ft.mu.Unlock()
if len(types) != len(ft.transports) {
return fmt.Errorf("priority list length mismatch")
}
// Create new ordered list
newTransports := make([]Transport, 0, len(ft.transports))
for _, targetType := range types {
found := false
for _, transport := range ft.transports {
if transport.Type() == targetType {
newTransports = append(newTransports, transport)
found = true
break
}
}
if !found {
return fmt.Errorf("transport type %s not found", targetType)
}
}
ft.transports = newTransports
ft.currentIndex = 0
return nil
}
// healthCheckLoop periodically checks transport health
func (ft *FailoverTransport) healthCheckLoop(interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
ft.performHealthCheck()
}
}
// performHealthCheck checks if current transport is still healthy
func (ft *FailoverTransport) performHealthCheck() {
ft.mu.RLock()
current := ft.transports[ft.currentIndex]
lastSuccess, exists := ft.healthCheck[current.Type()]
ft.mu.RUnlock()
// If no successful connection in last 5 minutes, try next transport
if !exists || time.Since(lastSuccess) > 5*time.Minute {
ft.mu.Lock()
oldIndex := ft.currentIndex
ft.currentIndex = (ft.currentIndex + 1) % len(ft.transports)
ft.mu.Unlock()
if ft.onFailover != nil && oldIndex != ft.currentIndex {
ft.mu.RLock()
go ft.onFailover(ft.transports[oldIndex].Type(), ft.transports[ft.currentIndex].Type())
ft.mu.RUnlock()
}
}
}
// SetOnFailover sets callback for failover events
func (ft *FailoverTransport) SetOnFailover(callback func(from, to TransportType)) {
ft.mu.Lock()
defer ft.mu.Unlock()
ft.onFailover = callback
}
// GetHealthStatus returns health status of all transports
func (ft *FailoverTransport) GetHealthStatus() map[TransportType]time.Time {
ft.mu.RLock()
defer ft.mu.RUnlock()
status := make(map[TransportType]time.Time)
for k, v := range ft.healthCheck {
status[k] = v
}
return status
}
// String returns a string representation
func (ft *FailoverTransport) String() string {
ft.mu.RLock()
defer ft.mu.RUnlock()
currentType := "none"
if ft.currentIndex < len(ft.transports) {
currentType = ft.transports[ft.currentIndex].Type().String()
}
return fmt.Sprintf("FailoverTransport(current=%s, transports=%d)",
currentType, len(ft.transports))
}
// ConnectWithRetry attempts connection with exponential backoff
func (ft *FailoverTransport) ConnectWithRetry(address string, maxAttempts int) (net.Conn, error) {
var conn net.Conn
var err error
backoff := 1 * time.Second
for attempt := 1; attempt <= maxAttempts; attempt++ {
conn, err = ft.Connect(address)
if err == nil {
return conn, nil
}
fmt.Printf("Attempt %d/%d failed, retrying in %v...\n", attempt, maxAttempts, backoff)
time.Sleep(backoff)
// Exponential backoff with jitter
backoff *= 2
if backoff > 60*time.Second {
backoff = 60 * time.Second
}
}
return nil, fmt.Errorf("failed after %d attempts: %w", maxAttempts, err)
}
|