aorecomp

Anarchy Online classic in the browser

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


server/browser_profile.go (2702B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/json"
      6 	"io"
      7 	"net/http"
      8 	"os"
      9 	"path/filepath"
     10 	"regexp"
     11 )
     12 
     13 var browserProfileID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
     14 
     15 type profileWriter struct {
     16 	requests chan profileBatch
     17 	done     chan struct{}
     18 }
     19 
     20 type profileBatch struct {
     21 	session string
     22 	data    []byte
     23 	reply   chan profileResult
     24 }
     25 
     26 type profileResult struct {
     27 	status  int
     28 	message string
     29 }
     30 
     31 func newProfileWriter() *profileWriter {
     32 	writer := &profileWriter{requests: make(chan profileBatch), done: make(chan struct{})}
     33 	go func() {
     34 		defer close(writer.done)
     35 		for batch := range writer.requests {
     36 			batch.reply <- batch.write()
     37 		}
     38 	}()
     39 	return writer
     40 }
     41 
     42 // HTTP producers finish before shutdown drains the accepted file writes.
     43 func (writer *profileWriter) stop() {
     44 	close(writer.requests)
     45 	<-writer.done
     46 }
     47 
     48 func (writer *profileWriter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
     49 	id := r.PathValue("session")
     50 	if !browserProfileID.MatchString(id) {
     51 		http.Error(w, "Invalid profile session", http.StatusBadRequest)
     52 		return
     53 	}
     54 	body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 2*1024*1024))
     55 	if err != nil {
     56 		http.Error(w, "Profile batch too large or unreadable", http.StatusRequestEntityTooLarge)
     57 		return
     58 	}
     59 	var compact bytes.Buffer
     60 	if err := json.Compact(&compact, body); err != nil {
     61 		http.Error(w, "Invalid profile JSON", http.StatusBadRequest)
     62 		return
     63 	}
     64 	compact.WriteByte('\n')
     65 
     66 	batch := profileBatch{session: id, data: compact.Bytes(), reply: make(chan profileResult, 1)}
     67 	writer.requests <- batch
     68 	result := <-batch.reply
     69 	if result.message != "" {
     70 		http.Error(w, result.message, result.status)
     71 		return
     72 	}
     73 	w.WriteHeader(result.status)
     74 }
     75 
     76 func (batch profileBatch) write() profileResult {
     77 	// Size validation and append belong to the same owner operation.
     78 	if err := os.MkdirAll("logs/profiles", 0755); err != nil {
     79 		return profileResult{http.StatusInternalServerError, "Cannot create profile directory"}
     80 	}
     81 	file, err := os.OpenFile(filepath.Join("logs/profiles", batch.session+".ndjson"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
     82 	if err != nil {
     83 		return profileResult{http.StatusInternalServerError, "Cannot open profile"}
     84 	}
     85 	defer file.Close()
     86 	info, err := file.Stat()
     87 	if err != nil {
     88 		return profileResult{http.StatusInternalServerError, "Cannot inspect profile"}
     89 	}
     90 	if info.Size()+int64(len(batch.data)) > 128*1024*1024 {
     91 		return profileResult{http.StatusRequestEntityTooLarge, "Profile session is full"}
     92 	}
     93 	if _, err := file.Write(batch.data); err != nil {
     94 		return profileResult{http.StatusInternalServerError, "Cannot save profile"}
     95 	}
     96 	return profileResult{status: http.StatusNoContent}
     97 }