public snapshot · system/tools/nib/bench/xlang/ · system@main · commit a92f56ab098e · shared 2026-11-22T22:43:57Z· frozen: this page does not change when the repository does
all files
  1// Shared state under load (nib/accounts.nib): 1024 accounts, each keeping
  2// its 32 most recent deposits; GET /a/<id> deposits 1 + len(id) and answers
  3// the sum of the account's recent deposits, on port 18451 (WINDOW sets how
  4// many it keeps). SHARDS=1 (the
  5// default) keeps every account behind one sync.Mutex; SHARDS=n splits them
  6// over n mutexes by the id's hash, as a hand-sharded server would.
  7package main
  8
  9import (
 10	"hash/fnv"
 11	"log"
 12	"net/http"
 13	"os"
 14	"strconv"
 15	"sync"
 16)
 17
 18type shard struct {
 19	mu     sync.Mutex
 20	recent map[string][]int64
 21}
 22
 23func main() {
 24	n, err := strconv.Atoi(os.Getenv("SHARDS"))
 25	if err != nil || n < 1 {
 26		n = 1
 27	}
 28	window, err := strconv.Atoi(os.Getenv("WINDOW"))
 29	if err != nil || window < 1 {
 30		window = 32
 31	}
 32	shards := make([]*shard, n)
 33	for i := range shards {
 34		shards[i] = &shard{recent: map[string][]int64{}}
 35	}
 36	shardOf := func(id string) *shard {
 37		h := fnv.New32a()
 38		h.Write([]byte(id))
 39		return shards[int(h.Sum32())%n]
 40	}
 41	for i := 0; i < 1024; i++ {
 42		id := strconv.Itoa(i)
 43		// A full window of zero deposits: every request does the same work.
 44		shardOf(id).recent[id] = make([]int64, window, window+1)
 45	}
 46	mux := http.NewServeMux()
 47	mux.HandleFunc("GET /a/{id}", func(w http.ResponseWriter, r *http.Request) {
 48		id := r.PathValue("id")
 49		s := shardOf(id)
 50		s.mu.Lock()
 51		recent, ok := s.recent[id]
 52		if !ok {
 53			s.mu.Unlock()
 54			http.Error(w, "bad account", http.StatusBadRequest)
 55			return
 56		}
 57		recent = append(recent, int64(1+len(id)))
 58		if len(recent) > window {
 59			recent = append(recent[:0], recent[1:]...)
 60		}
 61		s.recent[id] = recent
 62		var sum int64
 63		for _, x := range recent {
 64			sum += x
 65		}
 66		s.mu.Unlock()
 67		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
 68		w.Write([]byte(strconv.FormatInt(sum, 10)))
 69	})
 70	log.Fatal(http.ListenAndServe("0.0.0.0:18451", mux))
 71}