Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 56 additions & 7 deletions v1/providers/sfcomputev2/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,29 @@ import (
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"

"github.com/brevdev/cloud/internal/errors"
)

const (
defaultAPIURL = "https://api.sfcompute.com"
brevAPIPath = "/integrations/brev/v1"

sshRateLimitRetries = 2
)

type apiClient struct {
apiKey string
baseURL string
httpClient *http.Client

// SF Compute's rate-limit responses ask callers to retry after one second.
rateLimitRetryDelay time.Duration
}

type createInstanceRequest struct {
Expand Down Expand Up @@ -103,11 +111,39 @@ func (e *apiError) Error() string {
return fmt.Sprintf("SFCompute API request failed: status %d: %s", e.statusCode, e.body)
}

func hasStatusCode(err error, statusCode int) bool {
var responseErr *apiError
return errors.As(err, &responseErr) && responseErr.statusCode == statusCode
}

func isServerError(err error) bool {
var responseErr *apiError
return errors.As(err, &responseErr) &&
responseErr.statusCode >= http.StatusInternalServerError &&
responseErr.statusCode < 600
}

// isUninformativeError reports errors that say nothing about the instance a request was for.
func isUninformativeError(err error) bool {
if hasStatusCode(err, http.StatusTooManyRequests) ||
hasStatusCode(err, http.StatusUnauthorized) ||
hasStatusCode(err, http.StatusForbidden) ||
isServerError(err) {
return true
}
var netErr net.Error
return errors.As(err, &netErr) ||
errors.Is(err, io.ErrUnexpectedEOF) ||
errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded)
}

func newAPIClient(apiKey string) *apiClient {
return &apiClient{
apiKey: apiKey,
baseURL: defaultAPIURL,
httpClient: &http.Client{Timeout: 60 * time.Second},
apiKey: apiKey,
baseURL: defaultAPIURL,
httpClient: &http.Client{Timeout: 60 * time.Second},
rateLimitRetryDelay: time.Second,
}
}

Expand Down Expand Up @@ -158,11 +194,24 @@ func (c *apiClient) terminateInstance(ctx context.Context, id string) error {
}

func (c *apiClient) getSSHInfo(ctx context.Context, id string) (*instanceSSHInfo, error) {
var response instanceSSHInfo
if err := c.do(ctx, http.MethodGet, "/instances/"+url.PathEscape(id)+"/ssh", nil, nil, &response); err != nil {
return nil, err
for attempt := 0; ; attempt++ {
var response instanceSSHInfo
err := c.do(ctx, http.MethodGet, "/instances/"+url.PathEscape(id)+"/ssh", nil, nil, &response)
if err == nil {
return &response, nil
}
if attempt == sshRateLimitRetries || !hasStatusCode(err, http.StatusTooManyRequests) {
return nil, err
}

timer := time.NewTimer(c.rateLimitRetryDelay)
select {
case <-ctx.Done():
timer.Stop()
return nil, ctx.Err()
case <-timer.C:
}
}
return &response, nil
}

func (c *apiClient) getPool(ctx context.Context, id string) (*poolResponse, error) {
Expand Down
92 changes: 92 additions & 0 deletions v1/providers/sfcomputev2/api_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@ package v2
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"sync/atomic"
"testing"
"time"

"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -115,6 +121,92 @@ func TestAPIClientReturnsResponseErrors(t *testing.T) {
require.Contains(t, responseError.body, "not found")
}

func TestIsUninformativeError(t *testing.T) {
t.Parallel()

badJSON := json.Unmarshal([]byte("not json"), &struct{}{})
require.Error(t, badJSON)

tests := []struct {
name string
err error
want bool
}{
{name: "rate limited", err: &apiError{statusCode: http.StatusTooManyRequests}, want: true},
{name: "rejected credentials", err: &apiError{statusCode: http.StatusUnauthorized}, want: true},
{name: "forbidden", err: fmt.Errorf("get ssh info: %w", &apiError{statusCode: http.StatusForbidden}), want: true},
{name: "request failed", err: &url.Error{Op: "Get", URL: defaultAPIURL, Err: errors.New("connection reset by peer")}, want: true},
{name: "response cut off", err: io.ErrUnexpectedEOF, want: true},
{name: "canceled", err: context.Canceled, want: true},
{name: "deadline passed", err: fmt.Errorf("wait: %w", context.DeadlineExceeded), want: true},
{name: "not found", err: &apiError{statusCode: http.StatusNotFound}, want: false},
{name: "server error", err: &apiError{statusCode: http.StatusInternalServerError}, want: true},
{name: "service unavailable", err: fmt.Errorf("get ssh info: %w", &apiError{statusCode: http.StatusServiceUnavailable}), want: true},
{name: "conflict", err: &apiError{statusCode: http.StatusConflict}, want: false},
{name: "bad JSON", err: badJSON, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
require.Equal(t, tt.want, isUninformativeError(tt.err))
})
}
}

func TestAPIClientRetriesOnlyRateLimitedSSHLookups(t *testing.T) {
t.Parallel()

tests := []struct {
name string
status int
wantCalls int32
}{
{name: "rate limited", status: http.StatusTooManyRequests, wantCalls: sshRateLimitRetries + 1},
{name: "server error", status: http.StatusInternalServerError, wantCalls: 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
calls.Add(1)
http.Error(writer, "error", tt.status)
}))
t.Cleanup(server.Close)

client := newAPIClient("api-key")
client.baseURL = server.URL
client.rateLimitRetryDelay = 0

_, err := client.getSSHInfo(context.Background(), "inst_test")
var responseError *apiError
require.ErrorAs(t, err, &responseError)
require.Equal(t, tt.status, responseError.statusCode)
require.Equal(t, tt.wantCalls, calls.Load())
})
}
}

func TestAPIClientStopsRateLimitRetryWhenContextEnds(t *testing.T) {
t.Parallel()

server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
http.Error(writer, rateLimitedBody, http.StatusTooManyRequests)
}))
t.Cleanup(server.Close)

client := newAPIClient("api-key")
client.baseURL = server.URL
client.rateLimitRetryDelay = time.Hour

ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
t.Cleanup(cancel)

_, err := client.getSSHInfo(ctx, "inst_test")
require.ErrorIs(t, err, context.DeadlineExceeded)
}

func writeJSON(t *testing.T, writer http.ResponseWriter, value any) {
t.Helper()
writer.Header().Set("Content-Type", "application/json")
Expand Down
5 changes: 5 additions & 0 deletions v1/providers/sfcomputev2/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package v2

import (
"context"
"time"

v1 "github.com/brevdev/cloud/v1"
)
Expand Down Expand Up @@ -51,6 +52,9 @@ type SFCClientV2 struct {
location string
client *apiClient
logger v1.Logger

// dev-plane retries a failed list within 0.5 s, so ListInstances waits this long before failing.
failedListDelay time.Duration
}

var _ v1.CloudClient = &SFCClientV2{}
Expand All @@ -72,6 +76,7 @@ func (c *SFCCredentialV2) MakeClientWithOptions(_ context.Context, location stri
client: newAPIClient(c.APIKey),
logger: &v1.NoopLogger{},
}
sfcClient.failedListDelay = sfcClient.GetInstancePollTime()

for _, opt := range opts {
opt(sfcClient)
Expand Down
27 changes: 22 additions & 5 deletions v1/providers/sfcomputev2/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,15 @@ func (c *SFCClientV2) ListInstances(ctx context.Context, args v1.ListInstancesAr

sshInfo, err := c.getSSHInfo(ctx, &inst)
if err != nil {
// Callers treat a missing instance as terminated, so an uninformative error fails the whole list.
if isUninformativeError(err) {
c.logger.Warn(ctx, "sfcv2: ListInstances failing list due to SSH error",
v1.LogField("instanceID", inst.ID),
v1.LogField("error", err.Error()),
)
waitOrDone(ctx, c.failedListDelay)
return nil, errors.WrapAndTrace(fmt.Errorf("get SSH details for instance %s: %w", inst.ID, err))
}
c.logger.Error(ctx, err,
v1.LogField("msg", "sfcv2: ListInstances skipping instance due to SSH error"),
v1.LogField("instanceID", inst.ID),
Expand All @@ -170,11 +179,7 @@ func (c *SFCClientV2) ListInstances(ctx context.Context, args v1.ListInstancesAr

brevInst, err := c.sfcInstanceToBrevInstance(&inst, sshInfo)
if err != nil {
c.logger.Error(ctx, err,
v1.LogField("msg", "sfcv2: ListInstances skipping instance due to conversion error"),
v1.LogField("instanceID", inst.ID),
)
continue
return nil, errors.WrapAndTrace(fmt.Errorf("convert instance %s: %w", inst.ID, err))
}
instances = append(instances, *brevInst)
}
Expand Down Expand Up @@ -234,6 +239,18 @@ func (c *SFCClientV2) getSSHInfo(ctx context.Context, inst *instanceResponse) (*
return resp, nil
}

func waitOrDone(ctx context.Context, d time.Duration) {
if d <= 0 {
return
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-ctx.Done():
case <-timer.C:
}
}

func isSSHDetailsPending(err error, createdAt int64, now time.Time) bool {
var responseErr *apiError
if !errors.As(err, &responseErr) || responseErr.statusCode != http.StatusNotFound {
Expand Down
Loading
Loading