fix(discover): ask permission first, stable order, honest docs
- Check the discover_from_listening setting before reading the listening history, so a refused request does no work and a database failure cannot turn it into a 500. - Cosine adds up in tag order: the sum in map order changed in the last digit between runs, and equal artists could swap places between requests. - A seed that could not be read is no longer listed as a seed. - README and spec: Discover exists now; "disabled" means something had to be asked and Last.fm is off; the stored lookups are shared, so another local user can see from retrieved_at that an artist was looked up, but not who. - Tests: the history is not read for a refused request, a stable cosine, tags fetched only for the pool and four at a time, a cancelled request stops, MusicBrainz is never asked, the setting is per user.
This commit is contained in:
parent
28c249c268
commit
f548423f73
7 changed files with 196 additions and 25 deletions
|
|
@ -4,7 +4,7 @@ Sonda is a privacy-first, self-hosted music server written in Go. It streams the
|
|||
|
||||
It is a single executable, one database (SQLite by default, PostgreSQL if you prefer) and the folders that hold your music. There is no Redis, no message broker and no cloud account.
|
||||
|
||||
> **Status: early.** The local-playback part works end to end: accounts, libraries, scanning, search, and streaming with HTTP Range. Recommendations, a web client and OpenSubsonic compatibility are not built yet (see [What is not there yet](#what-is-not-there-yet)). The API may still change.
|
||||
> **Status: early.** The local-playback part works end to end: accounts, libraries, scanning, search, and streaming with HTTP Range. Suggestions of new artists work too (Discover). Radio queues, a web client and OpenSubsonic compatibility are not built yet (see [What is not there yet](#what-is-not-there-yet)). The API may still change.
|
||||
|
||||
## What works today
|
||||
|
||||
|
|
@ -16,14 +16,14 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
- **API documentation.** The full API is described in OpenAPI and browsable with Swagger UI, served by Sonda itself. The UI is embedded in the binary, so opening it contacts no other server.
|
||||
- **Listening history.** Clients report explicit `play`, `complete` and `skip` events. An event counts as a listen when it is `complete`, or when it was played for at least 20 seconds (`listening.min_listen_seconds`); the rule is applied when the history is read, so changing it re-reads the past. You can read your own history, with a `counted` flag on every event. It stays in your database and is never sent anywhere.
|
||||
- **Your taste.** `GET /me/taste` shows what Sonda has learned from your own listening: the artists you like and the kinds of music (tags) they have in common. A complete listen counts for more than a short one, a skip counts against the artist, and older listens weigh less (they halve every 90 days, `taste.half_life_days`; only the last ten half-lives are read). It is worked out on every request from data already in your database; nothing is sent to any provider.
|
||||
- **Discover.** `GET /discover` suggests artists you may like, in your library or not, each with a score from 0 to 1 and the parts it is made of: how close it is to the artists you like (affinity), how close its tags are to yours (genre), what your listening says about it (preference) and a bonus for what you have not played (discovery). The weights are in `[scoring]` in the config. A part with no data is left out and the rest rescaled, and every answer says which seeds led to each suggestion. It starts from the artists you name with `?seed=`, or, only if you turned on `discover_from_listening`, from the artists you play most. It needs Last.fm to be switched on; without it the answer says `disabled`. See [External providers](#external-providers).
|
||||
- **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, the Discover feature (coming next) may start from the artists you listen to most, and their names would be sent to Last.fm (only if an admin switched it on).
|
||||
- **Discover.** `GET /discover` suggests artists you may like, in your library or not, each with a score from 0 to 1 and the parts it is made of: how close it is to the artists you like (affinity), how close its tags are to yours (genre), what your listening says about it (preference) and a bonus for what you have not played (discovery). The weights are in `[scoring]` in the config. A part with no data is left out and the rest rescaled, and every answer says which seeds led to each suggestion. It starts from the artists you name with `?seed=`, or, only if you turned on `discover_from_listening`, from the artists you play most. It needs Last.fm to be switched on to ask for anything new: when Last.fm is off and a seed's similar artists are not stored yet, the answer says `disabled` (what was stored earlier is still used). See [External providers](#external-providers).
|
||||
- **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.
|
||||
|
||||
## What is not there yet
|
||||
|
||||
Recommendations and radio queues, a web client, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. Radio queues from all this data are next.
|
||||
Radio queues, a web client, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ import (
|
|||
type discoverEnv struct {
|
||||
*similarEnv
|
||||
lf *fakeTags // what Last.fm says about tags, for any artist
|
||||
mb *fakeTags // MusicBrainz, which Discover must never ask
|
||||
}
|
||||
|
||||
// newDiscoverEnv wires the real Discover on the similar-artists environment: Last.fm
|
||||
|
|
@ -28,11 +29,14 @@ type discoverEnv struct {
|
|||
// library) and Gamma (match 0.5, not in it) are similar to anyone.
|
||||
func newDiscoverEnv(t *testing.T) *discoverEnv {
|
||||
t.Helper()
|
||||
e := &discoverEnv{lf: &fakeTags{tags: []discovery.Tag{{Name: "rock", Weight: 100}, {Name: "grunge", Weight: 40}}}}
|
||||
e := &discoverEnv{
|
||||
lf: &fakeTags{tags: []discovery.Tag{{Name: "rock", Weight: 100}, {Name: "grunge", Weight: 40}}},
|
||||
mb: &fakeTags{tags: []discovery.Tag{{Name: "alternative rock", Weight: 43, Genre: true}}},
|
||||
}
|
||||
e.similarEnv = newSimilarEnvWith(t, func(d *Deps, db *bun.DB, prov *providers.Service) {
|
||||
tasteSvc := taste.NewService(storage.NewTasteRepo(db), taste.Options{MinListen: 20 * time.Second, HalfLife: 90 * 24 * time.Hour})
|
||||
settings := usersettings.NewService(storage.NewUserSettingsRepo(db))
|
||||
tags := discovery.NewTagService(storage.NewDiscoveryRepo(db), map[string]discovery.TagSource{providers.LastFM: e.lf}, prov, zap.NewNop())
|
||||
tags := discovery.NewTagService(storage.NewDiscoveryRepo(db), map[string]discovery.TagSource{providers.LastFM: e.lf, providers.MusicBrainz: e.mb}, prov, zap.NewNop())
|
||||
d.Taste, d.Settings = tasteSvc, settings
|
||||
d.Discover = discover.NewService(tasteSvc, d.Discovery.(discover.Similar), tags, storage.NewTasteRepo(db), settings, discover.DefaultWeights())
|
||||
})
|
||||
|
|
@ -170,6 +174,32 @@ func TestDiscoverFromMyListeningNeedsAndUsesTheSetting(t *testing.T) {
|
|||
if e.lf.calls == 0 {
|
||||
t.Error("the tags of the candidates were never read")
|
||||
}
|
||||
if e.mb.calls != 0 {
|
||||
t.Errorf("MusicBrainz was asked %d times: Discover reads tags from Last.fm only", e.mb.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheSettingBelongsToEachUser(t *testing.T) {
|
||||
e := newDiscoverEnv(t)
|
||||
e.enableLastfm(t)
|
||||
e.listen(t, e.admin, e.trackOf(t, "Alpha"), "complete", 1000, "a1")
|
||||
e.allowListening(t) // alice allows it
|
||||
|
||||
body := map[string]any{"username": "bob", "password": "longenough"}
|
||||
if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated {
|
||||
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
||||
}
|
||||
bob, _ := do(t, e.h, "POST", "/api/v1/auth/login", "", body).Body["access_token"].(string)
|
||||
r := do(t, e.h, "GET", "/api/v1/discover", bob, nil)
|
||||
if r.Code != http.StatusBadRequest || errCode(r) != "seed_required" {
|
||||
t.Errorf("bob did not allow it: %d %v, want 400 seed_required", r.Code, r.Body)
|
||||
}
|
||||
if e.source.count() != 0 {
|
||||
t.Error("Last.fm was asked on behalf of bob, who never allowed it")
|
||||
}
|
||||
if r := e.get(t, ""); r.Code != http.StatusOK {
|
||||
t.Errorf("alice did: %d %v", r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverFilterAndLimit(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -688,8 +688,10 @@ paths:
|
|||
gets old can take several seconds, because the provider is asked politely, a few at a time;
|
||||
later ones are served from the database.
|
||||
|
||||
`provider_status` is `disabled` when Last.fm is off or has no key (anything stored earlier
|
||||
is still used, so the list can be empty), `error` when Last.fm failed for some seed (the
|
||||
`provider_status` is `disabled` when something had to be asked from Last.fm (a seed's
|
||||
similar artists are missing or old) and Last.fm is off or has no key; anything stored earlier
|
||||
is still used, so the list can be empty. With every seed's data stored and fresh the status is `ok`
|
||||
whether Last.fm is on or not. It is `error` when Last.fm failed for some seed (the
|
||||
rest is still returned) and `ok` otherwise. Show `attribution` where you show the data.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
|
|
@ -1792,7 +1794,9 @@ components:
|
|||
When true, Discover may start from the artists you listen to most. That sends their
|
||||
names to Last.fm, which is asked for artists similar to each one (only when an admin
|
||||
switched Last.fm on). When false, Discover starts only from artists you name yourself.
|
||||
False until you turn it on.
|
||||
False until you turn it on. What Last.fm answers is stored like any other lookup and is
|
||||
shared: another user can see from `retrieved_at` in `GET /artists/{id}/similar` that
|
||||
somebody looked an artist up, but not who.
|
||||
|
||||
UpdateUserSettings:
|
||||
type: object
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ package discover
|
|||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Weights say how much each part counts. Only their proportions matter.
|
||||
|
|
@ -79,13 +80,15 @@ func Affinity(links []Link) float64 {
|
|||
// Cosine compares two tag vectors. ok is false when either has nothing to compare
|
||||
// (no tags, or all weights zero), which is different from "nothing in common".
|
||||
func Cosine(a, b map[string]float64) (float64, bool) {
|
||||
// Added up in tag order: a sum in map order changes in the last digit from one
|
||||
// run to the next, and two equal artists could swap places between requests.
|
||||
var dot, na, nb float64
|
||||
for tag, wa := range a {
|
||||
na += wa * wa
|
||||
dot += wa * b[tag]
|
||||
for _, tag := range sortedKeys(a) {
|
||||
na += a[tag] * a[tag]
|
||||
dot += a[tag] * b[tag]
|
||||
}
|
||||
for _, wb := range b {
|
||||
nb += wb * wb
|
||||
for _, tag := range sortedKeys(b) {
|
||||
nb += b[tag] * b[tag]
|
||||
}
|
||||
if na <= 0 || nb <= 0 {
|
||||
return 0, false
|
||||
|
|
@ -93,6 +96,15 @@ func Cosine(a, b map[string]float64) (float64, bool) {
|
|||
return clamp01(dot / (math.Sqrt(na) * math.Sqrt(nb))), true
|
||||
}
|
||||
|
||||
func sortedKeys(m map[string]float64) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
// PreferenceScore maps the preference from -1..1 to 0..1. An artist the listener
|
||||
// never played (known is false) is neutral: 0.5.
|
||||
func PreferenceScore(pref float64, known bool) float64 {
|
||||
|
|
|
|||
|
|
@ -150,3 +150,18 @@ func TestWeightsValidation(t *testing.T) {
|
|||
t.Errorf("default weights = %+v, want %+v", d, good)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCosineGivesTheSameNumberEveryTime(t *testing.T) {
|
||||
a, b := map[string]float64{}, map[string]float64{}
|
||||
for i := 0; i < 60; i++ {
|
||||
tag := string(rune('a'+i%26)) + string(rune('a'+i/26))
|
||||
a[tag] = 1 / float64(i+3)
|
||||
b[tag] = 1 / float64(2*i+7)
|
||||
}
|
||||
first, _ := Cosine(a, b)
|
||||
for i := 0; i < 300; i++ {
|
||||
if got, _ := Cosine(a, b); got != first {
|
||||
t.Fatalf("run %d: %v, first was %v: the sums depend on map order, and equal artists can swap places", i, got, first)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -139,14 +139,10 @@ func (s *Service) Discover(ctx context.Context, userID int64, q Query) (Result,
|
|||
return Result{}, err
|
||||
}
|
||||
|
||||
learned, err := s.taste.Learn(ctx, userID)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
res := Result{ProviderStatus: discovery.StatusOK, Seeds: []Seed{}, Items: []Item{}}
|
||||
seeds := named
|
||||
if len(named) == 0 {
|
||||
// Ask permission before doing any work for a request that may be refused.
|
||||
set, err := s.settings.Get(ctx, userID)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
|
|
@ -155,6 +151,13 @@ func (s *Service) Discover(ctx context.Context, userID int64, q Query) (Result,
|
|||
return Result{}, ErrSeedRequired
|
||||
}
|
||||
res.FromListening = true
|
||||
}
|
||||
|
||||
learned, err := s.taste.Learn(ctx, userID)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if res.FromListening {
|
||||
for i, p := range learned.Liked {
|
||||
if i == MaxListeningSeeds {
|
||||
break
|
||||
|
|
@ -165,7 +168,6 @@ func (s *Service) Discover(ctx context.Context, userID int64, q Query) (Result,
|
|||
return Result{}, err
|
||||
}
|
||||
}
|
||||
res.Seeds = append(res.Seeds, seeds...)
|
||||
if len(seeds) == 0 {
|
||||
return res, nil
|
||||
}
|
||||
|
|
@ -175,6 +177,8 @@ func (s *Service) Discover(ctx context.Context, userID int64, q Query) (Result,
|
|||
return Result{}, err
|
||||
}
|
||||
res.ProviderStatus = status
|
||||
seeds, lists = withoutUnread(seeds, lists)
|
||||
res.Seeds = append(res.Seeds, seeds...)
|
||||
|
||||
cands := gather(seeds, lists, q.InLibrary)
|
||||
pool := rankByAffinity(cands, max(limit, minPool))
|
||||
|
|
@ -278,10 +282,10 @@ func (s *Service) nameSeeds(ctx context.Context, seeds []Seed) error {
|
|||
|
||||
// readSimilar reads the similar artists of every seed, Parallelism at a time. A seed
|
||||
// that was removed in the meantime is skipped; any other error stops the request.
|
||||
func (s *Service) readSimilar(ctx context.Context, seeds []Seed) ([]discovery.Result, string, error) {
|
||||
func (s *Service) readSimilar(ctx context.Context, seeds []Seed) ([]*discovery.Result, string, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
results := make([]discovery.Result, len(seeds))
|
||||
results := make([]*discovery.Result, len(seeds)) // nil for a seed that could not be read
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
|
|
@ -311,7 +315,7 @@ func (s *Service) readSimilar(ctx context.Context, seeds []Seed) ([]discovery.Re
|
|||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
results[i] = r
|
||||
results[i] = &r
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
|
@ -323,6 +327,9 @@ func (s *Service) readSimilar(ctx context.Context, seeds []Seed) ([]discovery.Re
|
|||
}
|
||||
status := discovery.StatusOK
|
||||
for _, r := range results {
|
||||
if r == nil {
|
||||
continue
|
||||
}
|
||||
switch r.ProviderStatus {
|
||||
case discovery.StatusDisabled:
|
||||
status = discovery.StatusDisabled
|
||||
|
|
@ -335,6 +342,19 @@ func (s *Service) readSimilar(ctx context.Context, seeds []Seed) ([]discovery.Re
|
|||
return results, status, nil
|
||||
}
|
||||
|
||||
// withoutUnread drops the seeds that could not be read, with their lists, so that
|
||||
// they are not reported as the reason for anything.
|
||||
func withoutUnread(seeds []Seed, lists []*discovery.Result) ([]Seed, []*discovery.Result) {
|
||||
var keptSeeds []Seed
|
||||
var keptLists []*discovery.Result
|
||||
for i, sd := range seeds {
|
||||
if lists[i] != nil {
|
||||
keptSeeds, keptLists = append(keptSeeds, sd), append(keptLists, lists[i])
|
||||
}
|
||||
}
|
||||
return keptSeeds, keptLists
|
||||
}
|
||||
|
||||
type candidate struct {
|
||||
id int64
|
||||
name string
|
||||
|
|
@ -344,7 +364,7 @@ type candidate struct {
|
|||
|
||||
// gather turns the similar lists into candidates. A seed is never suggested, and
|
||||
// the library filter is applied here.
|
||||
func gather(seeds []Seed, lists []discovery.Result, inLibrary *bool) []*candidate {
|
||||
func gather(seeds []Seed, lists []*discovery.Result, inLibrary *bool) []*candidate {
|
||||
isSeed := map[int64]bool{}
|
||||
for _, sd := range seeds {
|
||||
isSeed[sd.ID] = true
|
||||
|
|
|
|||
|
|
@ -18,9 +18,11 @@ type fakeTaste struct {
|
|||
learned taste.Learned
|
||||
err error
|
||||
user int64
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeTaste) Learn(_ context.Context, userID int64) (taste.Learned, error) {
|
||||
f.calls++
|
||||
f.user = userID
|
||||
return f.learned, f.err
|
||||
}
|
||||
|
|
@ -238,6 +240,9 @@ func TestDiscoverWithoutSeedsAndTheSettingOffIsRefusedAndAsksNobody(t *testing.T
|
|||
if len(r.similar.called())+len(r.fetch.called()) != 0 {
|
||||
t.Error("a provider was asked although the listener did not allow it")
|
||||
}
|
||||
if r.taste.calls != 0 {
|
||||
t.Error("the history was read for a request that was refused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverFromListeningUsesTheArtistsILikeWeightedByHowMuch(t *testing.T) {
|
||||
|
|
@ -390,7 +395,7 @@ func TestTagsAreFetchedOnlyForCandidatesWithNone_AndOnlyFromLastfm(t *testing.T)
|
|||
for _, id := range r.fetch.called() {
|
||||
got[id] = true
|
||||
}
|
||||
if got[10] || got[11] || !got[13] {
|
||||
if got[10] || got[11] || !got[12] || !got[13] {
|
||||
t.Errorf("fetched for %v, want only artists without tags", got)
|
||||
}
|
||||
for _, p := range r.fetch.prov {
|
||||
|
|
@ -605,3 +610,88 @@ func TestSettingsAndTasteErrorsPass(t *testing.T) {
|
|||
t.Errorf("settings: err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestASeedThatCannotBeReadIsNotListedAsASeed(t *testing.T) {
|
||||
r := newRig()
|
||||
r.similar.errs[1] = discovery.ErrNotFound
|
||||
res, err := r.svc.Discover(context.Background(), 7, Query{Seeds: []int64{1, 2}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(res.Seeds) != 1 || res.Seeds[0].ID != 2 {
|
||||
t.Errorf("seeds = %+v, want only the one that gave something", res.Seeds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyThePoolOfBestCandidatesIsScoredAndTaggedWhateverTheLimit(t *testing.T) {
|
||||
r := newRig()
|
||||
var items []discovery.Item
|
||||
for i := 0; i < 50; i++ {
|
||||
id := int64(200 + i)
|
||||
items = append(items, item(id, "c", i+1, 1-float64(i)/100, false))
|
||||
r.store.names[id] = "c"
|
||||
}
|
||||
r.similar.lists[1] = discovery.Result{Items: items}
|
||||
res, err := r.svc.Discover(context.Background(), 7, Query{Seeds: []int64{1}, Limit: 3})
|
||||
if err != nil || len(res.Items) != 3 {
|
||||
t.Fatalf("items %d err %v", len(res.Items), err)
|
||||
}
|
||||
fetched := r.fetch.called()
|
||||
if len(fetched) != minPool {
|
||||
t.Errorf("tags fetched for %d candidates, want the pool of %d", len(fetched), minPool)
|
||||
}
|
||||
for _, id := range fetched {
|
||||
if id >= 200+minPool {
|
||||
t.Errorf("tags fetched for candidate %d, which is below the pool", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagsAreFetchedFourAtATimeAndStopWhenTheListenerLeaves(t *testing.T) {
|
||||
r := newRig()
|
||||
var items []discovery.Item
|
||||
for i := 0; i < 20; i++ {
|
||||
items = append(items, item(int64(300+i), "c", i+1, 0.5, false))
|
||||
}
|
||||
r.similar.lists[1] = discovery.Result{Items: items}
|
||||
slow := &slowFetcher{delay: 20 * time.Millisecond}
|
||||
r.svc = NewService(r.taste, r.similar, slow, r.store, r.set, DefaultWeights())
|
||||
if _, err := r.svc.Discover(context.Background(), 7, Query{Seeds: []int64{1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m := atomic.LoadInt32(&slow.maxSeen); m < 2 || m > Parallelism {
|
||||
t.Errorf("at most %d tag requests at once, saw %d", Parallelism, m)
|
||||
}
|
||||
|
||||
slow = &slowFetcher{delay: time.Second}
|
||||
r.svc = NewService(r.taste, r.similar, slow, r.store, r.set, DefaultWeights())
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
if _, err := r.svc.Discover(ctx, 7, Query{Seeds: []int64{1}}); !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 500*time.Millisecond {
|
||||
t.Errorf("err = %v after %v, want a prompt deadline error", err, time.Since(start))
|
||||
}
|
||||
}
|
||||
|
||||
type slowFetcher struct {
|
||||
delay time.Duration
|
||||
inFlight int32
|
||||
maxSeen int32
|
||||
}
|
||||
|
||||
func (f *slowFetcher) ProviderTags(ctx context.Context, id int64, provider string) (discovery.TagSourceResult, error) {
|
||||
n := atomic.AddInt32(&f.inFlight, 1)
|
||||
defer atomic.AddInt32(&f.inFlight, -1)
|
||||
for {
|
||||
m := atomic.LoadInt32(&f.maxSeen)
|
||||
if n <= m || atomic.CompareAndSwapInt32(&f.maxSeen, m, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-time.After(f.delay):
|
||||
case <-ctx.Done():
|
||||
return discovery.TagSourceResult{}, ctx.Err()
|
||||
}
|
||||
return discovery.TagSourceResult{Provider: provider, Status: discovery.StatusOK}, nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue