mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-10 19:27:07 +02:00
- Refactor load balancer interface to separate server selection (ChooseServer) from request handling - Add cookie-based sticky session support with configurable max-age and secure cookie handling - Integrate idlewatcher requests with automatic sticky session assignment - Improve algorithm implementations: * Replace fnv with xxhash3 for better performance in IP hash and server keys * Add proper bounds checking and error handling in all algorithms * Separate concerns between server selection and request processing - Add Sticky and StickyMaxAge fields to LoadBalancerConfig - Create dedicated sticky.go for session management utilities
92 lines
1.8 KiB
Go
92 lines
1.8 KiB
Go
package loadbalancer
|
|
|
|
import (
|
|
"net"
|
|
"net/http"
|
|
"sync"
|
|
|
|
"github.com/bytedance/gopkg/util/xxhash3"
|
|
"github.com/yusing/godoxy/internal/net/gphttp/middleware"
|
|
"github.com/yusing/godoxy/internal/types"
|
|
gperr "github.com/yusing/goutils/errs"
|
|
)
|
|
|
|
type ipHash struct {
|
|
*LoadBalancer
|
|
|
|
realIP *middleware.Middleware
|
|
pool types.LoadBalancerServers
|
|
mu sync.Mutex
|
|
}
|
|
|
|
var _ impl = (*ipHash)(nil)
|
|
var _ customServeHTTP = (*ipHash)(nil)
|
|
|
|
func (lb *LoadBalancer) newIPHash() impl {
|
|
impl := &ipHash{LoadBalancer: lb}
|
|
if len(lb.Options) == 0 {
|
|
return impl
|
|
}
|
|
var err gperr.Error
|
|
impl.realIP, err = middleware.RealIP.New(lb.Options)
|
|
if err != nil {
|
|
gperr.LogError("invalid real_ip options, ignoring", err, &impl.l)
|
|
}
|
|
return impl
|
|
}
|
|
|
|
func (impl *ipHash) OnAddServer(srv types.LoadBalancerServer) {
|
|
impl.mu.Lock()
|
|
defer impl.mu.Unlock()
|
|
|
|
for i, s := range impl.pool {
|
|
if s == srv {
|
|
return
|
|
}
|
|
if s == nil {
|
|
impl.pool[i] = srv
|
|
return
|
|
}
|
|
}
|
|
|
|
impl.pool = append(impl.pool, srv)
|
|
}
|
|
|
|
func (impl *ipHash) OnRemoveServer(srv types.LoadBalancerServer) {
|
|
impl.mu.Lock()
|
|
defer impl.mu.Unlock()
|
|
|
|
for i, s := range impl.pool {
|
|
if s == srv {
|
|
impl.pool[i] = nil
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (impl *ipHash) ServeHTTP(_ types.LoadBalancerServers, rw http.ResponseWriter, r *http.Request) {
|
|
srv := impl.ChooseServer(impl.pool, r)
|
|
if srv == nil || srv.Status().Bad() {
|
|
http.Error(rw, "Service unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
|
|
if impl.realIP != nil {
|
|
impl.realIP.ModifyRequest(srv.ServeHTTP, rw, r)
|
|
} else {
|
|
srv.ServeHTTP(rw, r)
|
|
}
|
|
}
|
|
|
|
func (impl *ipHash) ChooseServer(_ types.LoadBalancerServers, r *http.Request) types.LoadBalancerServer {
|
|
if len(impl.pool) == 0 {
|
|
return nil
|
|
}
|
|
|
|
ip, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
if err != nil {
|
|
ip = r.RemoteAddr
|
|
}
|
|
return impl.pool[xxhash3.HashString(ip)%uint64(len(impl.pool))]
|
|
}
|