main.mx raw

   1  // A stdlib net/http server on the one-call-per-request handler path.
   2  //
   3  // The application's main type IS the handler: it holds whatever data access the
   4  // app needs, and the shell makes exactly one call per request -
   5  // `app.Handle(req) (resp)`. The shell owns the socket, the framing, the
   6  // keep-alive loop and one request arena per connection; the handler does no io
   7  // and keeps no state between requests.
   8  //
   9  // The /stats route reports how many requests this app has served and the
  10  // process RSS, so the phase can assert that serving requests does not
  11  // accumulate memory.
  12  //
  13  // usage: server [addr] [inline|spawned]
  14  package main
  15  
  16  import (
  17  	"bytes"
  18  	"fmt"
  19  	"net/http"
  20  	"os"
  21  	"runtime"
  22  	"strconv"
  23  )
  24  
  25  // app is the application's main type. A real app would hold its database
  26  // handle, config and caches here. This one is EMPTY and its Handle writes
  27  // nothing back through the receiver: keeping the handler pure is the design
  28  // rule, and it is also what keeps per-request memory in the request arena
  29  // (measured: a handler that mutates its receiver costs ~12kB per request in
  30  // the inline path, a pure one does not - the work log).
  31  type app struct{}
  32  
  33  // Handle is one call per request: request in, response out, no io.
  34  func (a *app) Handle(req *http.Req) (resp *http.Resp) {
  35  	headers := http.Header{}
  36  	headers["Content-Type"] = [][]byte{[]byte("text/plain; charset=utf-8")}
  37  	resp = &http.Resp{Status: 200, Headers: headers}
  38  	if req.Path == "/arenas" {
  39  		resp.Body = runtime.ArenaScopeReport()
  40  		return resp
  41  	}
  42  	if req.Path == "/stats" {
  43  		resp.Body = statsLine()
  44  		return resp
  45  	}
  46  	resp.Body = []byte("hello path=" | req.Path | "\n")
  47  	return resp
  48  }
  49  
  50  // statsLine reports the process RSS and the runtime's cumulative allocation
  51  // counters. Two snapshots around a loop give bytes-allocated-per-request
  52  // (churn) separately from RSS (retention): a churn that matches the growth says
  53  // nothing is being freed, a small churn with a growing RSS says the retention is
  54  // outside the allocator.
  55  func statsLine() (s string) {
  56  	var m runtime.MemStats
  57  	runtime.ReadMemStats(&m)
  58  	return "allocs=" | strconv.Itoa(int32(m.Allocs)) | "\ntotalalloc_kb=" | strconv.Itoa(int32(m.TotalAlloc/1024)) | "\nring_committed_kb=" | strconv.Itoa(http.ChanSlotCommittedBytes()/1024) | "\nring_inflight_max=" | strconv.Itoa(http.ChanSlotMaxInFlight()) | "\n" | rssLine()
  59  }
  60  
  61  // rssLine reads the process RSS so the phase can see whether requests
  62  // accumulate. That is the fixture's business, not the shell's.
  63  func rssLine() (s string) {
  64  	b, err := os.ReadFile("/proc/self/status")
  65  	if err != nil {
  66  		return "rss_kb=?\n"
  67  	}
  68  	i := bytes.Index(b, []byte("VmRSS:"))
  69  	if i < 0 {
  70  		return "rss_kb=?\n"
  71  	}
  72  	j := i + 6
  73  	for j < len(b) && (b[j] == ' ' || b[j] == '\t') {
  74  		j = j + 1
  75  	}
  76  	k := j
  77  	for k < len(b) && b[k] >= '0' && b[k] <= '9' {
  78  		k = k + 1
  79  	}
  80  	return "rss_kb=" | string(b[j:k]) | "\n"
  81  }
  82  
  83  func main() {
  84  	// Termination: a batch program must still be stoppable, so the entry
  85  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  86  	select {
  87  	case <-shutdown:
  88  		return
  89  	default:
  90  	}
  91  
  92  	addr := "127.0.0.1:39128"
  93  	mode := "inline"
  94  	if len(os.Args) > 1 {
  95  		addr = os.Args[1]
  96  	}
  97  	if len(os.Args) > 2 {
  98  		mode = os.Args[2]
  99  	}
 100  	dispatch := http.DispatchInline
 101  	if mode == "spawned" {
 102  		dispatch = http.DispatchSpawned
 103  	}
 104  	runtime.ResetArenaScopeStats()
 105  	runtime.SetArenaTrace(true)
 106  	a := &app{}
 107  	mux := http.NewChanMux()
 108  	mux.Handle("/", a)
 109  	fmt.Printf("listening on %s mode=%s\n", addr, mode)
 110  	err := http.ChanServeMode(addr, mux, dispatch, 4)
 111  	fmt.Printf("server returned err=%v\n", err)
 112  	os.Exit(1)
 113  }
 114