Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
354 lines (329 loc) · 9.13 KB
/
Copy pathmain.go
File metadata and controls
354 lines (329 loc) · 9.13 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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"math/rand"
"net"
"net/http"
"sync/atomic"
"time"
sentry "github.com/getsentry/sentry-go"
sentryhttp "github.com/getsentry/sentry-go/http"
"github.com/mattrobenolt/go-eventsource"
)
var (
flagHost = flag.String("host", "127.0.0.1", "listen addr")
flagHttpPort = flag.Int("http-port", 7000, "http port")
flagUdpPort = flag.Int("udp-port", 5556, "udp port")
flagTest = flag.Bool("test", false, "send test events")
flagSampleRate = flag.Float64("sample-rate", 1.0, "fraction of UDP events eligible to forward (0.0–1.0); applied before max-forward-rate")
flagMaxForwardRate = flag.Float64("max-forward-rate", 50, "max events/sec to forward to SSE clients (0 = unlimited)")
)
// ingestStats tracks UDP receive/forward counters for /stats.
var ingestStats struct {
received atomic.Uint64
forwarded atomic.Uint64
dropped atomic.Uint64
}
func handleHealth(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}
func handleStats(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"udp_received": ingestStats.received.Load(),
"udp_forwarded": ingestStats.forwarded.Load(),
"udp_dropped": ingestStats.dropped.Load(),
"sample_rate": *flagSampleRate,
"max_forward_rate": *flagMaxForwardRate,
})
}
func runTest(port int) {
conn, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
dst := &net.UDPAddr{
IP: net.ParseIP("127.0.0.1"),
Port: port,
}
// Platform weights reflect real-world Sentry SDK distribution.
// TODO: fetch dynamically from https://release-registry.services.sentry.io/sdks
platforms := [...]string{
"javascript",
"javascript",
"javascript",
"node",
"node",
"node",
"python",
"python",
"java",
"java",
"cocoa",
"php",
"csharp",
"ruby",
"go",
"native",
"elixir",
}
// Real city coordinates — events only appear where people actually are
cities := [][2]float64{
{40.7, -74.0}, // New York
{37.8, -122.4}, // San Francisco
{51.5, -0.1}, // London
{48.9, 2.3}, // Paris
{52.5, 13.4}, // Berlin
{35.7, 139.7}, // Tokyo
{39.9, 116.4}, // Beijing
{31.2, 121.5}, // Shanghai
{-33.9, 151.2}, // Sydney
{-23.5, -46.6}, // São Paulo
{19.1, 72.9}, // Mumbai
{12.9, 77.6}, // Bangalore
{30.0, 31.2}, // Cairo
{6.5, 3.4}, // Lagos
{19.4, -99.1}, // Mexico City
{-34.6, -58.4}, // Buenos Aires
{55.8, 37.6}, // Moscow
{41.0, 29.0}, // Istanbul
{37.6, 127.0}, // Seoul
{1.3, 103.8}, // Singapore
{25.2, 55.3}, // Dubai
{43.7, -79.4}, // Toronto
{41.9, -87.6}, // Chicago
{34.1, -118.2}, // Los Angeles
{47.6, -122.3}, // Seattle
{25.8, -80.2}, // Miami
{52.4, 4.9}, // Amsterdam
{59.3, 18.1}, // Stockholm
{40.4, -3.7}, // Madrid
{41.9, 12.5}, // Rome
{22.3, 114.2}, // Hong Kong
{-6.2, 106.8}, // Jakarta
{13.8, 100.5}, // Bangkok
{-1.3, 36.8}, // Nairobi
{-33.9, 18.4}, // Cape Town
{4.7, -74.1}, // Bogotá
{-12.0, -77.0}, // Lima
{-33.5, -70.6}, // Santiago
{45.5, -73.6}, // Montreal
{50.1, 8.7}, // Frankfurt
{53.3, -6.3}, // Dublin
{59.9, 10.8}, // Oslo
{60.2, 25.0}, // Helsinki
{47.4, 8.5}, // Zurich
{50.9, 4.4}, // Brussels
{38.7, -9.1}, // Lisbon
{37.9, 23.7}, // Athens
{44.8, 20.5}, // Belgrade
{50.1, 14.4}, // Prague
{47.5, 19.1}, // Budapest
{52.2, 21.0}, // Warsaw
{59.4, 24.7}, // Tallinn
{23.1, 113.3}, // Guangzhou
{28.6, 77.2}, // New Delhi
{24.9, 67.0}, // Karachi
{33.7, 73.1}, // Islamabad
{23.8, 90.4}, // Dhaka
{6.9, 79.9}, // Colombo
{3.1, 101.7}, // Kuala Lumpur
{14.6, 121.0}, // Manila
{10.8, 106.7}, // Ho Chi Minh City
{16.8, 96.2}, // Yangon
{27.7, 85.3}, // Kathmandu
{-4.3, 15.3}, // Kinshasa
{5.6, -0.2}, // Accra
{12.4, -1.5}, // Ouagadougou
{9.1, 7.4}, // Abuja
{-26.2, 28.0}, // Johannesburg
{-17.8, 31.0}, // Harare
{-8.8, 13.2}, // Luanda
{33.9, -6.9}, // Rabat
{36.8, 10.2}, // Tunis
{32.9, 13.2}, // Tripoli
{15.6, 32.5}, // Khartoum
{2.0, 45.3}, // Mogadishu
{-18.9, 47.5}, // Antananarivo
{-25.9, 32.6}, // Maputo
{-15.4, 28.3}, // Lusaka
{-13.0, -38.5}, // Salvador
{-3.1, -60.0}, // Manaus
{-30.0, -51.2}, // Porto Alegre
{10.5, -66.9}, // Caracas
{-0.2, -78.5}, // Quito
{-16.5, -68.2}, // La Paz
{-11.2, 17.9}, // Luanda surrounds
{32.1, 34.8}, // Tel Aviv
{33.9, 35.5}, // Beirut
{33.3, 44.4}, // Baghdad
{35.7, 51.4}, // Tehran
{41.3, 69.3}, // Tashkent
{43.3, 76.9}, // Almaty
{51.2, 71.5}, // Astana
{47.9, 106.9}, // Ulaanbaatar
{-36.9, 174.8}, // Auckland
{-27.5, 153.0}, // Brisbane
{-31.9, 115.9}, // Perth
{-37.8, 145.0}, // Melbourne
{21.3, -157.8}, // Honolulu
{61.2, -149.9}, // Anchorage
{64.8, -147.7}, // Fairbanks
{45.4, -75.7}, // Ottawa
{49.3, -123.1}, // Vancouver
{51.0, -114.1}, // Calgary
{53.5, -113.5}, // Edmonton
}
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
for {
city := cities[rng.Intn(len(cities))]
// Add small jitter so repeated city hits don't stack exactly
lat := city[0] + (rng.Float64()-0.5)*2.0
lng := city[1] + (rng.Float64()-0.5)*2.0
b := []byte(fmt.Sprintf(
`[%.4f,%.4f,%d,"%s"]`,
lat,
lng,
int(time.Now().UnixNano()/1000000),
platforms[rng.Intn(len(platforms))],
))
time.Sleep(time.Millisecond / 2)
conn.WriteTo(b, dst)
}
}
func init() {
flag.Parse()
}
func main() {
if err := sentry.Init(sentry.ClientOptions{
Dsn: "https://da9a4372645d168eff259433fb2403c9@o1.ingest.us.sentry.io/4510957955514368",
EnableTracing: true,
// 100% trace sampling — intentional for this low-traffic demo app.
// Reduce for high-traffic deployments.
TracesSampleRate: 1.0,
SendDefaultPII: false,
}); err != nil {
log.Fatalf("sentry.Init: %s", err)
}
defer sentry.Flush(2 * time.Second)
if *flagTest {
go runTest(*flagUdpPort)
}
es := eventsource.New(&eventsource.Settings{
Timeout: 1 * time.Second,
IdleTimeout: 1 * time.Minute,
CloseOnTimeout: true,
Gzip: false,
}, nil)
defer es.Close()
mux := http.NewServeMux()
mux.HandleFunc("/healthz", handleHealth)
mux.HandleFunc("/stats", handleStats)
mux.Handle("/stream", es)
// Serve the Vite-built frontend from static/
mux.Handle("/", http.FileServer(http.Dir("static")))
sentryHandler := sentryhttp.New(sentryhttp.Options{Repanic: true})
conn, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.ParseIP(*flagHost),
Port: *flagUdpPort,
})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
// Heartbeat: send a ping every 3s so the client watchdog doesn't
// fire during legitimate low-traffic periods.
go func() {
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for range ticker.C {
es.SendEventMessage([]byte("{}"))
}
}()
// Periodic ingest rate logging — makes empty-globe outages obvious.
go func() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
var prevRecv, prevFwd uint64
for range ticker.C {
recv := ingestStats.received.Load()
fwd := ingestStats.forwarded.Load()
log.Printf(
"ingest: received=%.1f/s forwarded=%.1f/s (total recv=%d fwd=%d drop=%d)",
float64(recv-prevRecv)/30,
float64(fwd-prevFwd)/30,
recv,
fwd,
ingestStats.dropped.Load(),
)
prevRecv, prevFwd = recv, fwd
}
}()
go func() {
b := make([]byte, 256)
// Token bucket so UDP bursts still achieve max-forward-rate over time.
// A min-gap gate would drop almost an entire kernel backlog because
// time.Now barely advances between tight ReadFromUDP iterations.
var (
forwardRate = *flagMaxForwardRate
forwardBurst float64
tokens float64
lastRefill time.Time
)
if forwardRate > 0 {
// Burst is 1s of rate, but never below 1 token — otherwise any
// 0 < max-forward-rate < 1 permanently caps the bucket below the
// cost of a single forward and drops every event.
forwardBurst = forwardRate
if forwardBurst < 1 {
forwardBurst = 1
}
tokens = forwardBurst
lastRefill = time.Now()
}
allowForward := func() bool {
if forwardRate <= 0 {
return true
}
now := time.Now()
tokens += now.Sub(lastRefill).Seconds() * forwardRate
lastRefill = now
if tokens > forwardBurst {
tokens = forwardBurst
}
if tokens < 1 {
return false
}
tokens--
return true
}
for {
n, _, err := conn.ReadFromUDP(b)
if err != nil {
sentry.CaptureException(err)
sentry.Flush(2 * time.Second)
log.Fatal(err)
return
}
ingestStats.received.Add(1)
if *flagSampleRate < 1.0 && rng.Float64() >= *flagSampleRate {
ingestStats.dropped.Add(1)
continue
}
if !allowForward() {
ingestStats.dropped.Add(1)
continue
}
d := make([]byte, n)
copy(d, b)
es.SendEventMessage(d)
ingestStats.forwarded.Add(1)
}
}()
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", *flagHost, *flagHttpPort), sentryHandler.Handle(mux)))
}