mirror of
https://github.com/go-gitea/gitea.git
synced 2026-08-03 14:54:28 +00:00
13d0f24423
* Closes #36942 * Fixes #19265 Replaces the SSE-based push channel (`/user/events`) with a WebSocket endpoint (`/-/ws`). ### What changes - **New `/-/ws` endpoint** (authenticated). One WebSocket per origin, shared across tabs via a single `SharedWorker`. - **Pubsub broker** (`services/pubsub`) for fan-out by topic, behind a `Broker` interface. `MemoryBroker` is the default (single process); a Redis backend is available for multi-process setups, configured via `[websocket].PUBSUB_TYPE` / `PUBSUB_CONN_STR`. The internal Gitea queue was not usable here because it has FIFO/single-consumer semantics. - **Push-only event production.** Events are emitted by write-triggered notifiers — `NotificationCountChange`, `PublishStopwatchesForUser`, and the logout publisher — wired into the existing `notify.Notifier` interface. No server-side pollers. - **Typed pub/sub on the client.** `web_src/js/modules/worker.ts` is a singleton transport; features subscribe per event type via `onUserEvent('notification-count', cb)` instead of branching on `event.data.type`. - **Wire contract** (`UserEventType` union) is shared between the worker and consumers via `web_src/js/types.ts`, kept in sync with `services/websocket/events.go`. - **Client-side periodic polling fallback** kicks in only when the WebSocket cannot be established (e.g. proxy blocks WS, browser lacks module-SharedWorker support). ### What's removed - `modules/eventsource` (SSE manager, run loop, messenger). - `/user/events` route and `tests/integration/eventsource_test.go`. - All server-side polling for stopwatches and notification counts. ### Stopwatch multi-tab fix The navbar stopwatch icon was previously rendered conditionally on `{{if $activeStopwatch}}`, so tabs loaded before the timer started had no DOM element to update. The icon and popup are now always rendered (toggled with `tw-hidden`), and the start/stop/cancel handlers POST silently so all open tabs reflect the change in real time. ### Deployment note WebSocket needs the upgrade headers to pass through a reverse proxy, e.g. for nginx: ```nginx proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; ``` Without them the WebSocket cannot be established, and after 3 consecutive failed opens the shared worker signals `push-unavailable`: the notification count and stopwatch fall back to periodic polling on the existing `[ui.notification]` timeouts. Real-time push is lost, the features keep working. The reverse-proxy docs need the same note (see the `docs-update-needed` label). --------- Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: wxiaoguang <wxiaoguang@gmail.com> Co-authored-by: Epid <rexmrj@gmail.com>
171 lines
4.5 KiB
Go
171 lines
4.5 KiB
Go
// Copyright 2026 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package pubsub
|
|
|
|
import (
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
// newBrokerFunc builds a fresh Broker bound to the test's lifecycle.
|
|
type newBrokerFunc func(t *testing.T) Broker
|
|
|
|
// testBrokerBasic runs the behavior every Broker backend must share. Each backend
|
|
// invokes it from its own *_test.go (like testQueueBasic in modules/queue) so
|
|
// memory and redis prove identical semantics against the same scenarios.
|
|
//
|
|
// recvTimeout absorbs redis's network round-trip (memory delivers synchronously).
|
|
func testBrokerBasic(t *testing.T, newBroker newBrokerFunc, recvTimeout time.Duration) {
|
|
t.Run("PublishWithoutSubscribers", func(t *testing.T) {
|
|
b := newBroker(t)
|
|
b.Publish("nobody", []byte("msg")) // must not block or panic
|
|
})
|
|
|
|
t.Run("SubscribeReceivesPublished", func(t *testing.T) {
|
|
b := newBroker(t)
|
|
ch, cancel := b.Subscribe("topic")
|
|
defer cancel()
|
|
|
|
b.Publish("topic", []byte("hello"))
|
|
assert.Equal(t, []byte("hello"), recvWithin(t, ch, recvTimeout))
|
|
})
|
|
|
|
t.Run("FanOutToAllSubscribers", func(t *testing.T) {
|
|
b := newBroker(t)
|
|
const n = 3
|
|
channels := make([]<-chan []byte, n)
|
|
for i := range n {
|
|
ch, cancel := b.Subscribe("topic")
|
|
defer cancel()
|
|
channels[i] = ch
|
|
}
|
|
|
|
b.Publish("topic", []byte("broadcast"))
|
|
for i, ch := range channels {
|
|
assert.Equal(t, []byte("broadcast"), recvWithin(t, ch, recvTimeout), "subscriber %d", i)
|
|
}
|
|
})
|
|
|
|
t.Run("TopicIsolation", func(t *testing.T) {
|
|
b := newBroker(t)
|
|
chA, cancelA := b.Subscribe("a")
|
|
defer cancelA()
|
|
chB, cancelB := b.Subscribe("b")
|
|
defer cancelB()
|
|
|
|
b.Publish("a", []byte("only-a"))
|
|
assert.Equal(t, []byte("only-a"), recvWithin(t, chA, recvTimeout))
|
|
assertQuiet(t, chB, 100*time.Millisecond) // topic b must stay silent
|
|
})
|
|
|
|
t.Run("CancelStopsDelivery", func(t *testing.T) {
|
|
b := newBroker(t)
|
|
ch, cancel := b.Subscribe("topic")
|
|
|
|
cancel()
|
|
_, ok := <-ch
|
|
assert.False(t, ok, "channel must be closed after cancel")
|
|
|
|
b.Publish("topic", []byte("after-cancel")) // must not panic or block
|
|
})
|
|
|
|
t.Run("CancelIsIdempotent", func(t *testing.T) {
|
|
b := newBroker(t)
|
|
_, cancel := b.Subscribe("topic")
|
|
cancel()
|
|
assert.NotPanics(t, cancel, "cancel must be safe to call more than once")
|
|
})
|
|
|
|
// What each backend reports with no live subscriber differs, so that stays in
|
|
// the backend's own test file.
|
|
t.Run("HasTopicSubscribers", func(t *testing.T) {
|
|
b := newBroker(t)
|
|
_, cancel := b.Subscribe("topic")
|
|
defer cancel()
|
|
assert.True(t, b.HasTopicSubscribers("topic"), "must report subscribers while one is live")
|
|
})
|
|
|
|
t.Run("SlowSubscriberDropsWithoutBlocking", func(t *testing.T) {
|
|
b := newBroker(t)
|
|
_, cancelSlow := b.Subscribe("topic") // never drained, buffer overflows
|
|
defer cancelSlow()
|
|
fast, cancelFast := b.Subscribe("topic")
|
|
defer cancelFast()
|
|
|
|
// Drain fast concurrently so it keeps up while slow's buffer fills.
|
|
got := make(chan struct{}, 1)
|
|
done := make(chan struct{})
|
|
defer close(done)
|
|
go func() {
|
|
for {
|
|
select {
|
|
case _, ok := <-fast:
|
|
if !ok {
|
|
return
|
|
}
|
|
select {
|
|
case got <- struct{}{}:
|
|
default:
|
|
}
|
|
case <-done:
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
|
|
// Far more than the 8-slot buffer: Publish must never block on slow.
|
|
const n = 50
|
|
published := make(chan struct{})
|
|
go func() {
|
|
for i := range n {
|
|
b.Publish("topic", []byte{byte(i)})
|
|
}
|
|
close(published)
|
|
}()
|
|
select {
|
|
case <-published:
|
|
case <-time.After(recvTimeout):
|
|
t.Fatal("Publish blocked on slow subscriber")
|
|
}
|
|
|
|
// The fast subscriber still receives while slow is stuck.
|
|
select {
|
|
case <-got:
|
|
case <-time.After(recvTimeout):
|
|
t.Fatal("fast subscriber received nothing while slow subscriber stalled")
|
|
}
|
|
})
|
|
}
|
|
|
|
// recvWithin returns the next message or fails if none arrives before timeout.
|
|
func recvWithin(t *testing.T, ch <-chan []byte, timeout time.Duration) []byte {
|
|
t.Helper()
|
|
select {
|
|
case msg, ok := <-ch:
|
|
require.True(t, ok, "channel closed before a message arrived")
|
|
return msg
|
|
case <-time.After(timeout):
|
|
t.Fatalf("timed out after %s waiting for a message", timeout)
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// assertQuiet fails if any message arrives on ch within d.
|
|
func assertQuiet(t *testing.T, ch <-chan []byte, d time.Duration) {
|
|
t.Helper()
|
|
select {
|
|
case msg := <-ch:
|
|
t.Fatalf("unexpected message: %s", msg)
|
|
case <-time.After(d):
|
|
}
|
|
}
|
|
|
|
func TestUserTopic(t *testing.T) {
|
|
assert.Equal(t, "user-42", UserTopic(42))
|
|
assert.Equal(t, "user-0", UserTopic(0))
|
|
}
|