Skip to content

Commit

Permalink
Force iRail rate limit
Browse files Browse the repository at this point in the history
  • Loading branch information
meyskens committed Jul 13, 2024
1 parent 5d72b84 commit d1c281f
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
2 changes: 1 addition & 1 deletion apiserver/pkg/ris/irail/liveboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func GetLiveboard(station, arriveOrDeparture, lang string, from time.Time) (Live
}
req.Header.Set("User-Agent", USER_AGENT)

client := &http.Client{}
client := newClient()
resp, err := client.Do(req)
if err != nil {
return Liveboard{}, err
Expand Down
37 changes: 37 additions & 0 deletions apiserver/pkg/ris/irail/ratelimit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package irail

import (
"context"
"net/http"
"time"

"golang.org/x/time/rate"
)

var rateLimit = rate.NewLimiter(rate.Every(time.Second), 3)

type RLHTTPClient struct {
client *http.Client
Ratelimiter *rate.Limiter
}

func (c *RLHTTPClient) Do(req *http.Request) (*http.Response, error) {
ctx := context.Background()
err := c.Ratelimiter.Wait(ctx) // This is a blocking call. Honors the rate limit
if err != nil {
return nil, err
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}

func newClient() *RLHTTPClient {
c := &RLHTTPClient{
client: http.DefaultClient,
Ratelimiter: rateLimit,
}
return c
}
2 changes: 1 addition & 1 deletion apiserver/pkg/ris/irail/vehicle.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func GetVehicleCached(id, lang string, date time.Time) (Vehicle, error) {
}
req.Header.Set("User-Agent", USER_AGENT)

client := &http.Client{}
client := newClient()
resp, err := client.Do(req)
if err != nil {
return Vehicle{}, err
Expand Down

0 comments on commit d1c281f

Please sign in to comment.