mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-10 19:37:08 +02:00
* refactor(persistence): adopt generic deluan/rest repository API Pin deluan/rest to the refactor branch. REST-facing repository methods take a context and return typed values. Drop DataStore.Resource and ResourceRepository; the native API names typed repositories directly through a per-request adapter that later commits remove. * refactor(persistence): base repository helpers take a context * refactor(persistence): LibraryRepository takes a context per call * refactor(persistence): PropertyRepository takes a context per call * refactor(persistence): UserPropsRepository takes a context per call * refactor(persistence): TranscodingRepository takes a context per call * refactor(persistence): ShareRepository takes a context per call * refactor(persistence): PlayerRepository takes a context per call * refactor(persistence): RadioRepository takes a context per call * refactor(persistence): PlayQueueRepository takes a context per call * refactor(persistence): Tag and Genre repositories take a context per call * refactor(persistence): PluginRepository takes a context per call * refactor(persistence): Scrobble repositories take a context per call * refactor(persistence): FolderRepository takes a context per call * refactor(persistence): Artwork repositories take a context per call * refactor(persistence): UserRepository takes a context per call * refactor(persistence): ArtistRepository takes a context per call ReadAll no longer rewrites the shared sort mappings for the role filter; it works on a per-call copy. * test(persistence): assert artist role sort sanitization in ReadAll * refactor(persistence): AlbumRepository takes a context per call * test(persistence): pass the test context to album repository helpers * refactor(persistence): MediaFileRepository takes a context per call * refactor(persistence): Playlist repositories take a context per call * refactor(persistence): build all repositories once per store * refactor(core): REST repository wrappers are built once * refactor(persistence): repositories are stateless Remove the context field from the base repository and the per-request REST adapter. Enable the containedctx linter so no repository can hold a request context again. * chore(lint): skip containedctx in test files * refactor: share simplifications from the stateless repositories sweep Add deleteOwnedAll on sqlRepository and use it in player/share Delete to remove the duplicated bulk-delete loop; have Share.Repository() return model.ShareRepository so subsonic sharing.go drops its repeated type assertions. * chore(core): assert REST wrappers implement Persistable * chore: reformat imports * perf(persistence): build repositories on first use Each transaction store used to construct all 21 repositories up front, paying for filter and sort mapping setup the block never touched. Fields are now sync.OnceValue thunks, so a store only builds what it uses. * fix(persistence): clean plugin references per deleted user A bulk user delete that fails on a later id had already removed the earlier rows but skipped their plugin cleanup. Cleanup now runs right after each successful delete. * fix(core): unload disabled plugins even when a user delete fails A bulk delete can fail on a later id after earlier users were removed and their plugins auto-disabled. The wrapper returned before unloading, leaving those plugins running until the next successful delete or a restart. * chore(deps): pin deluan/rest to v1.0.1 Replaces the pseudo-version of the refactor branch with the tagged release. REST error messages now name the bare type (Artist, not model.Artist). * test: use the spec context instead of context.Background() Replace the context.Background()/context.TODO() calls this branch added to tests with the spec's ctx, GinkgoT().Context(), or t/b.Context(), so repository calls are bound to the running spec's lifetime. * test: declare the spec context once per Describe Set ctx from GinkgoT().Context() first in each top-level BeforeEach and reuse it, building user contexts on top of it instead of repeating inline calls.
292 lines
8.1 KiB
Go
292 lines
8.1 KiB
Go
// Package events based on https://thoughtbot.com/blog/writing-a-server-sent-events-server-in-go
|
|
package events
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/navidrome/navidrome/consts"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/model/id"
|
|
"github.com/navidrome/navidrome/model/request"
|
|
"github.com/navidrome/navidrome/utils/pl"
|
|
"github.com/navidrome/navidrome/utils/singleton"
|
|
)
|
|
|
|
type Broker interface {
|
|
http.Handler
|
|
SendMessage(ctx context.Context, event Event)
|
|
SendBroadcastMessage(ctx context.Context, event Event)
|
|
}
|
|
|
|
const (
|
|
keepAliveFrequency = 15 * time.Second
|
|
// The timeout must be higher than the keepAliveFrequency, or the lack of activity will cause the channel to close.
|
|
writeTimeOut = keepAliveFrequency + 5*time.Second
|
|
bufferSize = 1
|
|
)
|
|
|
|
type (
|
|
message struct {
|
|
id uint64
|
|
event string
|
|
data string
|
|
senderCtx context.Context //nolint:containedctx // queued message carries the sender ctx
|
|
}
|
|
messageChan chan message
|
|
clientsChan chan client
|
|
client struct {
|
|
id string
|
|
address string
|
|
username string
|
|
userAgent string
|
|
clientUniqueId string
|
|
displayString string
|
|
msgC chan message
|
|
}
|
|
)
|
|
|
|
func (c client) String() string {
|
|
return c.displayString
|
|
}
|
|
|
|
type broker struct {
|
|
// Events are pushed to this channel by the main events-gathering routine
|
|
publish messageChan
|
|
|
|
// New client connections
|
|
subscribing clientsChan
|
|
|
|
// Closed client connections
|
|
unsubscribing clientsChan
|
|
}
|
|
|
|
func GetBroker() Broker {
|
|
return singleton.GetInstance(func() *broker {
|
|
// Instantiate a broker
|
|
broker := &broker{
|
|
publish: make(messageChan, 2),
|
|
subscribing: make(clientsChan, 1),
|
|
unsubscribing: make(clientsChan, 1),
|
|
}
|
|
|
|
// Set it running - listening and broadcasting events
|
|
go broker.listen()
|
|
return broker
|
|
})
|
|
}
|
|
|
|
func (b *broker) SendBroadcastMessage(ctx context.Context, evt Event) {
|
|
ctx = broadcastToAll(ctx)
|
|
b.SendMessage(ctx, evt)
|
|
}
|
|
|
|
func (b *broker) SendMessage(ctx context.Context, evt Event) {
|
|
msg := b.prepareMessage(ctx, evt)
|
|
log.Trace("Broker received new event", "type", msg.event, "data", msg.data)
|
|
b.publish <- msg
|
|
}
|
|
|
|
func (b *broker) prepareMessage(ctx context.Context, event Event) message {
|
|
msg := message{}
|
|
msg.data = event.Data(event)
|
|
msg.event = event.Name(event)
|
|
msg.senderCtx = ctx
|
|
return msg
|
|
}
|
|
|
|
// writeEvent writes a message to the given io.Writer, formatted as a Server-Sent Event.
|
|
// If the writer is a http.Flusher, it flushes the data immediately instead of buffering it.
|
|
func writeEvent(ctx context.Context, w io.Writer, event message, timeout time.Duration) error {
|
|
if err := setWriteTimeout(w, timeout); err != nil {
|
|
log.Debug(ctx, "Error setting write timeout", err)
|
|
}
|
|
|
|
_, err := fmt.Fprintf(w, "id: %d\nevent: %s\ndata: %s\n\n", event.id, event.event, event.data) //nolint:gosec
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// If the writer is a http.Flusher, flush the data immediately.
|
|
if flusher, ok := w.(http.Flusher); ok && flusher != nil {
|
|
flusher.Flush()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func setWriteTimeout(rw io.Writer, timeout time.Duration) error {
|
|
for {
|
|
switch t := rw.(type) {
|
|
case interface{ SetWriteDeadline(time.Time) error }:
|
|
return t.SetWriteDeadline(time.Now().Add(timeout))
|
|
case interface{ Unwrap() http.ResponseWriter }:
|
|
rw = t.Unwrap()
|
|
default:
|
|
return fmt.Errorf("%T - %w", rw, http.ErrNotSupported)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (b *broker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
user, _ := request.UserFrom(ctx)
|
|
|
|
// Make sure that the writer supports flushing.
|
|
_, ok := w.(http.Flusher)
|
|
if !ok {
|
|
log.Error(r, "Streaming unsupported! Events cannot be sent to this client", "address", r.RemoteAddr,
|
|
"userAgent", r.UserAgent(), "user", user.UserName)
|
|
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("Cache-Control", "no-cache, no-transform")
|
|
w.Header().Set("Connection", "keep-alive")
|
|
// Tells Nginx to not buffer this response. See https://stackoverflow.com/a/33414096
|
|
w.Header().Set("X-Accel-Buffering", "no")
|
|
|
|
// Each connection registers its own message channel with the Broker's connections registry
|
|
c := b.subscribe(r)
|
|
defer b.unsubscribe(c)
|
|
log.Debug(ctx, "Started new EventStream connection", "client", c.String())
|
|
|
|
for event := range pl.ReadOrDone(ctx, c.msgC) {
|
|
log.Trace(ctx, "Sending event to client", "event", event, "client", c.String())
|
|
err := writeEvent(ctx, w, event, writeTimeOut)
|
|
if err != nil {
|
|
log.Debug(ctx, "Error sending event to client. Closing connection", "event", event, "client", c.String(), err)
|
|
return
|
|
}
|
|
}
|
|
log.Trace(ctx, "Client EventStream connection closed", "client", c.String())
|
|
}
|
|
|
|
func (b *broker) subscribe(r *http.Request) client {
|
|
ctx := r.Context()
|
|
user, _ := request.UserFrom(ctx)
|
|
clientUniqueId, _ := request.ClientUniqueIdFrom(ctx)
|
|
c := client{
|
|
id: id.NewRandom(),
|
|
username: user.UserName,
|
|
address: r.RemoteAddr,
|
|
userAgent: r.UserAgent(),
|
|
clientUniqueId: clientUniqueId,
|
|
}
|
|
if log.IsGreaterOrEqualTo(log.LevelTrace) {
|
|
c.displayString = fmt.Sprintf("%s (%s - %s - %s - %s)", c.id, c.username, c.address, c.clientUniqueId, c.userAgent)
|
|
} else {
|
|
c.displayString = fmt.Sprintf("%s (%s - %s - %s)", c.id, c.username, c.address, c.clientUniqueId)
|
|
}
|
|
|
|
c.msgC = make(chan message, bufferSize)
|
|
|
|
// Signal the broker that we have a new client
|
|
b.subscribing <- c
|
|
return c
|
|
}
|
|
|
|
func (b *broker) unsubscribe(c client) {
|
|
b.unsubscribing <- c
|
|
}
|
|
|
|
func (b *broker) shouldSend(msg message, c client) bool {
|
|
if broadcastToAll, ok := msg.senderCtx.Value(broadcastToAllKey).(bool); ok && broadcastToAll {
|
|
return true
|
|
}
|
|
clientUniqueId, originatedFromClient := request.ClientUniqueIdFrom(msg.senderCtx)
|
|
if !originatedFromClient {
|
|
return true
|
|
}
|
|
if c.clientUniqueId == clientUniqueId {
|
|
return false
|
|
}
|
|
if username, ok := request.UsernameFrom(msg.senderCtx); ok {
|
|
return username == c.username
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (b *broker) listen() {
|
|
keepAlive := time.NewTicker(keepAliveFrequency)
|
|
defer keepAlive.Stop()
|
|
|
|
clients := map[client]struct{}{}
|
|
var eventId uint64
|
|
|
|
getNextEventId := func() uint64 {
|
|
eventId++
|
|
return eventId
|
|
}
|
|
|
|
for {
|
|
select {
|
|
case c := <-b.subscribing:
|
|
// A new client has connected.
|
|
// Register their message channel
|
|
clients[c] = struct{}{}
|
|
log.Debug("Client added to EventStream broker", "numActiveClients", len(clients), "newClient", c.String())
|
|
|
|
// Send a serverStart event to new client
|
|
msg := b.prepareMessage(context.Background(),
|
|
&ServerStart{StartTime: consts.ServerStart, Version: consts.Version})
|
|
sendOrDrop(c, msg)
|
|
|
|
case c := <-b.unsubscribing:
|
|
// A client has detached, and we want to
|
|
// stop sending them messages.
|
|
close(c.msgC)
|
|
delete(clients, c)
|
|
log.Debug("Removed client from EventStream broker", "numActiveClients", len(clients), "client", c.String())
|
|
|
|
case msg := <-b.publish:
|
|
msg.id = getNextEventId()
|
|
log.Trace("Got new published event", "event", msg)
|
|
// We got a new event from the outside!
|
|
// Send event to all connected clients
|
|
for c := range clients {
|
|
if b.shouldSend(msg, c) {
|
|
log.Trace("Putting event on client's queue", "client", c.String(), "event", msg)
|
|
sendOrDrop(c, msg)
|
|
}
|
|
}
|
|
|
|
case ts := <-keepAlive.C:
|
|
// Send a keep alive message every 15 seconds to all connected clients
|
|
if len(clients) == 0 {
|
|
continue
|
|
}
|
|
msg := b.prepareMessage(context.Background(), &KeepAlive{TS: ts.Unix()})
|
|
msg.id = getNextEventId()
|
|
for c := range clients {
|
|
log.Trace("Putting a keepalive event on client's queue", "client", c.String(), "event", msg)
|
|
sendOrDrop(c, msg)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func sendOrDrop(client client, msg message) {
|
|
select {
|
|
case client.msgC <- msg:
|
|
default:
|
|
if log.IsGreaterOrEqualTo(log.LevelTrace) {
|
|
log.Trace("Event dropped because client's channel is full", "event", msg, "client", client.String())
|
|
}
|
|
}
|
|
}
|
|
|
|
func NoopBroker() Broker {
|
|
return noopBroker{}
|
|
}
|
|
|
|
type noopBroker struct {
|
|
http.Handler
|
|
}
|
|
|
|
func (b noopBroker) SendBroadcastMessage(context.Context, Event) {}
|
|
|
|
func (noopBroker) SendMessage(context.Context, Event) {}
|