bring back logging of too many concurrent requests and apply it to /njump/ prefixes.

This commit is contained in:
fiatjaf
2024-09-27 07:31:02 -03:00
parent 0012a45488
commit d8580e4eac
2 changed files with 15 additions and 7 deletions

View File

@@ -22,7 +22,7 @@ func agentBlock(next http.HandlerFunc) http.HandlerFunc {
} { } {
if strings.Contains(ua, bua) { if strings.Contains(ua, bua) {
// log.Debug().Str("ua", ua).Msg("user-agent blocked") // log.Debug().Str("ua", ua).Msg("user-agent blocked")
http.Error(w, "Forbidden", http.StatusForbidden) http.Error(w, "", http.StatusForbidden)
return return
} }
} }
@@ -69,7 +69,7 @@ func ipBlock(next http.HandlerFunc) http.HandlerFunc {
for _, ipnet := range ranges { for _, ipnet := range ranges {
if ipnet.Contains(ip) { if ipnet.Contains(ip) {
log.Debug().Stringer("ip", ip).Msg("ip blocked") log.Debug().Stringer("ip", ip).Msg("ip blocked")
http.Error(w, "Forbidden", http.StatusForbidden) http.Error(w, "", http.StatusForbidden)
return return
} }
} }

View File

@@ -43,7 +43,7 @@ func queueMiddleware(next http.HandlerFunc) http.HandlerFunc {
} }
willQueue := false willQueue := false
for _, prefix := range []string{"/nevent1", "/image", "/naddr1", "/npub1", "/nprofile1", "/note1", "/embed"} { for _, prefix := range []string{"/njump", "/nevent1", "/image", "/naddr1", "/npub1", "/nprofile1", "/note1", "/embed"} {
if strings.HasPrefix(r.URL.Path, prefix) { if strings.HasPrefix(r.URL.Path, prefix) {
willQueue = true willQueue = true
break break
@@ -56,11 +56,19 @@ func queueMiddleware(next http.HandlerFunc) http.HandlerFunc {
} }
qidx := stupidHash(r.URL.Path) qidx := stupidHash(r.URL.Path)
curr := concurrentRequests[qidx].Load() // add 1
isFirst := curr == 0 count := concurrentRequests[qidx].Add(1)
isFirst := count == 1
if count > 2 {
log.Debug().Uint32("count", count).Int("qidx", qidx).Msg("too many concurrent requests")
// add 1 and lock (or wait for the lock) if count > 4 {
concurrentRequests[qidx].Add(1) http.Error(w, "", http.StatusTooManyRequests)
return
}
}
// lock (or wait for the lock)
queue[qidx].Lock() queue[qidx].Lock()
if isFirst { if isFirst {