Логирование: ревью всего кода и рефакторинг в соответствии с конвенциями

This commit is contained in:
av
2026-06-28 20:13:40 +03:00
parent c739a20749
commit 9cfccc7b4a
24 changed files with 473 additions and 203 deletions
+20 -17
View File
@@ -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{}