Skip to content

Commit 8ac9115

Browse files
authored
Merge pull request #46 from jungaretti/porkbun-api-throttling
Throttle Porkbun API requests
2 parents 9c587cb + c75a453 commit 8ac9115

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

pkg/providers/porkbun/api/api.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ const (
1414
)
1515

1616
type Api struct {
17-
Auth Auth
17+
Auth Auth
18+
Throttler Throttler
1819
}
1920

2021
func (p Api) Ping() error {
@@ -24,6 +25,7 @@ func (p Api) Ping() error {
2425
}
2526

2627
response := pingRes{}
28+
p.Throttler.WaitForPermit()
2729
err := makeRequest(PING, p.Auth, &response)
2830
if err != nil {
2931
return err
@@ -39,6 +41,7 @@ func (p Api) RetrieveRecords(domain string) ([]porkbun.Record, error) {
3941
}
4042

4143
response := listRes{}
44+
p.Throttler.WaitForPermit()
4245
err := makeRequest(RETRIEVE+"/"+domain, p.Auth, &response)
4346
if err != nil {
4447
return nil, err
@@ -70,6 +73,7 @@ func (p Api) CreateRecord(domain string, toCreate porkbun.Record) (string, error
7073
request.Name = trimDomain(toCreate.Name, domain)
7174

7275
response := createRes{}
76+
p.Throttler.WaitForPermit()
7377
err := makeRequest(CREATE+"/"+domain, request, &response)
7478
if err != nil {
7579
return "", err
@@ -80,6 +84,7 @@ func (p Api) CreateRecord(domain string, toCreate porkbun.Record) (string, error
8084

8185
func (p Api) DeleteRecord(domain string, id string) error {
8286
response := baseRes{}
87+
p.Throttler.WaitForPermit()
8388
err := makeRequest(DELETE+"/"+domain+"/"+id, p.Auth, &response)
8489
if err != nil {
8590
return err

pkg/providers/porkbun/api/throttle.go

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package api
2+
3+
import (
4+
"time"
5+
)
6+
7+
type Throttler struct {
8+
ticker *time.Ticker
9+
}
10+
11+
func NewThrottler(ratePerSecond int) *Throttler {
12+
interval := time.Second / time.Duration(ratePerSecond)
13+
ticker := time.NewTicker(interval)
14+
15+
return &Throttler{
16+
ticker: ticker,
17+
}
18+
}
19+
20+
// Waits for the next available permit.
21+
// Use this method to respect rate limits.
22+
func (t *Throttler) WaitForPermit() {
23+
// Send a tick to 1 caller per interval
24+
<-t.ticker.C
25+
}
26+
27+
func (t *Throttler) Stop() {
28+
t.ticker.Stop()
29+
}

pkg/providers/porkbun/porkbun.go

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ func NewPorkbunProvider(apiKey, secretApiKey string) dns.Provider {
1818
ApiKey: apiKey,
1919
SecretApiKey: secretApiKey,
2020
},
21+
Throttler: *api.NewThrottler(1),
2122
},
2223
}
2324
}

0 commit comments

Comments
 (0)