Skip to content

Commit

Permalink
add retry mechanism;
Browse files Browse the repository at this point in the history
Signed-off-by: tcar <tcar121293@gmail.com>
  • Loading branch information
tcar121293 committed Jul 30, 2024
1 parent d5c8a62 commit 4a8f0f3
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions chains/btc/uploader/ipfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ import (
"io"
"mime/multipart"
"net/http"
"time"

"github.com/ChainSafe/sygma-relayer/config/relayer"
)

const MAX_RETRIES = 3

type Uploader interface {
Upload(proposals []map[string]interface{}) (string, error)
}
Expand All @@ -27,13 +30,11 @@ type IPFSResponse struct {
}

func (s *IPFSUploader) Upload(dataToUpload []map[string]interface{}) (string, error) {
// Convert proposals to JSON
jsonData, err := json.Marshal(dataToUpload)
if err != nil {
return "", err
}

// Create a multipart form file
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", "metadata.json")
Expand All @@ -46,31 +47,35 @@ func (s *IPFSUploader) Upload(dataToUpload []map[string]interface{}) (string, er
}
writer.Close()

// Create a new request
req, err := http.NewRequest("POST", s.config.URL, body)
if err != nil {
return "", err
}

// Set the headers
req.Header.Add("Authorization", "Bearer "+s.config.AuthToken)
req.Header.Add("Content-Type", writer.FormDataContentType())

// Make the request
client := &http.Client{}
resp, err := client.Do(req)
var resp *http.Response
for attempt := 1; attempt <= MAX_RETRIES; attempt++ {
client := &http.Client{}
resp, err = client.Do(req)
if err == nil && resp.StatusCode == 200 {
break
}

time.Sleep(time.Duration(attempt) * time.Second)
}

if err != nil {
return "", err
}
defer resp.Body.Close()

// Read the response
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

// Parse the response
var ipfsResponse IPFSResponse
if err := json.Unmarshal(respBody, &ipfsResponse); err != nil {
return "", err
Expand Down

0 comments on commit 4a8f0f3

Please sign in to comment.