Skip to content

Commit

Permalink
hacky fix for sporadic Gateway Timeouts on play/challenge start
Browse files Browse the repository at this point in the history
  • Loading branch information
iximiuz committed Nov 20, 2024
1 parent e94dcd0 commit 7acca84
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
12 changes: 11 additions & 1 deletion internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@ import (
"strings"
)

var ErrAuthenticationRequired = errors.New("authentication required")
var (
ErrAuthenticationRequired = errors.New("authentication required")
ErrGatewayTimeout = errors.New("gateway timeout")
)

func isAuthenticationRequiredResponse(resp *http.Response) bool {
return resp.StatusCode == http.StatusUnauthorized
}

func isGatewayTimeoutResponse(resp *http.Response) bool {
return resp.StatusCode == http.StatusGatewayTimeout
}

type Client struct {
baseURL string
apiBaseURL string
Expand Down Expand Up @@ -356,6 +363,9 @@ func (c *Client) doRequest(req *http.Request) (*http.Response, error) {
if isAuthenticationRequiredResponse(resp) {
return nil, ErrAuthenticationRequired
}
if isGatewayTimeoutResponse(resp) {
return nil, ErrGatewayTimeout
}

return nil, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, body)
}
Expand Down
31 changes: 29 additions & 2 deletions internal/api/plays.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package api

import (
"context"
"errors"
"fmt"
"time"
)

type Play struct {
Expand Down Expand Up @@ -169,6 +172,30 @@ func (c *Client) StartTunnel(ctx context.Context, id string, req StartTunnelRequ
return nil, err
}

var resp StartTunnelResponse
return &resp, c.PostInto(ctx, "/plays/"+id+"/tunnels", nil, nil, body, &resp)
// A hacky workaround for the fact that the CLI currently
// doesn't check for playground readiness before establishing
// a tunnel.
backoff := 200 * time.Millisecond
for attempt := 0; attempt < 5; attempt++ {
var resp StartTunnelResponse
err := c.PostInto(ctx, "/plays/"+id+"/tunnels", nil, nil, body, &resp)
if err == nil {
return &resp, nil
}
if !errors.Is(err, ErrGatewayTimeout) {
return nil, err
}
if attempt == 2 {
return nil, fmt.Errorf("max retries exceeded: %w", err)
}

select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(backoff):
}
backoff *= 2
}

return nil, ctx.Err()
}

0 comments on commit 7acca84

Please sign in to comment.