aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/player_limit.go (1552B)


      1 package main
      2 
      3 import (
      4 	"net/http"
      5 	"sync"
      6 )
      7 
      8 // Shared across zone owners; overlapping reconnects occupy the same player slot.
      9 type playerLimit struct {
     10 	mutex   sync.Mutex
     11 	maximum int
     12 	clients map[uint32]map[*worldClient]bool
     13 }
     14 
     15 func (limit *playerLimit) full(id uint32) bool {
     16 	if limit == nil {
     17 		return false
     18 	}
     19 	limit.mutex.Lock()
     20 	defer limit.mutex.Unlock()
     21 	return len(limit.clients) >= limit.maximum && len(limit.clients[id]) == 0
     22 }
     23 
     24 func (limit *playerLimit) admit(client *worldClient) bool {
     25 	if limit == nil {
     26 		return true
     27 	}
     28 	limit.mutex.Lock()
     29 	defer limit.mutex.Unlock()
     30 	if len(limit.clients[client.id]) == 0 {
     31 		if len(limit.clients) >= limit.maximum {
     32 			return false
     33 		}
     34 		limit.clients[client.id] = make(map[*worldClient]bool)
     35 	}
     36 	limit.clients[client.id][client] = true
     37 	return true
     38 }
     39 
     40 func (limit *playerLimit) release(client *worldClient) {
     41 	if limit == nil {
     42 		return
     43 	}
     44 	limit.mutex.Lock()
     45 	defer limit.mutex.Unlock()
     46 	delete(limit.clients[client.id], client)
     47 	if len(limit.clients[client.id]) == 0 {
     48 		delete(limit.clients, client.id)
     49 	}
     50 }
     51 
     52 func (server *server) rejectFull(w http.ResponseWriter, r *http.Request) bool {
     53 	if !server.playerLimit.full(0) {
     54 		return false
     55 	}
     56 	id, err := server.browserPlayerID(browserCredential(r))
     57 	if err != nil {
     58 		http.Error(w, err.Error(), http.StatusInternalServerError)
     59 		return true
     60 	}
     61 	if !server.playerLimit.full(id) {
     62 		return false
     63 	}
     64 	w.Header().Set("Cache-Control", "no-store")
     65 	http.Error(w, "Server full. Please try again later.", http.StatusServiceUnavailable)
     66 	return true
     67 }