fix(lidarr): protect Lidarr from many asks, refuse bad ids, give up when the request does
- Asking whether Lidarr has an artist keeps the answer for a minute, asks once however many ask at once, and has at most four questions on their way; what cannot be answered is not kept, and a send forgets what was kept. - An id that is not a MusicBrainz id (one that a provider named and that was only cleaned) is no id: it is refused or shown as no_id instead of becoming a 500. - A send that waits for its turn gives up when its request does. - A bad answer after the add also says the artist may have been added; a canceled send ends like the other canceled requests. - The README says which artists can be sent.
This commit is contained in:
parent
8160c33960
commit
22cd0aecd4
5 changed files with 284 additions and 19 deletions
|
|
@ -20,7 +20,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
- **Artist descriptions.** `GET /artists/{id}/description` shows what Wikipedia says about an artist: a short text, with the page it comes from, a link to it and the licence (CC BY-SA 4.0), which you must show next to it. With the `wikipedia` provider and the `musicbrainz` one switched on (the link to Wikidata comes from MusicBrainz), Sonda follows ids and never a name: the artist's MusicBrainz id, then the Wikidata item that MusicBrainz links to it, then the Wikipedia page that Wikidata names in the first of your languages (`[wikipedia] languages`, the code of that Wikipedia, for example `["it", "en"]`) that has one. An artist without a MusicBrainz id has no description. It is kept for 30 days and removed with the provider's data. To read the descriptions of the whole library in one go, an admin starts a background job like a scan: `POST /library/descriptions` (follow it with `GET /library/descriptions`, stop it with `DELETE /library/descriptions`; `?refresh=true` reads every artist again). It only goes through artists that have a MusicBrainz id, never replaces a description by a failure, and ends at once, saying so, when a provider it needs is off. See [External providers](#external-providers).
|
||||
- **Artist photos.** `GET /artists/{id}/image` serves a free picture of an artist from Wikimedia Commons, and `GET /artists/{id}/image/credit` says whose it is and under which licence, which you must show next to it. Only free licences are kept (public domain, CC0, CC BY, CC BY-SA): non-commercial, no-derivatives, fair-use and unknown ones are refused, because Sonda stores a copy (`?size=small` is 300 pixels, `large` 1000) in the data folder. With the `commons` provider and the `musicbrainz` one switched on, Sonda follows ids and never a name: the artist's MusicBrainz id, the Wikidata item MusicBrainz links to it, the picture Wikidata names for it, and Commons for its licence. Many artists will have none. Kept for 30 days (a week when there is none) and removed, files included, with the provider's data. To look for the pictures of the whole library in one go, an admin starts a background job like a scan: `POST /library/artist-images` (follow it with `GET /library/artist-images`, stop it with `DELETE /library/artist-images`; `?refresh=true` searches every artist again). It only goes through artists that have a MusicBrainz id, never replaces a picture by a failure, and ends at once, saying so, when a provider it needs is off. See [External providers](#external-providers).
|
||||
- **Album covers.** `GET /albums/{id}/cover` serves the cover of an album from your own files: the picture embedded in them, or else a `cover`, `folder`, `front`, `album` or `albumart` image in the album's folder. It is built the first time it is asked for (a few at a time), scaled (`?size=small` is 300 pixels, `large` 1000) and kept in the data folder (`storage.data_dir`, you can delete it: covers are built again). A picture you replace in a folder is noticed within a week, or at once after a full rescan. When your files have no picture at all and an admin switched on the `coverartarchive` provider, the cover is asked from the Cover Art Archive by the MusicBrainz release group id that the tags of the album's files carry (`MUSICBRAINZ_RELEASEGROUPID`; run a full rescan to read it for music you already indexed); your own files always come first, and only that id leaves the server. For an album split in `CD1`/`Disc 2` folders, the picture in the folder above is used. Nothing is sent anywhere unless you switched on the `coverartarchive` provider (see [External providers](#external-providers)). It also takes `?access_token=`, so an `<img>` element can use it. To build the covers of the whole library in one go instead of one album at a time, an admin starts a background job like a scan: `POST /library/covers` (follow it with `GET /library/covers`, stop it with `DELETE /library/covers`; `?refresh=true` searches every album again; it never replaces a cover by "no cover" because a disk was not mounted, and keeps the covers that came from the archive if you switched it off).
|
||||
- **Wishlist and "not interested".** `PUT /wishlist/{artist}` puts an artist on your wishlist (`GET /wishlist` lists it, `DELETE` takes it off), and `POST /discover/{artist}/dismiss` hides an artist from your Discover for good (`DELETE` brings it back, `GET /discover/dismissed` lists them). An artist is wished or dismissed, never both, and both lists are yours alone. Discover marks the wished artists it shows (`wishlisted`) and never suggests a dismissed one. The wishlist is a list for you and sends nothing anywhere; Sonda downloads nothing, but an admin can send an artist you wished for to their own Lidarr (see [External providers](#external-providers)). An artist that only Last.fm named is kept while you have it marked (your lists still show it, but other users cannot see that it exists), and goes with the rest of Last.fm's data if an admin removes Last.fm's data. Removing MusicBrainz's data does not touch it.
|
||||
- **Wishlist and "not interested".** `PUT /wishlist/{artist}` puts an artist on your wishlist (`GET /wishlist` lists it, `DELETE` takes it off), and `POST /discover/{artist}/dismiss` hides an artist from your Discover for good (`DELETE` brings it back, `GET /discover/dismissed` lists them). An artist is wished or dismissed, never both, and both lists are yours alone. Discover marks the wished artists it shows (`wishlisted`) and never suggests a dismissed one. The wishlist is a list for you and sends nothing anywhere; Sonda downloads nothing, but an admin can send an artist that Discover showed to their own Lidarr (see [External providers](#external-providers)), which works for an artist that has a MusicBrainz id and that Sonda knows of from a list or from your files. An artist that only Last.fm named is kept while you have it marked (your lists still show it, but other users cannot see that it exists), and goes with the rest of Last.fm's data if an admin removes Last.fm's data. Removing MusicBrainz's data does not touch it.
|
||||
- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so this setting never sends your listening to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on). What Last.fm answers is kept in the shared database like any other lookup, so another local user can see, from `retrieved_at` of `GET /artists/{id}/similar`, that someone looked up an artist, but not who.
|
||||
- **Tags.** `GET /artists/{id}/tags` shows what Last.fm and MusicBrainz say kind of music an artist plays, each with its own weights, and the genres of the artist's own files, read offline. See [External providers](#external-providers).
|
||||
- **Similar artists.** With Last.fm switched on, `GET /artists/{id}/similar` lists artists similar to an artist, and says which of them you already have. See [External providers](#external-providers). Without it, Sonda makes no outbound network requests at all.
|
||||
|
|
|
|||
|
|
@ -41,7 +41,9 @@ func (h *lidarrArtistHandlers) send(c *gin.Context) {
|
|||
writeError(c, http.StatusUnprocessableEntity, "lidarr_unknown_artist", "Lidarr does not know this artist")
|
||||
case errors.Is(err, lidarr.ErrRejected):
|
||||
writeError(c, http.StatusUnprocessableEntity, "lidarr_rejected", err.Error())
|
||||
case errors.Is(err, lidarr.ErrUnreachable), errors.Is(err, context.DeadlineExceeded):
|
||||
case errors.Is(err, context.Canceled):
|
||||
c.AbortWithStatus(statusClientClosed) // the one who clicked left
|
||||
case errors.Is(err, lidarr.ErrUnreachable), errors.Is(err, lidarr.ErrBadResponse), errors.Is(err, context.DeadlineExceeded):
|
||||
// The request may have got there before the answer was lost: say so.
|
||||
_ = c.Error(err)
|
||||
writeError(c, http.StatusBadGateway, "lidarr_unavailable", "Lidarr could not be asked, or did not answer in time: the artist may have been added, check with GET /artists/{id}/lidarr")
|
||||
|
|
|
|||
|
|
@ -230,6 +230,7 @@ func TestWhatStopsAnArtistFromBeingSentIsSaid(t *testing.T) {
|
|||
{lidarr.ErrNotFound, http.StatusUnprocessableEntity, "lidarr_unknown_artist"},
|
||||
{lidarr.ErrKeyRefused, http.StatusBadGateway, "lidarr_key_refused"},
|
||||
{lidarr.ErrUnreachable, http.StatusBadGateway, "lidarr_unavailable"},
|
||||
{lidarr.ErrBadResponse, http.StatusBadGateway, "lidarr_unavailable"},
|
||||
{context.DeadlineExceeded, http.StatusBadGateway, "lidarr_unavailable"},
|
||||
} {
|
||||
fake.err = c.err
|
||||
|
|
@ -244,11 +245,17 @@ func TestWhatStopsAnArtistFromBeingSentIsSaid(t *testing.T) {
|
|||
if r.Code != http.StatusUnprocessableEntity || errCode(r) != "lidarr_rejected" || !strings.Contains(msg, "Root folder does not exist") {
|
||||
t.Errorf("rejected: %d %v", r.Code, r.Body)
|
||||
}
|
||||
fake.err = lidarr.ErrUnreachable
|
||||
r = do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil)
|
||||
msg, _ = r.Body["error"].(map[string]any)["message"].(string)
|
||||
if !strings.Contains(msg, "may have been added") {
|
||||
t.Errorf("unreachable: %q, want it to say the artist may have been added", msg)
|
||||
for _, cause := range []error{lidarr.ErrUnreachable, lidarr.ErrBadResponse, context.DeadlineExceeded} {
|
||||
fake.err = cause
|
||||
r = do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil)
|
||||
msg, _ = r.Body["error"].(map[string]any)["message"].(string)
|
||||
if !strings.Contains(msg, "may have been added") {
|
||||
t.Errorf("%v: %q, want it to say the artist may have been added", cause, msg)
|
||||
}
|
||||
}
|
||||
fake.err = context.Canceled
|
||||
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil); r.Code != 499 {
|
||||
t.Errorf("a request that left: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,9 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"codeberg.org/squidd/sonda/internal/discovery"
|
||||
"codeberg.org/squidd/sonda/internal/providers"
|
||||
|
|
@ -29,6 +32,21 @@ const (
|
|||
AlreadyAdded Outcome = "already_added"
|
||||
)
|
||||
|
||||
const (
|
||||
// PresenceTTL is how long an answer about an artist is kept: a person looking at an artist
|
||||
// page does not make Sonda ask the admin's Lidarr again at every look.
|
||||
PresenceTTL = time.Minute
|
||||
|
||||
// MaxAsking is how many artists Lidarr is asked about at the same time.
|
||||
MaxAsking = 4
|
||||
|
||||
// maxSeen is how many answers are kept before the old ones are dropped.
|
||||
maxSeen = 1000
|
||||
|
||||
// askTimeout bounds one question to Lidarr, however many people wait for the answer.
|
||||
askTimeout = 25 * time.Second
|
||||
)
|
||||
|
||||
// Artists finds an artist by id.
|
||||
type Artists interface {
|
||||
Artist(ctx context.Context, id int64) (discovery.Artist, error)
|
||||
|
|
@ -52,12 +70,46 @@ type Service struct {
|
|||
settings Switches
|
||||
remote Remote
|
||||
|
||||
mu sync.Mutex // one add at a time: two clicks on the same artist must not both reach Lidarr
|
||||
now func() time.Time
|
||||
turn chan struct{} // one add at a time: two clicks on the same artist must not both reach Lidarr
|
||||
asking chan struct{} // at most MaxAsking questions at the same time
|
||||
flight singleflight.Group
|
||||
|
||||
mu sync.Mutex // guards seen
|
||||
seen map[presenceKey]seenEntry
|
||||
}
|
||||
|
||||
type presenceKey struct {
|
||||
artist int64
|
||||
url string // another address is another Lidarr
|
||||
}
|
||||
|
||||
type seenEntry struct {
|
||||
p Presence
|
||||
at time.Time
|
||||
}
|
||||
|
||||
// NewService builds a Service.
|
||||
func NewService(a Artists, s Switches, r Remote) *Service {
|
||||
return &Service{artists: a, settings: s, remote: r}
|
||||
return &Service{
|
||||
artists: a, settings: s, remote: r, now: time.Now,
|
||||
turn: make(chan struct{}, 1), asking: make(chan struct{}, MaxAsking), seen: map[presenceKey]seenEntry{},
|
||||
}
|
||||
}
|
||||
|
||||
// validID says whether an id is a MusicBrainz id. Ids of files are checked when they are read, but
|
||||
// the ones that a provider named are only cleaned, and an id that cannot be one is no id.
|
||||
func validID(id string) bool { return idRe.MatchString(id) }
|
||||
|
||||
// forget drops what was kept about an artist: it is about to change, or just did.
|
||||
func (s *Service) forget(artistID int64) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for k := range s.seen {
|
||||
if k.artist == artistID {
|
||||
delete(s.seen, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Send adds the artist to Lidarr, with the profiles and the folder the admin chose, and tells
|
||||
|
|
@ -70,7 +122,7 @@ func (s *Service) Send(ctx context.Context, artistID int64) (Outcome, error) {
|
|||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if artist.MBID == "" { // Sonda never looks an id up by name
|
||||
if !validID(artist.MBID) { // Sonda never looks an id up by name
|
||||
return "", ErrNoID
|
||||
}
|
||||
set, on, err := s.settings.Active(ctx, providers.Lidarr)
|
||||
|
|
@ -84,8 +136,13 @@ func (s *Service) Send(ctx context.Context, artistID int64) (Outcome, error) {
|
|||
return "", ErrNotSetUp
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
select { // a request that leaves while it waits for its turn does not take it
|
||||
case s.turn <- struct{}{}:
|
||||
defer func() { <-s.turn }()
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
}
|
||||
defer s.forget(artistID) // what Lidarr has is not what was kept
|
||||
err = s.remote.Add(ctx, AddRequest{
|
||||
MBID: artist.MBID, QualityProfileID: set.Lidarr.QualityProfileID, MetadataProfileID: set.Lidarr.MetadataProfileID,
|
||||
RootFolderPath: set.Lidarr.RootFolderPath, Monitor: set.Lidarr.Monitor, SearchMissing: set.Lidarr.SearchMissing,
|
||||
|
|
@ -109,22 +166,57 @@ type Presence struct {
|
|||
|
||||
// Presence asks Lidarr whether it has the artist. Like the descriptions, whatever stops the answer is
|
||||
// a status and not an error; only a request that was canceled, or an artist that does not exist, is.
|
||||
// Anyone signed in can ask, so Lidarr is protected: an answer is kept for PresenceTTL, however many
|
||||
// ask at once it is asked once, and only MaxAsking questions are on their way at the same time.
|
||||
func (s *Service) Presence(ctx context.Context, artistID int64) (Presence, error) {
|
||||
artist, err := s.artists.Artist(ctx, artistID)
|
||||
if err != nil {
|
||||
return Presence{}, err
|
||||
}
|
||||
if artist.MBID == "" {
|
||||
if !validID(artist.MBID) {
|
||||
return Presence{Status: discovery.StatusNoID}, nil
|
||||
}
|
||||
_, on, err := s.settings.Active(ctx, providers.Lidarr)
|
||||
set, on, err := s.settings.Active(ctx, providers.Lidarr)
|
||||
if err != nil {
|
||||
return Presence{}, err
|
||||
}
|
||||
if !on {
|
||||
return Presence{Status: discovery.StatusDisabled}, nil
|
||||
}
|
||||
have, err := s.remote.Artist(ctx, artist.MBID)
|
||||
key := presenceKey{artist: artistID, url: set.URL}
|
||||
s.mu.Lock()
|
||||
kept, ok := s.seen[key]
|
||||
s.mu.Unlock()
|
||||
if ok && s.now().Sub(kept.at) < PresenceTTL {
|
||||
return kept.p, nil
|
||||
}
|
||||
|
||||
done := s.flight.DoChan(key.url+"\x00"+artist.MBID, func() (any, error) {
|
||||
return s.ask(key, artist.MBID)
|
||||
})
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return Presence{}, ctx.Err()
|
||||
case r := <-done:
|
||||
if r.Err != nil {
|
||||
return Presence{}, r.Err
|
||||
}
|
||||
return r.Val.(Presence), nil
|
||||
}
|
||||
}
|
||||
|
||||
// ask puts the question to Lidarr on a context of its own, so that the one who first asked leaving
|
||||
// does not cancel it for the others.
|
||||
func (s *Service) ask(key presenceKey, mbid string) (Presence, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), askTimeout)
|
||||
defer cancel()
|
||||
select {
|
||||
case s.asking <- struct{}{}:
|
||||
defer func() { <-s.asking }()
|
||||
case <-ctx.Done():
|
||||
return Presence{Status: discovery.StatusError}, nil
|
||||
}
|
||||
have, err := s.remote.Artist(ctx, mbid)
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, context.Canceled):
|
||||
|
|
@ -132,10 +224,22 @@ func (s *Service) Presence(ctx context.Context, artistID int64) (Presence, error
|
|||
case errors.Is(err, ErrNotConfigured):
|
||||
return Presence{Status: StatusNotConfigured}, nil
|
||||
default:
|
||||
return Presence{Status: discovery.StatusError}, nil
|
||||
return Presence{Status: discovery.StatusError}, nil // not kept: the next ask tries again
|
||||
}
|
||||
if have == nil {
|
||||
return Presence{Status: discovery.StatusOK}, nil
|
||||
p := Presence{Status: discovery.StatusOK}
|
||||
if have != nil {
|
||||
p.InLidarr, p.Monitored = true, have.Monitored
|
||||
}
|
||||
return Presence{Status: discovery.StatusOK, InLidarr: true, Monitored: have.Monitored}, nil
|
||||
s.mu.Lock()
|
||||
now := s.now()
|
||||
if len(s.seen) >= maxSeen { // what is old goes, so the memory does not follow the size of the library
|
||||
for k, e := range s.seen {
|
||||
if now.Sub(e.at) >= PresenceTTL {
|
||||
delete(s.seen, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.seen[key] = seenEntry{p: p, at: now}
|
||||
s.mu.Unlock()
|
||||
return p, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package lidarr
|
|||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
|
@ -45,6 +46,10 @@ type fakeRemote struct {
|
|||
delay time.Duration
|
||||
live int32
|
||||
maxLive int32
|
||||
|
||||
artistDelay time.Duration
|
||||
artistLive int32
|
||||
artistMax int32
|
||||
}
|
||||
|
||||
func (f *fakeRemote) Add(_ context.Context, r AddRequest) error {
|
||||
|
|
@ -73,6 +78,17 @@ func (f *fakeRemote) Add(_ context.Context, r AddRequest) error {
|
|||
|
||||
func (f *fakeRemote) Artist(context.Context, string) (*Artist, error) {
|
||||
atomic.AddInt32(&f.asked, 1)
|
||||
n := atomic.AddInt32(&f.artistLive, 1)
|
||||
defer atomic.AddInt32(&f.artistLive, -1)
|
||||
for {
|
||||
m := atomic.LoadInt32(&f.artistMax)
|
||||
if n <= m || atomic.CompareAndSwapInt32(&f.artistMax, m, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(f.artistDelay)
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.artist, f.artistEr
|
||||
}
|
||||
|
||||
|
|
@ -85,7 +101,11 @@ func newService() (*Service, *fakeSwitch, *fakeRemote) {
|
|||
artists := fakeArtists{m: map[int64]discovery.Artist{
|
||||
1: {ID: 1, Name: "Radiohead", MBID: mbid},
|
||||
2: {ID: 2, Name: "No Id"},
|
||||
3: {ID: 3, Name: "Bad Id", MBID: "abc"},
|
||||
}}
|
||||
for i := int64(10); i < 30; i++ { // more artists, with ids of their own
|
||||
artists.m[i] = discovery.Artist{ID: i, Name: "Many", MBID: fmt.Sprintf("00000000-0000-4000-8000-%012d", i)}
|
||||
}
|
||||
return NewService(artists, sw, rem), sw, rem
|
||||
}
|
||||
|
||||
|
|
@ -177,11 +197,15 @@ func TestTwoSendsOfTheSameArtistAtOnceAreOneAfterTheOther(t *testing.T) {
|
|||
func TestPresenceSaysWhetherLidarrHasTheArtist(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, sw, rem := newService()
|
||||
now := time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC)
|
||||
s.now = func() time.Time { return now }
|
||||
later := func() { now = now.Add(PresenceTTL + time.Second) } // an answer kept is not the point here
|
||||
rem.artist = &Artist{ID: 7, Name: "Radiohead", Monitored: true}
|
||||
if p, err := s.Presence(ctx, 1); err != nil || p != (Presence{Status: discovery.StatusOK, InLidarr: true, Monitored: true}) {
|
||||
t.Errorf("there: %+v %v", p, err)
|
||||
}
|
||||
rem.artist = nil
|
||||
later()
|
||||
if p, err := s.Presence(ctx, 1); err != nil || p != (Presence{Status: discovery.StatusOK}) {
|
||||
t.Errorf("not there: %+v %v", p, err)
|
||||
}
|
||||
|
|
@ -194,6 +218,7 @@ func TestPresenceSaysWhetherLidarrHasTheArtist(t *testing.T) {
|
|||
t.Errorf("off: %+v, Lidarr was asked: %v", p, atomic.LoadInt32(&rem.asked) != before)
|
||||
}
|
||||
sw.on = true
|
||||
later()
|
||||
for cause, want := range map[error]string{ErrNotConfigured: StatusNotConfigured, ErrKeyRefused: discovery.StatusError, ErrUnreachable: discovery.StatusError, ErrBadResponse: discovery.StatusError} {
|
||||
rem.artistEr = cause
|
||||
if p, err := s.Presence(ctx, 1); err != nil || p.Status != want || p.InLidarr {
|
||||
|
|
@ -208,3 +233,130 @@ func TestPresenceSaysWhetherLidarrHasTheArtist(t *testing.T) {
|
|||
t.Errorf("a canceled request is not a status: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnIdThatIsNotAMusicBrainzIdIsNoIdAtAll(t *testing.T) {
|
||||
s, _, rem := newService()
|
||||
if _, err := s.Send(context.Background(), 3); !errors.Is(err, ErrNoID) {
|
||||
t.Errorf("Send: %v", err)
|
||||
}
|
||||
if p, err := s.Presence(context.Background(), 3); err != nil || p.Status != discovery.StatusNoID {
|
||||
t.Errorf("Presence: %+v %v", p, err)
|
||||
}
|
||||
if len(rem.added) != 0 || atomic.LoadInt32(&rem.asked) != 0 {
|
||||
t.Error("Lidarr was asked about an id that cannot be one")
|
||||
}
|
||||
}
|
||||
|
||||
func TestASendThatIsGivenUpWhileItWaitsForItsTurnDoesNotGoOn(t *testing.T) {
|
||||
s, _, rem := newService()
|
||||
rem.delay = 150 * time.Millisecond
|
||||
first := make(chan struct{})
|
||||
go func() { _, _ = s.Send(context.Background(), 1); close(first) }()
|
||||
time.Sleep(30 * time.Millisecond) // the first has its turn
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
if _, err := s.Send(ctx, 10); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Errorf("err = %v, want the deadline of the request", err)
|
||||
}
|
||||
if time.Since(start) > 100*time.Millisecond {
|
||||
t.Errorf("it waited %v for a turn it could not use", time.Since(start))
|
||||
}
|
||||
<-first
|
||||
if len(rem.added) != 1 {
|
||||
t.Errorf("added %d, want only the first", len(rem.added))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresenceIsKeptForAWhileAndAskedOnceWhateverTheNumberOfAskers(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, sw, rem := newService()
|
||||
now := time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC)
|
||||
s.now = func() time.Time { return now }
|
||||
rem.artist = &Artist{ID: 7, Monitored: true}
|
||||
rem.artistDelay = 40 * time.Millisecond
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 20; i++ {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); _, _ = s.Presence(ctx, 1) }()
|
||||
}
|
||||
wg.Wait()
|
||||
if n := atomic.LoadInt32(&rem.asked); n != 1 {
|
||||
t.Errorf("Lidarr was asked %d times by 20 at once, want 1", n)
|
||||
}
|
||||
rem.artistDelay = 0
|
||||
_, _ = s.Presence(ctx, 1)
|
||||
if n := atomic.LoadInt32(&rem.asked); n != 1 {
|
||||
t.Errorf("a second ask within the time asked Lidarr again (%d)", n)
|
||||
}
|
||||
// After a send the answer is not the one that was kept.
|
||||
if _, err := s.Send(ctx, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = s.Presence(ctx, 1)
|
||||
if n := atomic.LoadInt32(&rem.asked); n != 2 {
|
||||
t.Errorf("after a send Lidarr was asked %d times in all, want 2", n)
|
||||
}
|
||||
now = now.Add(PresenceTTL + time.Second)
|
||||
_, _ = s.Presence(ctx, 1)
|
||||
if n := atomic.LoadInt32(&rem.asked); n != 3 {
|
||||
t.Errorf("after the time Lidarr was asked %d times in all, want 3", n)
|
||||
}
|
||||
// Another address is another Lidarr.
|
||||
sw.set.URL = "http://elsewhere:8686"
|
||||
_, _ = s.Presence(ctx, 1)
|
||||
if n := atomic.LoadInt32(&rem.asked); n != 4 {
|
||||
t.Errorf("with another address Lidarr was asked %d times in all, want 4", n)
|
||||
}
|
||||
// What cannot be answered is not kept: the next ask tries again.
|
||||
rem.artistEr = ErrUnreachable
|
||||
now = now.Add(PresenceTTL + time.Second)
|
||||
_, _ = s.Presence(ctx, 1)
|
||||
_, _ = s.Presence(ctx, 1)
|
||||
if n := atomic.LoadInt32(&rem.asked); n != 6 {
|
||||
t.Errorf("a failure was kept: Lidarr was asked %d times in all, want 6", n)
|
||||
}
|
||||
// And a provider that is off is not asked, kept or not.
|
||||
rem.artistEr = nil
|
||||
sw.on = false
|
||||
before := atomic.LoadInt32(&rem.asked)
|
||||
if p, _ := s.Presence(ctx, 1); p.Status != discovery.StatusDisabled || atomic.LoadInt32(&rem.asked) != before {
|
||||
t.Errorf("off: %+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyAFewAskLidarrAtTheSameTime(t *testing.T) {
|
||||
s, _, rem := newService()
|
||||
rem.artistDelay = 30 * time.Millisecond
|
||||
var wg sync.WaitGroup
|
||||
for id := int64(10); id < 30; id++ {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); _, _ = s.Presence(context.Background(), id) }()
|
||||
}
|
||||
wg.Wait()
|
||||
if m := atomic.LoadInt32(&rem.artistMax); m > MaxAsking || m < 2 {
|
||||
t.Errorf("%d asks at the same time, want at most %d (and more than one)", m, MaxAsking)
|
||||
}
|
||||
if n := atomic.LoadInt32(&rem.asked); n != 20 {
|
||||
t.Errorf("asked %d times, want once for each of the 20 artists", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresenceGivesUpWhenTheRequestDoes(t *testing.T) {
|
||||
s, _, rem := newService()
|
||||
rem.artistDelay = 200 * time.Millisecond
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
if _, err := s.Presence(ctx, 1); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresenceAndSendPassOnAFailureToReadTheSettings(t *testing.T) {
|
||||
s, sw, _ := newService()
|
||||
sw.err = errors.New("database is locked")
|
||||
if _, err := s.Presence(context.Background(), 1); err == nil {
|
||||
t.Error("Presence hid a failure to read the settings")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue