Skip to content

Commit

Permalink
Improve main loop resilience
Browse files Browse the repository at this point in the history
  • Loading branch information
hjr265 committed Jan 28, 2023
1 parent 613f2ef commit bb381fd
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 8 deletions.
16 changes: 16 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package main

import "fmt"

type tophError struct {
msg string
err error
}

func (e tophError) Error() string {
return fmt.Sprintf("%s: %s", e.msg, e.err)
}

func (e tophError) Unwrap() error {
return e.err
}
8 changes: 8 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package main

import (
"context"
"errors"
"flag"
"fmt"
"log"
"time"
)
Expand All @@ -29,6 +31,12 @@ func main() {
for {
log.Println("Waiting for prints")
pr, err := getNextPrint(ctx, cfg)
fmt.Println(errors.Is(err, &tophError{}))
if errors.As(err, &tophError{}) {
log.Println(err)
time.Sleep(5 * time.Second)
continue
}
catch(err)

log.Printf("Printing %s", pr.ID)
Expand Down
27 changes: 19 additions & 8 deletions print.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package main

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
Expand All @@ -18,28 +20,37 @@ type Print struct {
ModifiedAt time.Time
}

func getNextPrint(ctx context.Context, cfg Config) (Print, error) {
func getNextPrint(ctx context.Context, cfg Config) (pr Print, err error) {
b := bytes.Buffer{}

for {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/printd/contests/%s/next_print", cfg.Toph.BaseURL, cfg.Toph.ContestID), nil)
req.Header.Add("Authorization", "Printd "+cfg.Toph.Token)
if err != nil {
return Print{}, err
}
req.Header.Add("Authorization", "Printd "+cfg.Toph.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return Print{}, err
return Print{}, tophError{"Could not reach Toph", err}
}
if resp.StatusCode == http.StatusNotFound {
resp.Body.Close()
time.Sleep(5 * time.Second)
continue
} else {
defer resp.Body.Close()
}

pr := Print{}
err = json.NewDecoder(resp.Body).Decode(&pr)
return pr, err
b.Reset()
_, err = io.Copy(&b, resp.Body)
if err != nil {
return Print{}, tophError{"Could not retrieve print", err}
}
resp.Body.Close()

err = json.NewDecoder(&b).Decode(&pr)
if err != nil {
return Print{}, tophError{"Could not parse response", err}
}
return pr, nil
}
}

Expand Down

0 comments on commit bb381fd

Please sign in to comment.