From 107bf7368d405f68eb1256869850b882c80d6649 Mon Sep 17 00:00:00 2001 From: David Schlachter Date: Mon, 10 Nov 2025 09:07:02 -0500 Subject: Retry when task creation fails --- main.go | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) (limited to 'main.go') diff --git a/main.go b/main.go index 8d104b7..00a319f 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "bufio" "bytes" + "context" "fmt" "io" "log" @@ -14,6 +15,7 @@ import ( "strings" "time" + "github.com/cenkalti/backoff/v5" "github.com/robfig/cron/v3" ) @@ -31,7 +33,10 @@ type Task struct { } func (t Task) Run() { - createTask(t.Name) + _, err := backoff.Retry(context.Background(), func() (bool, error) { return true, createTask(t.Name) }, backoff.WithBackOff(backoff.NewExponentialBackOff())) + if err != nil { + log.Printf("Failed to create task: %s", err) + } } var lastSeenInput = map[InputLine]TaskAddingJob{} @@ -164,7 +169,7 @@ func inputChanged(old, new map[InputLine]TaskAddingJob) bool { return false } -func createTask(task string) { +func createTask(task string) error { jsonBody := []byte(fmt.Sprintf(`{"content": %s}`, strconv.Quote(task))) req, err := http.NewRequest( http.MethodPost, @@ -172,29 +177,26 @@ func createTask(task string) { bytes.NewBuffer(jsonBody), ) if err != nil { - log.Printf("Failed to create request: %s", err) - return + return fmt.Errorf("creating request: %w", err) } req.Header.Add("Authorization", "Bearer "+todoistToken) req.Header.Set("Content-Type", "application/json") resp, err := httpClient.Do(req) if err != nil { - log.Printf("Failed to Do request: %s", err) - return + return fmt.Errorf("doing request: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - log.Printf("Got status code %d, expected 200 when creating task", resp.StatusCode) bodyBytes, err := io.ReadAll(resp.Body) if err != nil { - log.Printf("Failed to read body: %s", err) - return + return fmt.Errorf("reading body when preparing error message (HTTP status was %d): %w", resp.StatusCode, err) } - log.Printf("Got body: %s", string(bodyBytes)) - } else { - log.Printf("Created task '%s'", task) + return fmt.Errorf("expected 200, got status code %d: body was %s", resp.StatusCode, strconv.Quote(string(bodyBytes))) } + + log.Printf("Created task '%s'", task) + return nil } func addJobs(c *cron.Cron, tasks map[InputLine]TaskAddingJob) { -- cgit v1.2.3