Логирование: ревью всего кода и рефакторинг в соответствии с конвенциями
This commit is contained in:
+24
-27
@@ -10,6 +10,9 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"git.vakhrushev.me/av/jellybit/internal/logctx"
|
||||
"git.vakhrushev.me/av/jellybit/internal/logging"
|
||||
)
|
||||
|
||||
const defaultTimeout = 10 * time.Second
|
||||
@@ -38,8 +41,9 @@ func newHTTPClient(proxy string, timeout time.Duration) (*http.Client, error) {
|
||||
const maxBody = 4 << 20 // 4 MiB — потолок на тело ответа
|
||||
|
||||
// getJSON выполняет GET и декодирует JSON-ответ в out. headers — опц.
|
||||
// дополнительные заголовки (напр. Authorization).
|
||||
func getJSON(ctx context.Context, hc *http.Client, log *slog.Logger, rawURL string, headers map[string]string, out any) error {
|
||||
// дополнительные заголовки (напр. Authorization). service/operation — поля
|
||||
// ext.* для телеметрии вызова.
|
||||
func getJSON(ctx context.Context, hc *http.Client, log *slog.Logger, service, operation, rawURL string, headers map[string]string, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("metadata: build request: %w", err)
|
||||
@@ -48,11 +52,11 @@ func getJSON(ctx context.Context, hc *http.Client, log *slog.Logger, rawURL stri
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
return doJSON(hc, log, req, out)
|
||||
return doJSON(ctx, hc, log, service, operation, req, out)
|
||||
}
|
||||
|
||||
// postJSON выполняет POST с JSON-телом и декодирует ответ.
|
||||
func postJSON(ctx context.Context, hc *http.Client, log *slog.Logger, rawURL string, body, out any) error {
|
||||
func postJSON(ctx context.Context, hc *http.Client, log *slog.Logger, service, operation, rawURL string, body, out any) error {
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("metadata: marshal body: %w", err)
|
||||
@@ -63,46 +67,39 @@ func postJSON(ctx context.Context, hc *http.Client, log *slog.Logger, rawURL str
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
return doJSON(hc, log, req, out)
|
||||
return doJSON(ctx, hc, log, service, operation, req, out)
|
||||
}
|
||||
|
||||
// doJSON выполняет запрос и декодирует ответ, логируя исход. В лог идут только
|
||||
// host и path (без query) — у TMDB api_key передаётся query-параметром, его
|
||||
// нельзя светить в логах.
|
||||
func doJSON(hc *http.Client, log *slog.Logger, req *http.Request, out any) error {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
start := time.Now()
|
||||
// doJSON выполняет запрос и декодирует ответ, логируя исход телеметрией ext.*
|
||||
// (логическая operation вместо URL: у TMDB api_key передаётся query-параметром,
|
||||
// его нельзя светить в логах). Логгер берётся из ctx (scoped-логгер загрузки),
|
||||
// при отсутствии — переданный fallback.
|
||||
func doJSON(ctx context.Context, hc *http.Client, log *slog.Logger, service, operation string, req *http.Request, out any) error {
|
||||
log = logctx.FromOr(ctx, log)
|
||||
call := logging.ExtCall{Service: service, Operation: operation, Start: time.Now()}
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
log.Warn("metadata: request failed",
|
||||
"method", req.Method, "host", req.URL.Host, "path", req.URL.Path,
|
||||
"duration", time.Since(start), "err", err)
|
||||
call.Failure(log, err)
|
||||
return fmt.Errorf("metadata: request: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
call.Status = resp.StatusCode
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxBody))
|
||||
if err != nil {
|
||||
log.Warn("metadata: read body failed",
|
||||
"host", req.URL.Host, "path", req.URL.Path, "err", err)
|
||||
call.Failure(log, err)
|
||||
return fmt.Errorf("metadata: read body: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
log.Warn("metadata: non-ok status",
|
||||
"method", req.Method, "host", req.URL.Host, "path", req.URL.Path,
|
||||
"status", resp.StatusCode, "duration", time.Since(start))
|
||||
return fmt.Errorf("metadata: status %d: %s", resp.StatusCode, snippet(raw))
|
||||
err := fmt.Errorf("metadata: status %d: %s", resp.StatusCode, snippet(raw))
|
||||
call.Failure(log, err)
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(raw, out); err != nil {
|
||||
log.Warn("metadata: decode failed",
|
||||
"host", req.URL.Host, "path", req.URL.Path, "err", err)
|
||||
call.Failure(log, err)
|
||||
return fmt.Errorf("metadata: decode: %w (body: %s)", err, snippet(raw))
|
||||
}
|
||||
log.Debug("metadata: request ok",
|
||||
"method", req.Method, "host", req.URL.Host, "path", req.URL.Path,
|
||||
"duration", time.Since(start))
|
||||
call.Success(log)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.vakhrushev.me/av/jellybit/internal/logging"
|
||||
)
|
||||
|
||||
const tmdbDefaultBaseURL = "https://api.themoviedb.org/3"
|
||||
@@ -81,12 +83,11 @@ func (t *TMDB) Search(ctx context.Context, q Query) ([]Candidate, error) {
|
||||
return nil, fmt.Errorf("metadata: tmdb: unknown type %q", q.Type)
|
||||
}
|
||||
|
||||
t.log.Debug("tmdb: search", "type", q.Type, "title", q.Title, "year", q.Year)
|
||||
var resp tmdbSearchResp
|
||||
if err := getJSON(ctx, t.hc, t.log, t.baseURL+path+"?"+params.Encode(), nil, &resp); err != nil {
|
||||
op := strings.TrimPrefix(path, "/") // search/movie | search/tv
|
||||
if err := getJSON(ctx, t.hc, t.log, logging.ServiceTMDB, op, t.baseURL+path+"?"+params.Encode(), nil, &resp); err != nil {
|
||||
return nil, fmt.Errorf("tmdb search: %w", err)
|
||||
}
|
||||
t.log.Debug("tmdb: search done", "title", q.Title, "results", len(resp.Results))
|
||||
|
||||
out := make([]Candidate, 0, len(resp.Results))
|
||||
for _, r := range resp.Results {
|
||||
@@ -116,7 +117,7 @@ type tmdbTVResp struct {
|
||||
func (t *TMDB) SeasonEpisodeCounts(ctx context.Context, id string) (map[int]int, error) {
|
||||
params := url.Values{"api_key": {t.apiKey}}
|
||||
var resp tmdbTVResp
|
||||
if err := getJSON(ctx, t.hc, t.log, t.baseURL+"/tv/"+url.PathEscape(id)+"?"+params.Encode(), nil, &resp); err != nil {
|
||||
if err := getJSON(ctx, t.hc, t.log, logging.ServiceTMDB, "tv", t.baseURL+"/tv/"+url.PathEscape(id)+"?"+params.Encode(), nil, &resp); err != nil {
|
||||
return nil, fmt.Errorf("tmdb tv %s: %w", id, err)
|
||||
}
|
||||
out := make(map[int]int, len(resp.Seasons))
|
||||
|
||||
+20
-17
@@ -12,6 +12,9 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.vakhrushev.me/av/jellybit/internal/logctx"
|
||||
"git.vakhrushev.me/av/jellybit/internal/logging"
|
||||
)
|
||||
|
||||
const tvdbDefaultBaseURL = "https://api4.thetvdb.com/v4"
|
||||
@@ -70,8 +73,8 @@ func (t *TVDB) login(ctx context.Context) (string, error) {
|
||||
Token string `json:"token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
t.log.Debug("tvdb: login (fetching bearer token)")
|
||||
if err := postJSON(ctx, t.hc, t.log, t.baseURL+"/login",
|
||||
// Тело запроса содержит apikey — postJSON его не логирует (только ext.*).
|
||||
if err := postJSON(ctx, t.hc, t.log, logging.ServiceTVDB, "login", t.baseURL+"/login",
|
||||
map[string]string{"apikey": t.apiKey}, &resp); err != nil {
|
||||
return "", fmt.Errorf("tvdb login: %w", err)
|
||||
}
|
||||
@@ -83,24 +86,26 @@ func (t *TVDB) login(ctx context.Context) (string, error) {
|
||||
}
|
||||
|
||||
// get делает авторизованный GET; при 401 один раз перелогинивается.
|
||||
func (t *TVDB) get(ctx context.Context, path string, out any) error {
|
||||
// operation — логическая операция для поля ext.operation.
|
||||
func (t *TVDB) get(ctx context.Context, operation, path string, out any) error {
|
||||
token, err := t.login(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
status, raw, err := t.rawGet(ctx, path, token)
|
||||
status, raw, err := t.rawGet(ctx, operation, path, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status == http.StatusUnauthorized {
|
||||
t.log.Warn("tvdb: token expired, re-login", "path", path)
|
||||
// Рутинное обновление протухшего токена — DEBUG (не «может стать проблемой»).
|
||||
logctx.FromOr(ctx, t.log).Debug("tvdb token expired, re-login")
|
||||
t.mu.Lock()
|
||||
t.token = "" // сбрасываем протухший токен
|
||||
t.mu.Unlock()
|
||||
if token, err = t.login(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if status, raw, err = t.rawGet(ctx, path, token); err != nil {
|
||||
if status, raw, err = t.rawGet(ctx, operation, path, token); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -113,28 +118,28 @@ func (t *TVDB) get(ctx context.Context, path string, out any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *TVDB) rawGet(ctx context.Context, path, token string) (int, []byte, error) {
|
||||
func (t *TVDB) rawGet(ctx context.Context, operation, path, token string) (int, []byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, t.baseURL+path, nil)
|
||||
if err != nil {
|
||||
return 0, nil, fmt.Errorf("tvdb: build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
start := time.Now()
|
||||
log := logctx.FromOr(ctx, t.log)
|
||||
call := logging.ExtCall{Service: logging.ServiceTVDB, Operation: operation, Start: time.Now()}
|
||||
resp, err := t.hc.Do(req)
|
||||
if err != nil {
|
||||
t.log.Warn("tvdb: request failed",
|
||||
"host", req.URL.Host, "path", req.URL.Path, "duration", time.Since(start), "err", err)
|
||||
call.Failure(log, err)
|
||||
return 0, nil, fmt.Errorf("tvdb: request: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
call.Status = resp.StatusCode
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxBody))
|
||||
if err != nil {
|
||||
t.log.Warn("tvdb: read body failed", "host", req.URL.Host, "path", req.URL.Path, "err", err)
|
||||
call.Failure(log, err)
|
||||
return 0, nil, fmt.Errorf("tvdb: read body: %w", err)
|
||||
}
|
||||
t.log.Debug("tvdb: request done",
|
||||
"host", req.URL.Host, "path", req.URL.Path, "status", resp.StatusCode, "duration", time.Since(start))
|
||||
call.Success(log)
|
||||
return resp.StatusCode, raw, nil
|
||||
}
|
||||
|
||||
@@ -156,12 +161,10 @@ func (t *TVDB) Search(ctx context.Context, q Query) ([]Candidate, error) {
|
||||
if q.Year > 0 {
|
||||
params.Set("year", strconv.Itoa(q.Year))
|
||||
}
|
||||
t.log.Debug("tvdb: search", "type", q.Type, "title", q.Title, "year", q.Year)
|
||||
var resp tvdbSearchResp
|
||||
if err := t.get(ctx, "/search?"+params.Encode(), &resp); err != nil {
|
||||
if err := t.get(ctx, "search", "/search?"+params.Encode(), &resp); err != nil {
|
||||
return nil, fmt.Errorf("tvdb search: %w", err)
|
||||
}
|
||||
t.log.Debug("tvdb: search done", "title", q.Title, "results", len(resp.Data))
|
||||
out := make([]Candidate, 0, len(resp.Data))
|
||||
for _, r := range resp.Data {
|
||||
if r.TVDBID == "" {
|
||||
@@ -189,7 +192,7 @@ type tvdbExtendedResp struct {
|
||||
// SeasonEpisodeCounts считает число серий по сезонам из расширенных данных.
|
||||
func (t *TVDB) SeasonEpisodeCounts(ctx context.Context, id string) (map[int]int, error) {
|
||||
var resp tvdbExtendedResp
|
||||
if err := t.get(ctx, "/series/"+url.PathEscape(id)+"/extended?meta=episodes&short=true", &resp); err != nil {
|
||||
if err := t.get(ctx, "series/extended", "/series/"+url.PathEscape(id)+"/extended?meta=episodes&short=true", &resp); err != nil {
|
||||
return nil, fmt.Errorf("tvdb series %s: %w", id, err)
|
||||
}
|
||||
out := map[int]int{}
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.vakhrushev.me/av/jellybit/internal/logging"
|
||||
)
|
||||
|
||||
const tvmazeDefaultBaseURL = "https://api.tvmaze.com"
|
||||
@@ -68,11 +70,9 @@ func (t *TVMaze) Search(ctx context.Context, q Query) ([]Candidate, error) {
|
||||
Show tvmazeShow `json:"show"`
|
||||
}
|
||||
rawURL := t.baseURL + "/search/shows?q=" + url.QueryEscape(q.Title)
|
||||
t.log.Debug("tvmaze: search", "title", q.Title)
|
||||
if err := getJSON(ctx, t.hc, t.log, rawURL, nil, &resp); err != nil {
|
||||
if err := getJSON(ctx, t.hc, t.log, logging.ServiceTVMaze, "search/shows", rawURL, nil, &resp); err != nil {
|
||||
return nil, fmt.Errorf("tvmaze search: %w", err)
|
||||
}
|
||||
t.log.Debug("tvmaze: search done", "title", q.Title, "results", len(resp))
|
||||
|
||||
out := make([]Candidate, 0, len(resp))
|
||||
for _, r := range resp {
|
||||
@@ -104,7 +104,7 @@ type tvmazeEpisode struct {
|
||||
func (t *TVMaze) SeasonEpisodeCounts(ctx context.Context, id string) (map[int]int, error) {
|
||||
var eps []tvmazeEpisode
|
||||
rawURL := t.baseURL + "/shows/" + url.PathEscape(id) + "/episodes"
|
||||
if err := getJSON(ctx, t.hc, t.log, rawURL, nil, &eps); err != nil {
|
||||
if err := getJSON(ctx, t.hc, t.log, logging.ServiceTVMaze, "shows/episodes", rawURL, nil, &eps); err != nil {
|
||||
return nil, fmt.Errorf("tvmaze episodes %s: %w", id, err)
|
||||
}
|
||||
out := map[int]int{}
|
||||
|
||||
Reference in New Issue
Block a user