package api_test import ( "context" "encoding/json" "errors" "slices" "testing" "time" "github.com/jackc/pgx/v5" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" ) func TestAgentStream(t *testing.T) { e := newEnv(t) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) owner := e.browser(t) owner.signup("o@"+uniq("st")+".test", uniq("st-")) slug := uniq("stream-") _, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Before"}) pageID := body["id"].(string) owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Before", "published": true}) sp := e.statuspageClient(t, nil) events := make(chan agentapi.PagesEvent, 16) sp.UseStream(ctx, agentapi.StreamOptions{OnEvent: func(event string, body []byte) { var ev agentapi.PagesEvent if event == agentapi.EventPages && json.Unmarshal(body, &ev) == nil { events <- ev } }}) waitFor(t, 10*time.Second, "stream to open", sp.Streaming) snap, err := sp.Page(ctx, "", slug) if err != nil || snap.Title != "Before" { t.Fatalf("Page() over the stream = %q, %v", snap.Title, err) } if _, err := sp.PageIfChanged(ctx, "", slug, snap.Checksum()); !errors.Is(err, agentapi.ErrNotModified) { t.Errorf("PageIfChanged(current checksum) over the stream error = %v, want not modified", err) } if _, err := sp.Page(ctx, "", uniq("missing-")); !errors.Is(err, agentapi.ErrNotFound) { t.Errorf("Page(missing) over the stream error = %v, want not found", err) } // Editing the page tells the server at once. owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "After", "published": true}) deadline := time.After(10 * time.Second) for told := false; !told; { select { case ev := <-events: told = slices.ContainsFunc(ev.Pages, func(r agentapi.PageRef) bool { return r.Slug == slug }) case <-deadline: t.Fatal("no event for the edited page") } } if snap, err := sp.Page(ctx, "", slug); err != nil || snap.Title != "After" { t.Errorf("Page() after the edit = %q, %v", snap.Title, err) } // A revoked token ends the stream. hello, err := sp.Hello(ctx) if err != nil { t.Fatal(err) } if err := e.asSystem(t, func(tx pgx.Tx) error { _, err := tx.Exec(ctx, `DELETE FROM agents WHERE id = $1`, hello.AgentID) return err }); err != nil { t.Fatal(err) } if _, err := sp.Hello(ctx); !errors.Is(err, agentapi.ErrUnauthorized) { t.Errorf("Hello() with a revoked token error = %v, want unauthorized", err) } waitFor(t, 10*time.Second, "stream to close", func() bool { return !sp.Streaming() }) }