oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "io"
9 "net"
10 "net/http"
11 "net/http/cookiejar"
12 "net/url"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "regexp"
17 "runtime"
18 "strings"
19 "sync"
20 "syscall"
21 "testing"
22 "time"
23)
24
25// A stop with an editor open finishes at once and exits 0. The real
26// binary, a signed-in live-update stream open on one of its documents,
27// and SIGTERM, as the platform stops an instance.
28//
29// net/http's graceful shutdown waits for every request in progress and
30// cancels none of them, and a stream ends only when its client leaves or
31// its five-minute TTL runs out. So the process waited out rastrillo's
32// whole ten-second budget and exited 1 with "context deadline exceeded"
33// (2026-10-26 12:49:18-12:49:29, when the platform stopped every instance
34// on the box: Sheets and Slides exited 0 in two seconds, and Docs, with
35// one editor open, did not), answering nothing new the whole time.
36func TestStoppingWithAnEditorOpenExitsAtOnce(t *testing.T) {
37 if runtime.GOOS == "windows" {
38 t.Skip("signals and unix sockets")
39 }
40 dir := t.TempDir()
41 binary := filepath.Join(dir, "docs")
42 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
43 defer cancel()
44 build := exec.CommandContext(ctx, filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", binary, ".")
45 build.Env = append(os.Environ(), "CGO_ENABLED=0")
46 if out, err := build.CombinedOutput(); err != nil {
47 t.Fatalf("build: %v\n%s", err, out)
48 }
49
50 socket := filepath.Join(dir, "docs.sock")
51 output := &lockedBuffer{}
52 server := exec.CommandContext(ctx, binary, "-env", "development", "-socket", socket, "-db", filepath.Join(dir, "docs.db"))
53 server.Env = append(os.Environ(), "DOCS_ORIGIN=http://localhost", "DOCS_SEED_ADDRESS=", "DOCS_SAMPLE_DOCUMENTS=0")
54 server.Stdout = output
55 server.Stderr = output
56 if err := server.Start(); err != nil {
57 t.Fatal(err)
58 }
59 exited := make(chan error, 1)
60 go func() { exited <- server.Wait() }()
61 t.Cleanup(func() {
62 _ = server.Process.Kill()
63 <-exited
64 if t.Failed() {
65 t.Logf("process output:\n%s", output.String())
66 }
67 })
68
69 transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
70 return (&net.Dialer{}).DialContext(ctx, "unix", socket)
71 }}
72 defer transport.CloseIdleConnections()
73 jar, _ := cookiejar.New(nil)
74 client := &http.Client{Transport: transport, Jar: jar, Timeout: 5 * time.Second}
75 deadline := time.Now().Add(30 * time.Second)
76 for {
77 res, err := client.Get("http://localhost/healthz")
78 if err == nil {
79 _ = res.Body.Close()
80 break
81 }
82 if time.Now().After(deadline) {
83 t.Fatalf("the process never answered: %v", err)
84 }
85 time.Sleep(25 * time.Millisecond)
86 }
87 post := func(path string, form url.Values) *http.Response {
88 t.Helper()
89 req, _ := http.NewRequest(http.MethodPost, "http://localhost"+path, strings.NewReader(form.Encode()))
90 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
91 req.Header.Set("Sec-Fetch-Site", "same-origin")
92 res, err := client.Do(req)
93 if err != nil {
94 t.Fatalf("POST %s: %v", path, err)
95 }
96 _, _ = io.Copy(io.Discard, res.Body)
97 _ = res.Body.Close()
98 return res
99 }
100
101 // Signed in the way a person is: the link development logs instead of
102 // mailing, spent through the door's own form.
103 post("/signin", url.Values{"address": {"stopping@example.com"}, "force": {"1"}})
104 link := regexp.MustCompile(`http://localhost/auth/verify\?token=[A-Za-z0-9_-]+`)
105 var token string
106 for end := time.Now().Add(10 * time.Second); token == "" && time.Now().Before(end); time.Sleep(25 * time.Millisecond) {
107 if m := link.FindString(output.String()); m != "" {
108 u, _ := url.Parse(m)
109 token = u.Query().Get("token")
110 }
111 }
112 if token == "" {
113 t.Fatal("no sign-in link was logged")
114 }
115 post("/auth/verify", url.Values{"token": {token}})
116 created := post("/documents", url.Values{"title": {"Open while stopping"}})
117 if !strings.HasPrefix(created.Request.URL.Path, "/d/") {
118 t.Fatalf("creating a document ended at %s, not a document: not signed in?", created.Request.URL)
119 }
120
121 streamer := &http.Client{Transport: transport, Jar: jar}
122 res, err := streamer.Get("http://localhost" + created.Request.URL.Path + "/stream")
123 if err != nil {
124 t.Fatal(err)
125 }
126 defer res.Body.Close()
127 if res.StatusCode != http.StatusOK || !strings.HasPrefix(res.Header.Get("Content-Type"), "text/event-stream") {
128 t.Fatalf("stream: %d %s", res.StatusCode, res.Header.Get("Content-Type"))
129 }
130 events := bufio.NewReader(res.Body)
131 if line, err := events.ReadString('\n'); err != nil || !strings.HasPrefix(line, "event: update") {
132 t.Fatalf("the stream's first line is %q (%v), want its connect-time event", line, err)
133 }
134 ended := make(chan struct{})
135 go func() {
136 _, _ = io.Copy(io.Discard, events)
137 close(ended)
138 }()
139
140 stopped := time.Now()
141 if err := server.Process.Signal(syscall.SIGTERM); err != nil {
142 t.Fatal(err)
143 }
144 select {
145 case err := <-exited:
146 exited <- err // for the cleanup
147 took := time.Since(stopped)
148 var exit *exec.ExitError
149 if errors.As(err, &exit) {
150 t.Errorf("the process exited %d after %v, want 0", exit.ExitCode(), took.Round(time.Millisecond))
151 } else if err != nil {
152 t.Errorf("waiting for the process: %v", err)
153 }
154 if took > 3*time.Second {
155 t.Errorf("stopping took %v with a stream open; the graceful shutdown waited on it", took.Round(time.Millisecond))
156 }
157 case <-time.After(20 * time.Second):
158 t.Fatal("the process did not exit within 20s of SIGTERM")
159 }
160 select {
161 case <-ended:
162 case <-time.After(time.Second):
163 t.Error("the stream was still open after the process exited")
164 }
165}
166
167// lockedBuffer is the process's output, written by its pipes while the
168// test reads it.
169type lockedBuffer struct {
170 mu sync.Mutex
171 b bytes.Buffer
172}
173
174func (l *lockedBuffer) Write(p []byte) (int, error) {
175 l.mu.Lock()
176 defer l.mu.Unlock()
177 return l.b.Write(p)
178}
179
180func (l *lockedBuffer) String() string {
181 l.mu.Lock()
182 defer l.mu.Unlock()
183 return l.b.String()
184}
185