-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
214 lines (174 loc) · 6.47 KB
/
main.go
File metadata and controls
214 lines (174 loc) · 6.47 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
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"time"
"f1sockets/api"
"f1sockets/auth"
"f1sockets/broadcaster"
"f1sockets/f1tvclient"
"f1sockets/handlers"
"f1sockets/metrics"
"f1sockets/model"
"f1sockets/ratelimiter"
"f1sockets/recorder"
"f1sockets/replayer"
"f1sockets/sessionmanager"
"f1sockets/valkeyclient"
"golang.org/x/time/rate"
)
const (
listenAddr = ":8080"
)
var (
globalState *model.GlobalState
customEventBroadcaster model.CustomEventBroadcaster
sessionEndedCount int
)
var (
RECORD_LOGS = true
autoConnect = false
valkeyAddr string
skippedFeedUpdates = 0
f1tvClient *f1tvclient.F1TVClient
browserBroadcaster *broadcaster.Broadcaster
sessionRecorder *recorder.Recorder
// Replay mode variables
replayFile string
replaySpeed float64
replayWaitClient bool
activeReplayer *replayer.Replayer
)
func init() {
flag.BoolVar(&autoConnect, "auto-connect", false, "Automatically connect/disconnect to F1TV based on session times")
flag.StringVar(&valkeyAddr, "valkey-addr", os.Getenv("VALKEY_ADDR"), "Address for the Valkey instance. If not set, Valkey is disabled. Can also be set via VALKEY_ADDR env var.")
flag.StringVar(&replayFile, "replay-file", "", "Path to recording file to replay. If set, backend runs in replay mode instead of Live F1.")
flag.Float64Var(&replaySpeed, "replay-speed", 1.0, "Playback speed multiplier for replay mode")
flag.BoolVar(&replayWaitClient, "replay-wait-client", true, "Wait for first client connection before starting replay playback")
}
func main() {
flag.Parse()
metrics.Init()
fmt.Printf("Starting F1TV SignalR Proxy on %s\n", listenAddr)
connectionLimiter := ratelimiter.NewConnectionLimiter(100)
sessionRecorder = recorder.NewRecorder(2*time.Second, func() *model.GlobalState {
return globalState
}, RECORD_LOGS)
sessionRecorder.Start()
defer sessionRecorder.Stop()
browserBroadcaster = broadcaster.NewBroadcaster(connectionLimiter, sessionRecorder)
customEventBroadcaster = model.NewCustomEventBroadcaster(browserBroadcaster.Broadcast)
var valkey *valkeyclient.ValkeyClient
if valkeyAddr != "" {
fmt.Printf("Valkey integration enabled, connecting to %s\n", valkeyAddr)
valkey = valkeyclient.NewValkeyClient(valkeyAddr)
auth.SetValkeyClient(valkey)
}
seasonLoader := api.NewSeasonLoader(24*time.Hour, valkey)
seasonLoader.Start()
defer seasonLoader.Stop()
fmt.Println("Waiting for initial season data to load...")
seasonLoader.WaitUntilReady()
fmt.Println("Season data loaded.")
messageHandlers := handlers.NewMessageHandlers(&globalState, customEventBroadcaster, browserBroadcaster, f1tvClient, &skippedFeedUpdates)
f1tvClient = f1tvclient.NewF1TVClient(messageHandlers.HandleNewStreamMessage, messageHandlers.HandleLegacyStreamMessage)
if replayFile != "" {
fmt.Printf("Replay mode enabled. Replaying from %s\n", replayFile)
onReplayMessage := func(payload []byte) {
if len(payload) > 0 && payload[0] == '[' {
messageHandlers.HandleNewStreamMessage(payload)
} else {
messageHandlers.HandleLegacyStreamMessage(payload)
}
}
activeReplayer = replayer.NewReplayer(replayFile, replaySpeed, replayWaitClient, onReplayMessage)
go activeReplayer.Start()
} else if autoConnect {
manager := sessionmanager.NewManager(f1tvClient, seasonLoader, valkey, &globalState, customEventBroadcaster, sessionRecorder)
manager.Start()
} else {
fmt.Println("Auto-connect mode disabled. F1TV client starting immediately.")
f1tvClient.Start()
defer f1tvClient.Stop()
}
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
if globalState == nil {
globalState = model.NewEmptyGlobalState()
globalState.Broadcaster = customEventBroadcaster
}
initialState, err := globalState.GetStateAsJSON()
if err != nil {
fmt.Printf("Error retrieving initial global state: %v\n", err)
initialState = nil
}
browserBroadcaster.HandleConnections(w, r, initialState)
if activeReplayer != nil {
activeReplayer.NotifyFirstClient()
}
})
http.Handle("/state", metrics.InstrumentHandler(http.HandlerFunc(handleState)))
http.Handle("/season", metrics.InstrumentHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
schedule := seasonLoader.GetSeasonSchedule()
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
if len(schedule.Events) == 0 {
w.WriteHeader(http.StatusServiceUnavailable)
json.NewEncoder(w).Encode(map[string]string{"message": "Season data not yet available or failed to load."})
return
}
err := json.NewEncoder(w).Encode(schedule)
if err != nil {
fmt.Printf("Error encoding season schedule JSON: %v\n", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
})))
http.Handle("/recordings", metrics.InstrumentHandler(http.HandlerFunc(api.HandleRecordings)))
limiter := ratelimiter.NewIPRateLimiter(rate.Every(time.Minute), 15)
fileHandler := http.StripPrefix("/recordings/", api.RecordingsFileHandler())
http.Handle("/recordings/", metrics.InstrumentHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := ratelimiter.GetClientIP(r)
if !limiter.GetLimiter(ip).Allow() {
http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
return
}
fileHandler.ServeHTTP(w, r)
})))
http.Handle("/track/", metrics.InstrumentHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := ratelimiter.GetClientIP(r)
if !limiter.GetLimiter(ip).Allow() {
http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
return
}
api.HandleTrack(w, r)
})))
err := http.ListenAndServe(listenAddr, nil)
if err != nil {
fmt.Printf("HTTP server failed: %v\n", err)
}
}
func handleState(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
state := globalState
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
if state == nil {
w.WriteHeader(http.StatusServiceUnavailable)
json.NewEncoder(w).Encode(map[string]string{"message": "Driver data not yet available"})
return
}
err := json.NewEncoder(w).Encode(state)
if err != nil {
fmt.Printf("Error encoding driver list JSON: %v\n", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}