Move ProvisionCodespace to API client

- Make CreateCodespace private along with its errors
This commit is contained in:
Jose Garcia 2021-09-22 11:49:41 -04:00
parent 8c5330d9e9
commit d2d21996bc
4 changed files with 86 additions and 91 deletions

View file

@ -75,74 +75,3 @@ func ConnectToLiveshare(ctx context.Context, log logger, apiClient *api.API, use
return lsclient.JoinWorkspace(ctx)
}
type apiClient interface {
CreateCodespace(ctx context.Context, user *api.User, repo *api.Repository, machine, branch, location string) (*api.Codespace, error)
GetCodespaceToken(ctx context.Context, userLogin, codespaceName string) (string, error)
GetCodespace(ctx context.Context, token, userLogin, codespaceName string) (*api.Codespace, error)
}
// ProvisionParams are the required parameters for provisioning a Codespace.
type ProvisionParams struct {
User *api.User
Repository *api.Repository
Branch, Machine, Location string
}
// Provision creates a codespace with the given parameters and handles polling in the case
// of initial creation failures.
func Provision(ctx context.Context, log logger, client apiClient, params *ProvisionParams) (*api.Codespace, error) {
codespace, err := client.CreateCodespace(
ctx, params.User, params.Repository, params.Machine, params.Branch, params.Location,
)
if err != nil {
// This error is returned by the API when the initial creation fails with a retryable error.
// A retryable error means that GitHub will retry to re-create Codespace and clients should poll
// the API and attempt to fetch the Codespace for the next two minutes.
if err == api.ErrProvisioningInProgress {
pollTimeout := 2 * time.Minute
pollInterval := 1 * time.Second
log.Print(".")
codespace, err = pollForCodespace(ctx, client, log, pollTimeout, pollInterval, params.User.Login, codespace.Name)
log.Print("\n")
if err != nil {
return nil, fmt.Errorf("error creating codespace with async provisioning: %s: %w", codespace.Name, err)
}
}
return nil, err
}
return codespace, nil
}
// pollForCodespace polls the Codespaces GET endpoint on a given interval for a specified duration.
// If it succeeds at fetching the codespace, we consider the codespace provisioned.
func pollForCodespace(ctx context.Context, client apiClient, log logger, duration, interval time.Duration, user, name string) (*api.Codespace, error) {
ctx, cancel := context.WithTimeout(ctx, duration)
defer cancel()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
log.Print(".")
token, err := client.GetCodespaceToken(ctx, user, name)
if err != nil {
if err == api.ErrNotProvisioned {
// Do nothing. We expect this to fail until the codespace is provisioned
continue
}
return nil, fmt.Errorf("failed to get codespace token: %w", err)
}
return client.GetCodespace(ctx, token, user, name)
}
}
}

View file

@ -1,92 +0,0 @@
package codespaces
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/github/ghcs/cmd/ghcs/output"
"github.com/github/ghcs/internal/api"
)
type mockAPIClient struct {
createCodespace func(context.Context, *api.User, *api.Repository, string, string, string) (*api.Codespace, error)
getCodespaceToken func(context.Context, string, string) (string, error)
getCodespace func(context.Context, string, string, string) (*api.Codespace, error)
}
func (m *mockAPIClient) CreateCodespace(ctx context.Context, user *api.User, repo *api.Repository, machine, branch, location string) (*api.Codespace, error) {
if m.createCodespace == nil {
return nil, errors.New("mock api client CreateCodespace not implemented")
}
return m.createCodespace(ctx, user, repo, machine, branch, location)
}
func (m *mockAPIClient) GetCodespaceToken(ctx context.Context, userLogin, codespaceName string) (string, error) {
if m.getCodespaceToken == nil {
return "", errors.New("mock api client GetCodespaceToken not implemented")
}
return m.getCodespaceToken(ctx, userLogin, codespaceName)
}
func (m *mockAPIClient) GetCodespace(ctx context.Context, token, userLogin, codespaceName string) (*api.Codespace, error) {
if m.getCodespace == nil {
return nil, errors.New("mock api client GetCodespace not implemented")
}
return m.getCodespace(ctx, token, userLogin, codespaceName)
}
func TestPollForCodespace(t *testing.T) {
logger := output.NewLogger(nil, nil, false)
user := &api.User{Login: "test"}
tmpCodespace := &api.Codespace{Name: "tmp-codespace"}
codespaceToken := "codespace-token"
ctx := context.Background()
pollInterval := 50 * time.Millisecond
pollTimeout := 100 * time.Millisecond
api := &mockAPIClient{
getCodespaceToken: func(ctx context.Context, userLogin, codespace string) (string, error) {
if userLogin != user.Login {
return "", fmt.Errorf("user does not match, got: %s, expected: %s", userLogin, user.Login)
}
if codespace != tmpCodespace.Name {
return "", fmt.Errorf("codespace does not match, got: %s, expected: %s", codespace, tmpCodespace.Name)
}
return codespaceToken, nil
},
getCodespace: func(ctx context.Context, token, userLogin, codespace string) (*api.Codespace, error) {
if token != codespaceToken {
return nil, fmt.Errorf("token does not match, got: %s, expected: %s", token, codespaceToken)
}
if userLogin != user.Login {
return nil, fmt.Errorf("user does not match, got: %s, expected: %s", userLogin, user.Login)
}
if codespace != tmpCodespace.Name {
return nil, fmt.Errorf("codespace does not match, got: %s, expected: %s", codespace, tmpCodespace.Name)
}
return tmpCodespace, nil
},
}
codespace, err := pollForCodespace(ctx, api, logger, pollTimeout, pollInterval, user.Login, tmpCodespace.Name)
if err != nil {
t.Error(err)
}
if tmpCodespace.Name != codespace.Name {
t.Errorf("returned codespace does not match, got: %s, expected: %s", codespace.Name, tmpCodespace.Name)
}
// swap the durations to trigger a timeout
pollTimeout, pollInterval = pollInterval, pollTimeout
_, err = pollForCodespace(ctx, api, logger, pollTimeout, pollInterval, user.Login, tmpCodespace.Name)
if err != context.DeadlineExceeded {
t.Error("expected context deadline exceeded error, got nil")
}
}