| index 2d7344a..4c1c0e5 100644 |
| --- a/internal/docs/live_push_probe_test.go |
| +++ b/internal/docs/live_push_probe_test.go |
| @@ -38,7 +38,11 @@ import ( |
| "bufio" |
| "bytes" |
| "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/base64" |
| "encoding/binary" |
| + "encoding/hex" |
| "encoding/json" |
| "fmt" |
| "io" |
| @@ -48,6 +52,7 @@ import ( |
| "net/http" |
| "net/http/httptest" |
| "os" |
| + "os/exec" |
| "path/filepath" |
| "runtime" |
| "sort" |
| @@ -61,8 +66,21 @@ import ( |
| |
| "github.com/carlosframework/docs/internal/core" |
| "github.com/carlosframework/docs/internal/docs" |
| + _ "modernc.org/sqlite" |
| ) |
| |
| +// probeKeyFingerprint is the content key's fingerprint, as |
| +// content_cipher.go derives it (hex SHA-256 of the key's bytes), which |
| +// MaintainContent wants to activate sealing. |
| +func probeKeyFingerprint(key string) (string, error) { |
| + raw, err := base64.StdEncoding.DecodeString(key) |
| + if err != nil { |
| + return "", err |
| + } |
| + sum := sha256.Sum256(raw) |
| + return hex.EncodeToString(sum[:]), nil |
| +} |
| + |
| func probeNow() float64 { return float64(time.Now().UnixNano()) / 1e6 } |
| |
| func probeEnvInt(name string, def int) int { |
| @@ -175,7 +193,26 @@ func TestLivePushProbeServer(t *testing.T) { |
| defer proxyListener.Close() |
| origin = "http://" + proxyListener.Addr().String() |
| } |
| - app, err := docs.NewForTestWith(t, docs.Config{AllowedAddresses: "probe@example.com", Origin: origin}) |
| + cfg := docs.Config{AllowedAddresses: "probe@example.com", Origin: origin, WarmHandle: os.Getenv("DOCS_LIVE_PROBE_WARM") == "1"} |
| + if os.Getenv("DOCS_LIVE_PROBE_SEAL") == "1" { |
| + // Sealed rows, as production stores them. |
| + cfg.DBPath = filepath.Join(t.TempDir(), "docs.db") |
| + cfg.Env = "development" |
| + cfg.ContentKey = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{71}, 32)) |
| + first, err := docs.New(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + first.Close() |
| + fp, err := probeKeyFingerprint(cfg.ContentKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := docs.MaintainContent(context.Background(), docs.ContentMaintenanceConfig{DBPath: cfg.DBPath, ContentKey: cfg.ContentKey, ExpectedFingerprint: fp}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + app, err := docs.NewForTestWith(t, cfg) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -283,9 +320,9 @@ func TestLivePushProbeServer(t *testing.T) { |
| for _, c := range cookies { |
| cookie = append(cookie, c.Name+"="+c.Value) |
| } |
| - cfg := map[string]any{"origin": origin, "direct": "http://" + appListener.Addr().String(), "sqids": sqids, |
| + connCfg := map[string]any{"origin": origin, "direct": "http://" + appListener.Addr().String(), "sqids": sqids, |
| "cookie": strings.Join(cookie, "; "), "cookies": cookies, "rtt_ms": rtt, "pid": os.Getpid()} |
| - data, _ := json.Marshal(cfg) |
| + data, _ := json.Marshal(connCfg) |
| if err := os.WriteFile(filepath.Join(dir, "connection.json"), data, 0600); err != nil { |
| t.Fatal(err) |
| } |
| @@ -345,6 +382,12 @@ type probeClient struct { |
| fetches [][2]float64 // (t done, Docs-Seq) per fetch |
| fetchN int64 |
| fetchByte int64 |
| + push bool |
| + streamID string |
| + counter int |
| + sentOwn map[string]bool |
| + pushN int64 |
| + ownN int64 |
| } |
| |
| func newProbeClient(conn *probeConn, sqid string, native bool) *probeClient { |
| @@ -365,6 +408,17 @@ func (c *probeClient) request(method, path string, body []byte) (*http.Response, |
| if method == "POST" { |
| req.Header.Set("Origin", c.conn.Origin) |
| req.Header.Set("Content-Type", "application/octet-stream") |
| + c.mu.Lock() |
| + if c.push && c.streamID != "" { |
| + c.counter++ |
| + n := strconv.Itoa(c.counter) |
| + if c.sentOwn == nil { |
| + c.sentOwn = map[string]bool{} |
| + } |
| + c.sentOwn[n] = true |
| + req.Header.Set("Docs-Stream", c.streamID+"."+n) |
| + } |
| + c.mu.Unlock() |
| } |
| res, err := c.http.Do(req) |
| if err != nil { |
| @@ -433,9 +487,54 @@ func (c *probeClient) drain() { |
| }() |
| } |
| |
| +// frame handles a push-stream event (spec ยง3.1): push and own advance the |
| +// cursor when exactly next; anything else fetches. |
| +func (c *probeClient) frame(event, data string) { |
| + now := probeNow() |
| + parts := strings.SplitN(data, " ", 2) |
| + seq, _ := strconv.ParseInt(parts[0], 10, 64) |
| + c.mu.Lock() |
| + switch event { |
| + case "hello": |
| + c.streamID = parts[0] |
| + c.mu.Unlock() |
| + return |
| + case "push", "own": |
| + c.events = append(c.events, [2]float64{now, float64(seq)}) |
| + ok := seq == c.cursor+1 && !c.fetching |
| + if event == "own" { |
| + ok = ok && len(parts) == 2 && c.sentOwn[parts[1]] |
| + c.ownN++ |
| + } else { |
| + c.pushN++ |
| + } |
| + if ok { |
| + c.cursor = seq |
| + c.fetches = append(c.fetches, [2]float64{now, float64(seq)}) |
| + c.mu.Unlock() |
| + return |
| + } |
| + if seq <= c.cursor { |
| + c.mu.Unlock() |
| + return |
| + } |
| + c.mu.Unlock() |
| + c.drain() |
| + return |
| + } |
| + c.mu.Unlock() |
| + c.announce(seq) |
| +} |
| + |
| func (c *probeClient) listen(stop <-chan struct{}, tag string) { |
| go func() { |
| - req, _ := http.NewRequest("GET", c.conn.Origin+"/d/"+c.sqid+"/stream?probe="+tag, nil) |
| + url := c.conn.Origin + "/d/" + c.sqid + "/stream?probe=" + tag |
| + if c.push { |
| + c.mu.Lock() |
| + url += fmt.Sprintf("&push=1&since=%d", c.cursor) |
| + c.mu.Unlock() |
| + } |
| + req, _ := http.NewRequest("GET", url, nil) |
| req.Header.Set("Cookie", c.conn.Cookie) |
| tr := &http.Transport{} |
| res, err := (&http.Client{Transport: tr}).Do(req) |
| @@ -444,12 +543,22 @@ func (c *probeClient) listen(stop <-chan struct{}, tag string) { |
| } |
| go func() { <-stop; res.Body.Close() }() |
| sc := bufio.NewScanner(res.Body) |
| + sc.Buffer(make([]byte, 64<<10), 1<<20) |
| + event, data := "", "" |
| for sc.Scan() { |
| line := sc.Text() |
| - if strings.HasPrefix(line, "data:") { |
| - if seq, err := strconv.ParseInt(strings.TrimSpace(line[5:]), 10, 64); err == nil { |
| + switch { |
| + case strings.HasPrefix(line, "event:"): |
| + event = strings.TrimSpace(line[6:]) |
| + case strings.HasPrefix(line, "data:"): |
| + data = strings.TrimSpace(line[5:]) |
| + case line == "": |
| + if c.push && event != "" { |
| + c.frame(event, data) |
| + } else if seq, err := strconv.ParseInt(data, 10, 64); err == nil && data != "" { |
| c.announce(seq) |
| } |
| + event, data = "", "" |
| } |
| } |
| }() |
| @@ -531,7 +640,7 @@ func TestLivePushProbeClients(t *testing.T) { |
| default: |
| t.Fatalf("unknown policy %q", policy) |
| } |
| - if typists > len(conn.Sqids) { |
| + if shared := probeEnvInt("DOCS_LIVE_PROBE_SHARED", 0); shared == 0 && typists > len(conn.Sqids) { |
| t.Fatalf("%d typists, %d documents", typists, len(conn.Sqids)) |
| } |
| stats := func() map[string]float64 { |
| @@ -547,23 +656,40 @@ func TestLivePushProbeClients(t *testing.T) { |
| |
| stop := make(chan struct{}) |
| type typist struct { |
| - sender, watcher *probeClient |
| - keys []probeKey |
| - batches []*probeBatch |
| + sender *probeClient |
| + watchers []*probeClient |
| + keys []probeKey |
| + batches []*probeBatch |
| + } |
| + push := os.Getenv("DOCS_LIVE_PROBE_PUSH") == "1" |
| + shared := probeEnvInt("DOCS_LIVE_PROBE_SHARED", 0) // >0: every typist in one document, with this many watchers |
| + open := func(sqid string, native bool, tag string) *probeClient { |
| + c := newProbeClient(&conn, sqid, native) |
| + c.push = push |
| + res, _, err := c.request("GET", "/d/"+sqid+"/updates", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c.cursor, _ = strconv.ParseInt(res.Header.Get("Docs-Seq"), 10, 64) |
| + c.listen(stop, tag) |
| + return c |
| } |
| all := make([]*typist, typists) |
| + var sharedWatchers []*probeClient |
| + for w := 0; w < shared; w++ { |
| + sharedWatchers = append(sharedWatchers, open(conn.Sqids[0], false, "watcher")) |
| + } |
| for i := range all { |
| - sqid := conn.Sqids[i] |
| - ty := &typist{sender: newProbeClient(&conn, sqid, native), watcher: newProbeClient(&conn, sqid, false)} |
| - for _, c := range []*probeClient{ty.sender, ty.watcher} { |
| - _, body, err := c.request("GET", "/d/"+sqid+"/updates", nil) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - _ = body |
| + sqid := conn.Sqids[0] |
| + if shared == 0 { |
| + sqid = conn.Sqids[i] |
| + } |
| + ty := &typist{sender: open(sqid, native, "sender")} |
| + if shared > 0 { |
| + ty.watchers = sharedWatchers |
| + } else { |
| + ty.watchers = []*probeClient{open(sqid, false, "watcher")} |
| } |
| - ty.sender.listen(stop, "sender") |
| - ty.watcher.listen(stop, "watcher") |
| all[i] = ty |
| } |
| time.Sleep(1500 * time.Millisecond) // connect-time events settle |
| @@ -723,43 +849,51 @@ func TestLivePushProbeClients(t *testing.T) { |
| t.Fatal(err) |
| } |
| fmt.Fprintln(csv, "typist,key,at,send,ack,seq,announced,fetched") |
| + var pushes, owns int64 |
| + counted := map[*probeClient]bool{} |
| for i, ty := range all { |
| - w := ty.watcher |
| - w.mu.Lock() |
| - evs, fs := append([][2]float64(nil), w.events...), append([][2]float64(nil), w.fetches...) |
| - watcherFetches += w.fetchN |
| - events += int64(len(evs)) |
| - w.mu.Unlock() |
| ty.sender.mu.Lock() |
| senderFetches += ty.sender.fetchN |
| + owns += ty.sender.ownN |
| ty.sender.mu.Unlock() |
| for _, b := range ty.batches { |
| posts++ |
| reqBytes += b.reqBytes |
| } |
| sends += len(ty.batches) |
| - first := func(list [][2]float64, seq int64, after float64) float64 { |
| - for _, e := range list { |
| - if e[1] >= float64(seq) && e[0] >= after { |
| - return e[0] |
| + for _, w := range ty.watchers { |
| + w.mu.Lock() |
| + evs, fs := append([][2]float64(nil), w.events...), append([][2]float64(nil), w.fetches...) |
| + if !counted[w] { |
| + counted[w] = true |
| + watcherFetches += w.fetchN |
| + events += int64(len(evs)) |
| + pushes += w.pushN |
| + } |
| + w.mu.Unlock() |
| + first := func(list [][2]float64, seq int64, after float64) float64 { |
| + for _, e := range list { |
| + if e[1] >= float64(seq) && e[0] >= after { |
| + return e[0] |
| + } |
| } |
| + return math.NaN() |
| } |
| - return math.NaN() |
| - } |
| - for k, key := range ty.keys { |
| - b := key.batch |
| - if b == nil || b.seq == 0 { |
| - continue |
| + for k, key := range ty.keys { |
| + b := key.batch |
| + if b == nil || b.seq == 0 { |
| + continue |
| + } |
| + ann := first(evs, b.seq, b.send) |
| + got := first(fs, b.seq, b.send) |
| + fmt.Fprintf(csv, "%d,%d,%.3f,%.3f,%.3f,%d,%.3f,%.3f\n", i, k, key.at, b.send, b.ack, b.seq, ann, got) |
| + pace = append(pace, b.send-key.at) |
| + post = append(post, b.ack-b.send) |
| + announce = append(announce, ann-b.send) |
| + fetchAfter = append(fetchAfter, got-ann) |
| + viaFetch = append(viaFetch, got-key.at) |
| + viaPush = append(viaPush, ann-key.at) |
| } |
| - ann := first(evs, b.seq, b.send) |
| - got := first(fs, b.seq, b.send) |
| - fmt.Fprintf(csv, "%d,%d,%.3f,%.3f,%.3f,%d,%.3f,%.3f\n", i, k, key.at, b.send, b.ack, b.seq, ann, got) |
| - pace = append(pace, b.send-key.at) |
| - post = append(post, b.ack-b.send) |
| - announce = append(announce, ann-b.send) |
| - fetchAfter = append(fetchAfter, got-ann) |
| - viaFetch = append(viaFetch, got-key.at) |
| - viaPush = append(viaPush, ann-key.at) |
| } |
| } |
| csv.Close() |
| @@ -770,9 +904,10 @@ func TestLivePushProbeClients(t *testing.T) { |
| "seconds": seconds, "failed_posts": failed.Load(), |
| "pace": pp(pace), "post_rtt": pp(post), "send_to_announce": pp(announce), "announce_to_fetched": pp(fetchAfter), |
| "key_to_fetched": pp(viaFetch), "key_to_announced": pp(viaPush), |
| - "posts_per_s_per_typist": float64(posts) / seconds / float64(typists), |
| - "keys_per_s_per_typist": float64(keys) / seconds, |
| - "watcher_fetches_per_s_per_doc": float64(watcherFetches) / seconds / float64(typists), |
| + "posts_per_s_per_typist": float64(posts) / seconds / float64(typists), |
| + "keys_per_s_per_typist": float64(keys) / seconds, |
| + "watcher_fetches_per_s_per_doc": float64(watcherFetches) / seconds / float64(typists), |
| + "push": push, "shared_watchers": shared, "watcher_gets_total": watcherFetches, "push_frames": pushes, "own_frames": owns, |
| "sender_echo_fetches_per_typist": float64(senderFetches) / float64(typists), |
| "watcher_events": events, |
| "post_bytes_mean": float64(reqBytes) / float64(posts), |
| @@ -860,3 +995,150 @@ func TestLivePushProbeApplyCost(t *testing.T) { |
| fmt.Printf("LIVEAPPLY %s cold (new handle + seed + tail + update) p50 %.2f p95 %.2f ms; warm apply p50 %.3f p95 %.3f ms\n", |
| filepath.Base(seedPath), probePercentile(cold, .5), probePercentile(cold, .95), probePercentile(warm, .5), probePercentile(warm, .95)) |
| } |
| + |
| +// TestLivePushProbeWarmMemory prices a warm handle's memory: N handles of |
| +// one seed held at once (each a WASM instance with the document applied), |
| +// as Go heap and as process RSS. Skipped unless DOCS_LIVE_PROBE_MEM names |
| +// a seed. |
| +func TestLivePushProbeWarmMemory(t *testing.T) { |
| + seedPath := os.Getenv("DOCS_LIVE_PROBE_MEM") |
| + if seedPath == "" { |
| + t.Skip("set DOCS_LIVE_PROBE_MEM") |
| + } |
| + ctx := context.Background() |
| + seed, err := os.ReadFile(seedPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rt, err := core.New(ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rt.Close(ctx) |
| + rss := func() float64 { |
| + out, _ := exec.Command("ps", "-o", "rss=", "-p", strconv.Itoa(os.Getpid())).Output() |
| + kb, _ := strconv.ParseFloat(strings.TrimSpace(string(out)), 64) |
| + return kb / 1024 |
| + } |
| + heap := func() float64 { |
| + runtime.GC() |
| + var ms runtime.MemStats |
| + runtime.ReadMemStats(&ms) |
| + return float64(ms.HeapInuse) / 1e6 |
| + } |
| + const n = 32 |
| + h0, r0 := heap(), rss() |
| + var handles []*core.Handle |
| + for i := 0; i < n; i++ { |
| + h, err := rt.NewDoc(ctx, fmt.Sprintf("g%d", i), uint64(i+1)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := h.Apply(ctx, seed); err != nil { |
| + t.Fatal(err) |
| + } |
| + handles = append(handles, h) |
| + } |
| + h1, r1 := heap(), rss() |
| + fmt.Printf("LIVEMEM %s: %d warm handles: heap +%.1f MB (%.2f MB each), RSS +%.1f MB (%.2f MB each)\n", |
| + filepath.Base(seedPath), n, h1-h0, (h1-h0)/n, r1-r0, (r1-r0)/n) |
| + for _, h := range handles { |
| + h.Close(ctx) |
| + } |
| +} |
| + |
| +// TestLivePushProbeRowSize measures what one keystroke's row costs on disk |
| +// with content sealing on: 2,000 single-key updates POSTed through the app, |
| +// database and WAL checkpointed, size per row. Skipped unless |
| +// DOCS_LIVE_PROBE_ROWS names a gen-typing.mjs directory and |
| +// DOCS_LIVE_PROBE_SEED a seed. |
| +func TestLivePushProbeRowSize(t *testing.T) { |
| + dir, seedPath := os.Getenv("DOCS_LIVE_PROBE_ROWS"), os.Getenv("DOCS_LIVE_PROBE_SEED") |
| + if dir == "" || seedPath == "" { |
| + t.Skip("set DOCS_LIVE_PROBE_ROWS and DOCS_LIVE_PROBE_SEED") |
| + } |
| + seed, _ := os.ReadFile(seedPath) |
| + cfg := docs.Config{AllowedAddresses: "probe@example.com", Origin: "http://127.0.0.1", DBPath: filepath.Join(t.TempDir(), "docs.db"), Env: "development", |
| + ContentKey: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{71}, 32))} |
| + first, err := docs.New(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + first.Close() |
| + fp, _ := probeKeyFingerprint(cfg.ContentKey) |
| + if err := docs.MaintainContent(context.Background(), docs.ContentMaintenanceConfig{DBPath: cfg.DBPath, ContentKey: cfg.ContentKey, ExpectedFingerprint: fp}); err != nil { |
| + t.Fatal(err) |
| + } |
| + app, err := docs.NewForTestWith(t, cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cookies := signInCookies(t, app, "probe@example.com") |
| + do := func(method, path string, body []byte) *httptest.ResponseRecorder { |
| + req := httptest.NewRequest(method, path, bytes.NewReader(body)) |
| + req.Header.Set("Origin", cfg.Origin) |
| + if method == "POST" && path == "/documents" { |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + } else { |
| + req.Header.Set("Content-Type", "application/octet-stream") |
| + } |
| + for _, c := range cookies { |
| + req.AddCookie(c) |
| + } |
| + rec := httptest.NewRecorder() |
| + app.Handler().ServeHTTP(rec, req) |
| + return rec |
| + } |
| + rec := do("POST", "/documents", []byte("title=Rows")) |
| + sqid := strings.TrimPrefix(rec.Header().Get("Location"), "/d/") |
| + if rec := do("POST", "/d/"+sqid+"/updates", seed); rec.Code/100 != 2 { |
| + t.Fatal(rec.Code) |
| + } |
| + raw, err := sql.Open("sqlite", cfg.DBPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer raw.Close() |
| + checkpoint := func() { |
| + if _, err := raw.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + fileSize := func(suffix string) int64 { |
| + st, err := os.Stat(cfg.DBPath + suffix) |
| + if err != nil { |
| + return 0 |
| + } |
| + return st.Size() |
| + } |
| + updates, err := loadProbeUpdates(filepath.Join(dir, "t0.bin")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + post := func(k int) int { |
| + u := updates[[2]int{k % 300, k % 300}] |
| + if rec := do("POST", "/d/"+sqid+"/updates", u); rec.Code/100 != 2 { |
| + t.Fatalf("POST %d: %d", k, rec.Code) |
| + } |
| + return len(u) |
| + } |
| + // WAL bytes per commit: a short run that stays under the autocheckpoint. |
| + checkpoint() |
| + const short = 100 |
| + for k := 0; k < short; k++ { |
| + post(k) |
| + } |
| + walPerCommit := float64(fileSize("-wal")) / short |
| + // Storage per row: database file growth over 2,000 rows, checkpointed. |
| + checkpoint() |
| + before := fileSize("") |
| + const n = 2000 |
| + var payload int |
| + for k := 0; k < n; k++ { |
| + payload += post(k) |
| + } |
| + checkpoint() |
| + after := fileSize("") |
| + fmt.Printf("LIVEROWS sealed: payload %.1f B/row; database file growth %.0f B/row over %d rows (includes %d snapshots); WAL written per commit %.0f B\n", |
| + float64(payload)/n, float64(after-before)/n, n, n/256, walPerCommit) |
| +} |