oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3// The fan-out measurement slice 1b's done list asks for (live-push spec §4.2,
4// §10): five typists and five watchers in one document, push on, warm
5// handles on, sealed rows, in single-user and in team mode (where every
6// flush runs guard.check), with the per-document frame cache on and off.
7// Not a gate: skipped unless DOCS_LIVE_FANOUT=1. In process, so the CPU it
8// reports includes the clients (identical in every configuration): read it
9// as a comparison between configurations, not as the server's cost.
10
11import (
12 "context"
13 "fmt"
14 "math/rand"
15 "net/http"
16 "net/http/httptest"
17 "os"
18 "sort"
19 "strconv"
20 "strings"
21 "sync"
22 "syscall"
23 "testing"
24 "time"
25)
26
27func processCPU() time.Duration {
28 var ru syscall.Rusage
29 syscall.Getrusage(syscall.RUSAGE_SELF, &ru)
30 return time.Duration(ru.Utime.Nano() + ru.Stime.Nano())
31}
32
33func TestLivePushFanoutProbe(t *testing.T) {
34 if os.Getenv("DOCS_LIVE_FANOUT") != "1" {
35 t.Skip("set DOCS_LIVE_FANOUT=1")
36 }
37 posts, _ := strconv.Atoi(os.Getenv("DOCS_LIVE_FANOUT_POSTS"))
38 if posts == 0 {
39 posts = 120
40 }
41 for _, mode := range []string{"single", "team"} {
42 for _, cache := range []bool{false, true} {
43 t.Run(fmt.Sprintf("%s-cache%v", mode, cache), func(t *testing.T) {
44 f := fanoutFixture(t, mode)
45 f.app.handlers.pushFrameCache = cache
46 // The probe's typists share one session; real ones do not.
47 f.app.handlers.late.limit = 1 << 20
48 fanout(t, f, 5, 5, posts)
49 })
50 }
51 }
52}
53
54func fanoutFixture(t *testing.T, mode string) *pushFixture {
55 t.Helper()
56 if mode == "team" {
57 tf := newTeamRouterFixtureWith(t, false, true)
58 b := tf.browser()
59 b.localSignin(t, "alice@example.com")
60 b.linkProof(t, teamSubject('a'), "alice@example.com")
61 routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
62 srv := httptest.NewServer(tf.app.Handler())
63 t.Cleanup(srv.Close)
64 f := &pushFixture{t: t, app: tf.app, srv: srv, doc: tf.own, ctx: context.Background(), host: strings.TrimPrefix(bridgeOrigin, "https://")}
65 for _, c := range b.cookies {
66 f.cookies = append(f.cookies, c)
67 }
68 f.app.handlers.livePush = true
69 f.app.store.recordOrigin = f.app.handlers.pushRegistry.record
70 return f
71 }
72 app, _ := activatedContentApp(t)
73 app.handlers.livePush = true
74 app.store.recordOrigin = app.handlers.pushRegistry.record
75 app.store.warm = newWarmCache()
76 ctx := context.Background()
77 owner := app.TestPerson(t, "owner@example.com")
78 doc, err := app.Store().Create(ctx, owner, "Fan-out")
79 if err != nil {
80 t.Fatal(err)
81 }
82 srv := httptest.NewServer(app.Handler())
83 t.Cleanup(srv.Close)
84 f := &pushFixture{t: t, app: app, srv: srv, owner: owner, doc: doc, ctx: ctx}
85 f.cookies = f.session("owner@example.com")
86 return f
87}
88
89func (f *pushFixture) postHost(update []byte, docsStream string) (int, int64) {
90 req, _ := http.NewRequest(http.MethodPost, f.srv.URL+"/d/"+f.doc.Sqid+"/updates", strings.NewReader(string(update)))
91 if f.host != "" {
92 req.Host = f.host
93 req.Header.Set("Origin", bridgeOrigin)
94 }
95 req.Header.Set("Content-Type", "application/octet-stream")
96 req.Header.Set("Sec-Fetch-Site", "same-origin")
97 if docsStream != "" {
98 req.Header.Set("Docs-Stream", docsStream)
99 }
100 for _, c := range f.cookies {
101 req.AddCookie(c)
102 }
103 res, err := f.srv.Client().Do(req)
104 if err != nil {
105 f.t.Fatal(err)
106 }
107 res.Body.Close()
108 seq, _ := strconv.ParseInt(res.Header.Get("Docs-Seq"), 10, 64)
109 return res.StatusCode, seq
110}
111
112func fanout(t *testing.T, f *pushFixture, typists, watchers, posts int) {
113 since := "?push=1&since=" + strconv.FormatInt(f.currentSeq(), 10)
114 type arrival struct {
115 seq int64
116 at time.Time
117 }
118 var watchStreams []*testStream
119 for i := 0; i < watchers; i++ {
120 s := f.open(f.cookies, since, nil)
121 s.hello(t)
122 watchStreams = append(watchStreams, s)
123 }
124 arrivals := make([][]arrival, watchers)
125 var collect sync.WaitGroup
126 total := typists * posts
127 for i, s := range watchStreams {
128 collect.Add(1)
129 go func(i int, s *testStream) {
130 defer collect.Done()
131 for len(arrivals[i]) < total {
132 select {
133 case fr := <-s.frames:
134 seq, _ := strconv.ParseInt(fr.id, 10, 64)
135 if fr.event == "push" {
136 arrivals[i] = append(arrivals[i], arrival{seq, time.Now()})
137 }
138 case <-time.After(10 * time.Second):
139 return
140 }
141 }
142 }(i, s)
143 }
144 stats := f.app.handlers.pushStats
145 reads0, hits0, frames0 := stats.rowReads.Load(), stats.cacheHits.Load(), stats.frames.Load()
146 cpu0, wall0 := processCPU(), time.Now()
147 var mu sync.Mutex
148 sent := map[int64]time.Time{}
149 owns := 0
150 var wg sync.WaitGroup
151 for g := 0; g < typists; g++ {
152 wg.Add(1)
153 go func(g int) {
154 defer wg.Done()
155 own := f.open(f.cookies, since, nil)
156 id, _, _ := own.hello(t)
157 rng := rand.New(rand.NewSource(int64(g)))
158 for i := 0; i < posts; i++ {
159 time.Sleep(time.Duration(60+rng.ExpFloat64()*100) * time.Millisecond)
160 start := time.Now()
161 code, seq := f.postHost(f.update(g*10000+i, fmt.Sprintf("g%dk%d", g, i)), fmt.Sprintf("%s.%d", id, i+1))
162 if code != http.StatusNoContent {
163 t.Errorf("POST %d", code)
164 return
165 }
166 mu.Lock()
167 sent[seq] = start
168 mu.Unlock()
169 }
170 deadline := time.After(5 * time.Second)
171 pushes := 0
172 for n := 0; n < posts; {
173 select {
174 case fr := <-own.frames:
175 switch fr.event {
176 case "own":
177 n++
178 mu.Lock()
179 owns++
180 mu.Unlock()
181 case "push":
182 pushes++
183 default:
184 t.Logf("typist %d: %+v", g, fr)
185 }
186 case <-own.done:
187 t.Logf("typist %d: stream ended after %d own, %d push", g, n, pushes)
188 return
189 case <-deadline:
190 t.Logf("typist %d: %d own, %d push by the deadline", g, n, pushes)
191 return
192 }
193 }
194 }(g)
195 }
196 wg.Wait()
197 collect.Wait()
198 wall, cpu := time.Since(wall0), processCPU()-cpu0
199 var lat []float64
200 for _, list := range arrivals {
201 for _, a := range list {
202 if s, ok := sent[a.seq]; ok {
203 lat = append(lat, float64(a.at.Sub(s).Microseconds())/1000)
204 }
205 }
206 }
207 sort.Float64s(lat)
208 pct := func(p float64) float64 {
209 if len(lat) == 0 {
210 return 0
211 }
212 return lat[int(p*float64(len(lat)-1))]
213 }
214 uploads := float64(total)
215 t.Logf("FANOUT %s: %d uploads, %d watcher frames seen (want %d), %d own; process CPU %.1f ms/s, %.2f ms per upload; row reads %d, cache hits %d, flushes %d; POST -> watcher p50 %.1f ms p95 %.1f ms",
216 t.Name(), total, len(lat), total*watchers, owns, float64(cpu.Milliseconds())/wall.Seconds(), float64(cpu.Microseconds())/1000/uploads,
217 stats.rowReads.Load()-reads0, stats.cacheHits.Load()-hits0, stats.frames.Load()-frames0, pct(0.5), pct(0.95))
218}
219