Add logging, rate limiter, retries
This commit is contained in:
parent
aaca60cafc
commit
3ba71a7787
@ -1,15 +1,25 @@
|
|||||||
package mr
|
package mr
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
"golang.org/x/time/rate"
|
||||||
)
|
)
|
||||||
|
|
||||||
const apiURL = "https://snapshot.debian.org/mr"
|
const apiURL = "https://snapshot.debian.org/mr"
|
||||||
|
|
||||||
|
var Limiter = rate.NewLimiter(rate.Every(time.Second), 10)
|
||||||
|
|
||||||
|
// Retries in case of 5xx errors
|
||||||
|
var Retries = 10
|
||||||
|
|
||||||
// https://salsa.debian.org/snapshot-team/snapshot/blob/master/API
|
// https://salsa.debian.org/snapshot-team/snapshot/blob/master/API
|
||||||
|
|
||||||
// /mr/package/<package>/
|
// /mr/package/<package>/
|
||||||
@ -70,15 +80,32 @@ type Info struct {
|
|||||||
Result []Fileinfo `json:"result"`
|
Result []Fileinfo `json:"result"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func getJson(url string, target interface{}) (err error) {
|
func getJson(query string, target interface{}) (err error) {
|
||||||
resp, err := http.Get(url)
|
flog := log.With().Str("url", query).Logger()
|
||||||
|
|
||||||
|
var resp *http.Response
|
||||||
|
for i := Retries; i > 0; i-- {
|
||||||
|
flog.Trace().Msg("wait")
|
||||||
|
Limiter.Wait(context.Background())
|
||||||
|
|
||||||
|
flog.Trace().Msg("start")
|
||||||
|
resp, err = http.Get(query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
flog.Error().Err(err).Msg("")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
flog.Debug().Msgf("%s", resp.Status)
|
||||||
|
|
||||||
|
if resp.StatusCode < 500 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
flog.Debug().Msgf("retry (%d left)", i)
|
||||||
|
}
|
||||||
|
|
||||||
if resp.StatusCode >= 400 {
|
if resp.StatusCode >= 400 {
|
||||||
return fmt.Errorf("%d", resp.StatusCode)
|
err = fmt.Errorf("%d (%s)", resp.StatusCode, query)
|
||||||
}
|
}
|
||||||
return json.NewDecoder(resp.Body).Decode(target)
|
return json.NewDecoder(resp.Body).Decode(target)
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user