diff --git a/main.go b/main.go index e98c1c9..de0c572 100644 --- a/main.go +++ b/main.go @@ -38,32 +38,28 @@ var ( // buildCategoryRanger holt alle CIDRs aus Redis, baut einen PCTrie // und legt ihn 10 Minuten im Cache ab. func buildCategoryRanger(cat string) (cidranger.Ranger, error) { - rangerCacheMu.Lock() - // Cache-Hit? + // --------- 1) Leser-Lock: schneller Cache-Hit + rangerCacheMu.RLock() if e, ok := rangerCache[cat]; ok && time.Now().Before(e.expireAt) { - rangerCacheMu.Unlock() + rangerCacheMu.RUnlock() return e.ranger, nil } - rangerCacheMu.Unlock() + rangerCacheMu.RUnlock() - // Redis auslesen + // --------- 2) Daten aus Redis ziehen keys, err := rdb.HKeys(ctx, "bl:"+cat).Result() + log.Printf("Building ranger for %s - keys: %d", cat, len(keys)) if err != nil { return nil, err } - r := cidranger.NewPCTrieRanger() for _, k := range keys { - k = strings.TrimSpace(k) - _, ipNet, err := net.ParseCIDR(k) - if err != nil { - fmt.Printf("⚠️ Ungültiger Redis-Prefix %s: %s\n", cat, k) - continue + if _, ipNet, err := net.ParseCIDR(strings.TrimSpace(k)); err == nil { + _ = r.Insert(cidranger.NewBasicRangerEntry(*ipNet)) } - _ = r.Insert(cidranger.NewBasicRangerEntry(*ipNet)) } - // Cache aktualisieren + // --------- 3) Schreiber-Lock: Cache aktualisieren rangerCacheMu.Lock() rangerCache[cat] = rangerCacheEntry{ ranger: r, @@ -149,6 +145,8 @@ func main() { return } + warmUpRangers() + // Server http.HandleFunc("/", handleGUI) http.HandleFunc("/download/", handleDownload) @@ -466,6 +464,14 @@ func checkIP(ip netip.Addr, cats []string) ([]string, error) { return matches, nil } +func warmUpRangers() { + for cat := range blocklistURLs { + if _, err := buildCategoryRanger(cat); err != nil { + log.Printf("warm-up error for %s: %v", cat, err) + } + } +} + // JSON-Helfer func writeJSON(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json")