Skip to content

Commit

Permalink
Allow graceful exit from waiting state
Browse files Browse the repository at this point in the history
  • Loading branch information
hjr265 committed Jan 29, 2023
1 parent 32cbc82 commit c29fa09
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 27 deletions.
6 changes: 5 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,21 @@ func main() {
wg.Add(1)
go func() {
defer wg.Done()
log.Println(color.BlueString("[i]"), "Waiting for prints")
delay := 0 * time.Second
L:
for {
log.Println(color.BlueString("[i]"), "Waiting for prints")
pr, err := getNextPrint(ctx, cfg)
if errors.As(err, &tophError{}) {
log.Println(color.RedString("[E]"), err)
delay = cfg.Printd.DelayError
goto retry
}
catch(err)
if pr.ID == "" {
delay = 5 * time.Second
goto retry
}

log.Printf(color.BlueString("[i]"), "Printing %s", pr.ID)
err = runPrintJob(ctx, cfg, pr)
Expand Down
49 changes: 23 additions & 26 deletions print.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,35 +23,32 @@ type Print struct {
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)
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{}, tophError{"Could not reach Toph", err}
}
if resp.StatusCode == http.StatusNotFound {
resp.Body.Close()
time.Sleep(5 * time.Second)
continue
}

b.Reset()
_, err = io.Copy(&b, resp.Body)
if err != nil {
return Print{}, tophError{"Could not retrieve print", err}
}
req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/printd/contests/%s/next_print", cfg.Toph.BaseURL, cfg.Toph.ContestID), nil)
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{}, tophError{"Could not reach Toph", err}
}
if resp.StatusCode == http.StatusNotFound {
resp.Body.Close()
return Print{}, nil
}

err = json.NewDecoder(&b).Decode(&pr)
if err != nil {
return Print{}, tophError{"Could not parse response", err}
}
return pr, nil
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
}

func runPrintJob(ctx context.Context, cfg Config, pr Print) error {
Expand Down

0 comments on commit c29fa09

Please sign in to comment.