164 lines
4.7 KiB
Go
164 lines
4.7 KiB
Go
package musicbrainz
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"time"
|
|
|
|
"github.com/rs/zerolog"
|
|
"golang.org/x/time/rate"
|
|
|
|
"github.com/metadata-agregator/internal/metrics"
|
|
)
|
|
|
|
const (
|
|
baseURL = "https://musicbrainz.org/ws/2"
|
|
userAgent = "MetadataAggregator/0.1.0 (https://github.com/metadata-agregator)"
|
|
)
|
|
|
|
type client struct {
|
|
http *http.Client
|
|
limiter *rate.Limiter
|
|
}
|
|
|
|
func newClient() *client {
|
|
return &client{
|
|
http: &http.Client{
|
|
Timeout: 30 * time.Second,
|
|
},
|
|
limiter: rate.NewLimiter(rate.Every(time.Second), 1),
|
|
}
|
|
}
|
|
|
|
func (c *client) get(ctx context.Context, endpoint string, params url.Values) ([]byte, error) {
|
|
log := zerolog.Ctx(ctx)
|
|
|
|
log.Trace().Str("endpoint", endpoint).Msg("waiting for rate limiter")
|
|
if err := c.limiter.Wait(ctx); err != nil {
|
|
log.Debug().Err(err).Msg("rate limiter interrupted")
|
|
return nil, fmt.Errorf("rate limiter: %w", err)
|
|
}
|
|
|
|
if params == nil {
|
|
params = url.Values{}
|
|
}
|
|
params.Set("fmt", "json")
|
|
|
|
reqURL := fmt.Sprintf("%s/%s?%s", baseURL, endpoint, params.Encode())
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create request: %w", err)
|
|
}
|
|
|
|
req.Header.Set("User-Agent", userAgent)
|
|
req.Header.Set("Accept", "application/json")
|
|
|
|
start := time.Now()
|
|
log.Trace().Str("url", reqURL).Msg("sending HTTP request")
|
|
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
log.Debug().Err(err).Str("endpoint", endpoint).Dur("duration", time.Since(start)).Msg("HTTP request failed")
|
|
metrics.ProviderRequests.WithLabelValues("musicbrainz", endpoint, "error").Inc()
|
|
return nil, fmt.Errorf("do request: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
duration := time.Since(start)
|
|
metrics.ProviderLatency.WithLabelValues("musicbrainz", endpoint).Observe(duration.Seconds())
|
|
|
|
if resp.StatusCode == http.StatusNotFound {
|
|
log.Debug().Str("endpoint", endpoint).Int("status", resp.StatusCode).Dur("duration", duration).Msg("HTTP 404")
|
|
metrics.ProviderRequests.WithLabelValues("musicbrainz", endpoint, "not_found").Inc()
|
|
return nil, ErrNotFound
|
|
}
|
|
|
|
if resp.StatusCode == http.StatusServiceUnavailable {
|
|
log.Warn().Str("endpoint", endpoint).Dur("duration", duration).Msg("HTTP 503 rate limited by provider")
|
|
metrics.ProviderRequests.WithLabelValues("musicbrainz", endpoint, "rate_limited").Inc()
|
|
return nil, ErrRateLimited
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
log.Warn().Str("endpoint", endpoint).Int("status", resp.StatusCode).Str("body", string(body)).Dur("duration", duration).Msg("unexpected HTTP status")
|
|
metrics.ProviderRequests.WithLabelValues("musicbrainz", endpoint, fmt.Sprintf("%d", resp.StatusCode)).Inc()
|
|
return nil, fmt.Errorf("unexpected status %d: %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
log.Trace().Str("endpoint", endpoint).Int("status", resp.StatusCode).Dur("duration", duration).Msg("HTTP request succeeded")
|
|
metrics.ProviderRequests.WithLabelValues("musicbrainz", endpoint, "ok").Inc()
|
|
|
|
return io.ReadAll(resp.Body)
|
|
}
|
|
|
|
func (c *client) lookup(ctx context.Context, entity, id string, inc []string) ([]byte, error) {
|
|
zerolog.Ctx(ctx).Debug().Str("entity", entity).Str("id", id).Strs("includes", inc).Msg("provider lookup")
|
|
|
|
params := url.Values{}
|
|
if len(inc) > 0 {
|
|
incStr := ""
|
|
for i, v := range inc {
|
|
if i > 0 {
|
|
incStr += "+"
|
|
}
|
|
incStr += v
|
|
}
|
|
params.Set("inc", incStr)
|
|
}
|
|
|
|
return c.get(ctx, fmt.Sprintf("%s/%s", entity, id), params)
|
|
}
|
|
|
|
func (c *client) browse(ctx context.Context, entity, linkedEntity, linkedID string, limit, offset int, inc []string) ([]byte, error) {
|
|
zerolog.Ctx(ctx).Debug().
|
|
Str("entity", entity).
|
|
Str("linked_entity", linkedEntity).
|
|
Str("linked_id", linkedID).
|
|
Int("limit", limit).
|
|
Int("offset", offset).
|
|
Msg("provider browse")
|
|
|
|
params := url.Values{}
|
|
params.Set(linkedEntity, linkedID)
|
|
params.Set("limit", fmt.Sprintf("%d", limit))
|
|
params.Set("offset", fmt.Sprintf("%d", offset))
|
|
|
|
if len(inc) > 0 {
|
|
incStr := ""
|
|
for i, v := range inc {
|
|
if i > 0 {
|
|
incStr += "+"
|
|
}
|
|
incStr += v
|
|
}
|
|
params.Set("inc", incStr)
|
|
}
|
|
|
|
return c.get(ctx, entity, params)
|
|
}
|
|
|
|
func (c *client) search(ctx context.Context, entity, query string, limit, offset int) ([]byte, error) {
|
|
zerolog.Ctx(ctx).Debug().Str("entity", entity).Str("query", query).Int("limit", limit).Int("offset", offset).Msg("provider search")
|
|
|
|
params := url.Values{}
|
|
params.Set("query", query)
|
|
params.Set("limit", fmt.Sprintf("%d", limit))
|
|
params.Set("offset", fmt.Sprintf("%d", offset))
|
|
|
|
return c.get(ctx, entity, params)
|
|
}
|
|
|
|
func decode[T any](data []byte) (*T, error) {
|
|
var result T
|
|
if err := json.Unmarshal(data, &result); err != nil {
|
|
return nil, fmt.Errorf("decode: %w", err)
|
|
}
|
|
return &result, nil
|
|
}
|