-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathstartup.go
More file actions
142 lines (127 loc) · 4.97 KB
/
Copy pathstartup.go
File metadata and controls
142 lines (127 loc) · 4.97 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
package main
import (
"context"
"fmt"
"lyrics-api-go/logcolors"
"lyrics-api-go/middleware"
"lyrics-api-go/services/notifier"
"lyrics-api-go/stats"
"net/http"
"os"
"time"
log "github.com/sirupsen/logrus"
)
// newHTTPServer builds the API's HTTP server with explicit timeouts.
//
// http.ListenAndServe uses a zero-value http.Server with no timeouts, so idle
// or stuck keep-alive connections (dead peers, slowloris, clients that stop
// reading) are never reaped. On a long-lived, public-facing process they leak
// file descriptors until accept() fails with "too many open files" and the
// server stops answering. These timeouts bound every connection's lifetime.
func newHTTPServer(addr string, handler http.Handler) *http.Server {
return &http.Server{
Addr: addr,
Handler: handler,
ReadHeaderTimeout: 10 * time.Second, // slowloris guard: header must arrive quickly
ReadTimeout: 30 * time.Second, // whole request (headers + body)
WriteTimeout: 60 * time.Second, // response write ceiling (lyrics JSON, not streaming)
IdleTimeout: 90 * time.Second, // reap idle keep-alive connections
}
}
func getEnvOrDefault(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
func getNotifierTypeName(n notifier.Notifier) string {
switch n.(type) {
case *notifier.EmailNotifier:
return "email"
case *notifier.TelegramNotifier:
return "telegram"
case *notifier.NtfyNotifier:
return "ntfy"
default:
return "unknown"
}
}
func setupNotifiers() []notifier.Notifier {
var notifiers []notifier.Notifier
if smtpHost := os.Getenv("NOTIFIER_SMTP_HOST"); smtpHost != "" {
emailNotifier := ¬ifier.EmailNotifier{
SMTPHost: smtpHost,
SMTPPort: getEnvOrDefault("NOTIFIER_SMTP_PORT", "587"),
SMTPUsername: os.Getenv("NOTIFIER_SMTP_USERNAME"),
SMTPPassword: os.Getenv("NOTIFIER_SMTP_PASSWORD"),
FromEmail: os.Getenv("NOTIFIER_FROM_EMAIL"),
ToEmail: os.Getenv("NOTIFIER_TO_EMAIL"),
}
notifiers = append(notifiers, emailNotifier)
log.Infof("%s Email notifier enabled", logcolors.LogNotifier)
}
if botToken := os.Getenv("NOTIFIER_TELEGRAM_BOT_TOKEN"); botToken != "" {
telegramNotifier := ¬ifier.TelegramNotifier{
BotToken: botToken,
ChatID: os.Getenv("NOTIFIER_TELEGRAM_CHAT_ID"),
}
notifiers = append(notifiers, telegramNotifier)
log.Infof("%s Telegram notifier enabled", logcolors.LogNotifier)
}
if topic := os.Getenv("NOTIFIER_NTFY_TOPIC"); topic != "" {
ntfyNotifier := ¬ifier.NtfyNotifier{
Topic: topic,
Server: getEnvOrDefault("NOTIFIER_NTFY_SERVER", "https://ntfy.sh"),
}
notifiers = append(notifiers, ntfyNotifier)
log.Infof("%s Ntfy.sh notifier enabled", logcolors.LogNotifier)
}
return notifiers
}
func limitMiddleware(next http.Handler, limiter *middleware.IPRateLimiter) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check for API key to bypass rate limits
apiKey := r.Header.Get("X-API-Key")
if apiKey != "" && conf.Configuration.APIKey != "" && apiKey == conf.Configuration.APIKey {
w.Header().Set("X-RateLimit-Bypass", "true")
ctx := context.WithValue(r.Context(), rateLimitTypeKey, "bypass")
next.ServeHTTP(w, r.WithContext(ctx))
return
}
limiters := limiter.GetLimiter(r.RemoteAddr)
// Try normal tier first
if limiters.Normal.Allow() {
// Normal tier allows this request
stats.Get().RecordRateLimit("normal")
remainingNormal := limiters.GetNormalTokens()
w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", limiter.GetNormalLimit()))
w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", remainingNormal))
w.Header().Set("X-RateLimit-Type", "normal")
ctx := context.WithValue(r.Context(), rateLimitTypeKey, "normal")
next.ServeHTTP(w, r.WithContext(ctx))
return
}
// Normal tier exceeded, try cached tier
if limiters.Cached.Allow() {
// Cached tier allows, but only for cached responses
stats.Get().RecordRateLimit("cached")
remainingCached := limiters.GetCachedTokens()
w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", limiter.GetCachedLimit()))
w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", remainingCached))
w.Header().Set("X-RateLimit-Type", "cached")
log.Debugf("%s IP %s exceeded normal tier, using cached tier", logcolors.LogRateLimit, r.RemoteAddr)
ctx := context.WithValue(r.Context(), cacheOnlyModeKey, true)
ctx = context.WithValue(ctx, rateLimitTypeKey, "cached")
next.ServeHTTP(w, r.WithContext(ctx))
return
}
// Both tiers exceeded
stats.Get().RecordRateLimit("exceeded")
log.Warnf("%s IP %s exceeded both rate limit tiers", logcolors.LogRateLimit, r.RemoteAddr)
w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", limiter.GetCachedLimit()))
w.Header().Set("X-RateLimit-Remaining", "0")
w.Header().Set("X-RateLimit-Type", "exceeded")
w.Header().Set("Retry-After", "1")
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
})
}