package server import ( "context" "encoding/binary" "fmt" "io" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "sync/atomic" "testing" "time" "golang.org/x/net/websocket" "pageswiki/internal/geckorelay" "pageswiki/internal/store" ) // The real engine runs against a synthetic Wisp HTTP responder. This test never // dials an article server, production source, DNS name or external calendar. func TestFeedGeckoChromium(t *testing.T) { testFeedGeckoChromium(t, false) } func TestFeedGeckoStartupFailureChromium(t *testing.T) { testFeedGeckoChromium(t, true) } func testFeedGeckoChromium(t *testing.T, failure bool) { assets := os.Getenv("PAGESWIKI_GECKO_TEST_ASSETS") if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" || assets == "" { t.Skip("opt-in real Gecko assets") } var connections atomic.Int64 publicHTTPS := !failure && os.Getenv("PAGESWIKI_GECKO_PUBLIC_HTTPS_TEST") == "1" realRelay, err := geckorelay.New(geckoTestKey, assets) if err != nil { t.Fatal(err) } if publicHTTPS { realRelay.Distribution, err = geckorelay.VerifyDistribution(assets) if err != nil { t.Fatal(err) } } backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if failure && strings.HasSuffix(r.URL.Path, "/NotoSansCJKjp-Regular.otf") { http.Error(w, "synthetic startup failure", 503) return } if publicHTTPS { realRelay.ServeHTTP(w, r) return } if _, err := geckorelay.Verify(geckoTestKey, r.Header.Get(geckorelay.GrantHeader), time.Now()); err != nil { http.Error(w, "bad grant", 403) return } if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, geckorelay.DistributionPrefix) { http.ServeFile(w, r, filepath.Join(assets, filepath.Base(r.URL.Path))) return } if r.URL.Path != "/wisp/" { http.NotFound(w, r) return } websocket.Handler(func(ws *websocket.Conn) { connections.Add(1) defer connections.Add(-1) packet := func(kind byte, id uint32, data []byte) []byte { out := make([]byte, 5+len(data)) out[0] = kind binary.LittleEndian.PutUint32(out[1:], id) copy(out[5:], data) return out } websocket.Message.Send(ws, packet(3, 0, []byte{8, 0, 0, 0})) requests := map[uint32]string{} for { var p []byte if websocket.Message.Receive(ws, &p) != nil || len(p) < 5 { return } id := binary.LittleEndian.Uint32(p[1:]) switch p[0] { case 1: requests[id] = "" case 2: requests[id] += string(p[5:]) if !strings.Contains(requests[id], "\r\n\r\n") { continue } body := `Synthetic next page

日本語の記事:学舎の園

` if strings.HasPrefix(requests[id], "GET /next ") { body = `

Second synthetic page

` } response := fmt.Sprintf("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(body), body) websocket.Message.Send(ws, packet(2, id, []byte(response))) websocket.Message.Send(ws, packet(4, id, []byte{2})) delete(requests, id) case 4: delete(requests, id) } } }).ServeHTTP(w, r) })) defer backend.Close() s, token, domain, actor, source := feedFixture(t) configureTestGecko(t, s, domain, backend.URL) p, e := s.store.TaskPreferences(context.Background(), domain, actor) if e != nil { t.Fatal(e) } p.RSSLinkMode = "gecko" if _, e = s.store.SaveTaskPreferences(context.Background(), domain, actor, p, time.Now()); e != nil { t.Fatal(e) } claim, e := s.store.ClaimFeed(context.Background(), source) if e != nil { t.Fatal(e) } articleURL := "http://fixture.invalid/first" if publicHTTPS { articleURL = "https://example.com/" } if e = s.store.CompleteFeed(context.Background(), claim, []store.FeedItem{{ID: "synthetic", Title: "Gecko synthetic fixture", URL: articleURL, Body: "Synthetic test fixture."}}, "", "", "", false); e != nil { t.Fatal(e) } handler := s.handler() web := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if publicHTTPS && r.URL.Path == "/static/js/feed-gecko.js" { js, err := os.ReadFile("static/js/feed-gecko.js") if err != nil { t.Error(err) http.Error(w, "fixture missing", 500) return } w.Header().Set("Content-Type", "text/javascript") io.WriteString(w, strings.Replace(string(js), "engine=new Gecko(", "globalThis.fixtureEngine=engine=new Gecko(", 1)) return } if r.Header.Get("Origin") == "http://"+r.Host { r.Header.Set("Origin", "http://localhost") } r.Host = "localhost" r.Header.Set("Authorization", "Bearer "+token) handler.ServeHTTP(w, r) })) defer web.Close() ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) defer cancel() mode := "synthetic" if failure { mode = "startup-failure" } if publicHTTPS { mode = "public-https" } out, e := exec.CommandContext(ctx, "node", "internal/server/testdata/feed-gecko-browser.mjs", web.URL+"/v/feeds", t.TempDir(), "/tmp/pageswiki-feed-gecko.png", mode).CombinedOutput() if e != nil { t.Fatalf("browser: %v\n%s", e, out) } io.WriteString(os.Stdout, string(out)) for i := 0; i < 30 && connections.Load() != 0; i++ { time.Sleep(100 * time.Millisecond) } if connections.Load() != 0 { t.Fatal("viewer close left relay session alive") } }