| 1 | package main |
| 2 | |
| 3 | import ( |
| 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 decks, and |
| 27 | // 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 TTL runs out. So the process waited out rastrillo's whole |
| 32 | // ten-second budget and exited 1 with "context deadline exceeded" — Docs |
| 33 | // did, 2026-10-26 12:49, when the platform stopped every instance on the |
| 34 | // box (Docs #94). Slides exited 0 then, so no stream of its was open; with |
| 35 | // one open it would have done the same. internal/slides/drain.go. |
| 36 | func TestStoppingWithAStreamOpenExitsAtOnce(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, "slides") |
| 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 | // The socket in a short directory of its own: a unix socket's path is |
| 51 | // capped at 104 bytes on macOS, and t.TempDir under macOS's default |
| 52 | // $TMPDIR (/var/folders/…) runs past it, so the server cannot listen. |
| 53 | sockets, err := os.MkdirTemp("/tmp", "slides") |
| 54 | if err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | t.Cleanup(func() { os.RemoveAll(sockets) }) |
| 58 | socket := filepath.Join(sockets, "slides.sock") |
| 59 | output := &lockedBuffer{} |
| 60 | server := exec.CommandContext(ctx, binary, "-env", "development", "-socket", socket, "-db", filepath.Join(dir, "slides.db")) |
| 61 | server.Env = append(os.Environ(), "SLIDES_ORIGIN=http://localhost") |
| 62 | server.Stdout = output |
| 63 | server.Stderr = output |
| 64 | if err := server.Start(); err != nil { |
| 65 | t.Fatal(err) |
| 66 | } |
| 67 | exited := make(chan error, 1) |
| 68 | go func() { exited <- server.Wait() }() |
| 69 | t.Cleanup(func() { |
| 70 | _ = server.Process.Kill() |
| 71 | <-exited |
| 72 | if t.Failed() { |
| 73 | t.Logf("process output:\n%s", output.String()) |
| 74 | } |
| 75 | }) |
| 76 | |
| 77 | transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 78 | return (&net.Dialer{}).DialContext(ctx, "unix", socket) |
| 79 | }} |
| 80 | defer transport.CloseIdleConnections() |
| 81 | jar, _ := cookiejar.New(nil) |
| 82 | client := &http.Client{Transport: transport, Jar: jar, Timeout: 5 * time.Second} |
| 83 | deadline := time.Now().Add(30 * time.Second) |
| 84 | for { |
| 85 | res, err := client.Get("http://localhost/healthz") |
| 86 | if err == nil { |
| 87 | _ = res.Body.Close() |
| 88 | break |
| 89 | } |
| 90 | if time.Now().After(deadline) { |
| 91 | t.Fatalf("the process never answered: %v", err) |
| 92 | } |
| 93 | time.Sleep(25 * time.Millisecond) |
| 94 | } |
| 95 | post := func(path string, form url.Values) *http.Response { |
| 96 | t.Helper() |
| 97 | req, _ := http.NewRequest(http.MethodPost, "http://localhost"+path, strings.NewReader(form.Encode())) |
| 98 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 99 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 100 | res, err := client.Do(req) |
| 101 | if err != nil { |
| 102 | t.Fatalf("POST %s: %v", path, err) |
| 103 | } |
| 104 | _, _ = io.Copy(io.Discard, res.Body) |
| 105 | _ = res.Body.Close() |
| 106 | return res |
| 107 | } |
| 108 | |
| 109 | // Signed in the way a person is: the link development logs instead of |
| 110 | // mailing, spent through the door's own form. |
| 111 | post("/signin", url.Values{"address": {"stopping@example.com"}, "force": {"1"}}) |
| 112 | link := regexp.MustCompile(`http://localhost/auth/verify\?token=[A-Za-z0-9_-]+`) |
| 113 | var token string |
| 114 | for end := time.Now().Add(10 * time.Second); token == "" && time.Now().Before(end); time.Sleep(25 * time.Millisecond) { |
| 115 | if m := link.FindString(output.String()); m != "" { |
| 116 | u, _ := url.Parse(m) |
| 117 | token = u.Query().Get("token") |
| 118 | } |
| 119 | } |
| 120 | if token == "" { |
| 121 | t.Fatal("no sign-in link was logged") |
| 122 | } |
| 123 | post("/auth/verify", url.Values{"token": {token}}) |
| 124 | created := post("/decks", url.Values{"title": {"Open while stopping"}, "theme": {"ink"}}) |
| 125 | deck := regexp.MustCompile(`^/d/[^/]+`).FindString(created.Request.URL.Path) |
| 126 | if deck == "" { |
| 127 | t.Fatalf("creating a deck ended at %s, not a deck: not signed in?", created.Request.URL) |
| 128 | } |
| 129 | |
| 130 | streamer := &http.Client{Transport: transport, Jar: jar} |
| 131 | res, err := streamer.Get("http://localhost" + deck + "/stream") |
| 132 | if err != nil { |
| 133 | t.Fatal(err) |
| 134 | } |
| 135 | defer res.Body.Close() |
| 136 | if res.StatusCode != http.StatusOK || !strings.HasPrefix(res.Header.Get("Content-Type"), "text/event-stream") { |
| 137 | t.Fatalf("stream: %d %s", res.StatusCode, res.Header.Get("Content-Type")) |
| 138 | } |
| 139 | events := bufio.NewReader(res.Body) |
| 140 | if line, err := events.ReadString('\n'); err != nil || !strings.HasPrefix(line, "event: update") { |
| 141 | t.Fatalf("the stream's first line is %q (%v), want its connect-time event", line, err) |
| 142 | } |
| 143 | ended := make(chan struct{}) |
| 144 | go func() { |
| 145 | _, _ = io.Copy(io.Discard, events) |
| 146 | close(ended) |
| 147 | }() |
| 148 | |
| 149 | stopped := time.Now() |
| 150 | if err := server.Process.Signal(syscall.SIGTERM); err != nil { |
| 151 | t.Fatal(err) |
| 152 | } |
| 153 | select { |
| 154 | case err := <-exited: |
| 155 | exited <- err // for the cleanup |
| 156 | took := time.Since(stopped) |
| 157 | var exit *exec.ExitError |
| 158 | if errors.As(err, &exit) { |
| 159 | t.Errorf("the process exited %d after %v, want 0", exit.ExitCode(), took.Round(time.Millisecond)) |
| 160 | } else if err != nil { |
| 161 | t.Errorf("waiting for the process: %v", err) |
| 162 | } |
| 163 | if took > 3*time.Second { |
| 164 | t.Errorf("stopping took %v with a stream open; the graceful shutdown waited on it", took.Round(time.Millisecond)) |
| 165 | } |
| 166 | case <-time.After(20 * time.Second): |
| 167 | t.Fatal("the process did not exit within 20s of SIGTERM") |
| 168 | } |
| 169 | select { |
| 170 | case <-ended: |
| 171 | case <-time.After(time.Second): |
| 172 | t.Error("the stream was still open after the process exited") |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | // lockedBuffer is the process's output, written by its pipes while the |
| 177 | // test reads it. |
| 178 | type lockedBuffer struct { |
| 179 | mu sync.Mutex |
| 180 | b bytes.Buffer |
| 181 | } |
| 182 | |
| 183 | func (l *lockedBuffer) Write(p []byte) (int, error) { |
| 184 | l.mu.Lock() |
| 185 | defer l.mu.Unlock() |
| 186 | return l.b.Write(p) |
| 187 | } |
| 188 | |
| 189 | func (l *lockedBuffer) String() string { |
| 190 | l.mu.Lock() |
| 191 | defer l.mu.Unlock() |
| 192 | return l.b.String() |
| 193 | } |
| 194 | |