Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prod deploy #2849

Merged
merged 14 commits into from
Nov 7, 2024
Merged
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
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ require (
github.com/go-xmlfmt/xmlfmt v1.1.2
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/golangci/golangci-lint v1.61.0
github.com/google/go-cmp v0.6.0
github.com/google/go-github/v62 v62.0.0
github.com/google/go-querystring v1.1.0
github.com/google/uuid v1.6.0
Expand Down Expand Up @@ -170,6 +169,7 @@ require (
github.com/golangci/plugin-module-register v0.1.1 // indirect
github.com/golangci/revgrep v0.5.3 // indirect
github.com/golangci/unconvert v0.0.0-20240309020433-c5143eacb3ed // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/gordonklaus/ineffassign v0.1.0 // indirect
github.com/gorilla/css v1.0.0 // indirect
Expand Down
64 changes: 34 additions & 30 deletions internal/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"net/http"
"os"
"os/user"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -43,8 +42,6 @@ type AccessTokenResponse struct {
Nonce string `json:"nonce"`
}

const defaultRetryAfterSeconds = 2
const defaultMaxRetries = 90
const decryptionErrorMsg = "cannot decrypt access token"

var loggedInMsg = "You are now logged in. " + utils.Aqua("Happy coding!")
Expand Down Expand Up @@ -128,6 +125,8 @@ func (enc LoginEncryption) decryptAccessToken(accessToken string, publicKey stri
return string(decryptedAccessToken), nil
}

const maxRetries = 2

func pollForAccessToken(ctx context.Context, url string) (AccessTokenResponse, error) {
// TODO: Move to OpenAPI-generated http client once we reach v1 on API schema.
client := fetcher.NewFetcher(
Expand All @@ -137,20 +136,31 @@ func pollForAccessToken(ctx context.Context, url string) (AccessTokenResponse, e
}),
fetcher.WithExpectedStatus(http.StatusOK),
)
timeout := backoff.NewConstantBackOff(defaultRetryAfterSeconds)
console := utils.NewConsole()
probe := func() (AccessTokenResponse, error) {
resp, err := client.Send(ctx, http.MethodGet, url, nil)
if err == nil {
return fetcher.ParseJSON[AccessTokenResponse](resp.Body)
} else if resp != nil {
if retryAfterSeconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil {
timeout.Interval = time.Duration(retryAfterSeconds) * time.Second
}
// TODO: support automatic login flow
deviceCode, err := console.PromptText(ctx, "Enter your verification code: ")
if err != nil {
return AccessTokenResponse{}, err
}
urlWithQuery := fmt.Sprintf("%s?device_code=%s", url, deviceCode)
resp, err := client.Send(ctx, http.MethodGet, urlWithQuery, nil)
if err != nil {
return AccessTokenResponse{}, err
}
return AccessTokenResponse{}, err
return fetcher.ParseJSON[AccessTokenResponse](resp.Body)
}
policy := backoff.WithContext(backoff.WithMaxRetries(&backoff.ZeroBackOff{}, maxRetries), ctx)
return backoff.RetryNotifyWithData(probe, policy, newErrorCallback())
}

func newErrorCallback() backoff.Notify {
failureCount := 0
return func(err error, d time.Duration) {
failureCount += 1
fmt.Fprintln(os.Stderr, err)
fmt.Fprintf(os.Stderr, "Retry (%d/%d): ", failureCount, maxRetries)
}
policy := backoff.WithContext(backoff.WithMaxRetries(timeout, defaultMaxRetries), ctx)
return backoff.RetryWithData(probe, policy)
}

func Run(ctx context.Context, stdout io.Writer, params RunParams) error {
Expand Down Expand Up @@ -194,22 +204,16 @@ func Run(ctx context.Context, stdout io.Writer, params RunParams) error {
fmt.Fprintf(stdout, "Here is your login link, open it in the browser %s\n\n", utils.Bold(createLoginSessionUrl))
}

if err := utils.RunProgram(ctx, func(p utils.Program, ctx context.Context) error {
p.Send(utils.StatusMsg("Your token is now being generated and securely encrypted. Waiting for it to arrive..."))

sessionPollingUrl := "/platform/cli/login/" + params.SessionId
accessTokenResponse, err := pollForAccessToken(ctx, sessionPollingUrl)
if err != nil {
return err
}

decryptedAccessToken, err := params.Encryption.decryptAccessToken(accessTokenResponse.AccessToken, accessTokenResponse.PublicKey, accessTokenResponse.Nonce)
if err != nil {
return err
}

return utils.SaveAccessToken(decryptedAccessToken, params.Fsys)
}); err != nil {
sessionPollingUrl := "/platform/cli/login/" + params.SessionId
accessTokenResponse, err := pollForAccessToken(ctx, sessionPollingUrl)
if err != nil {
return err
}
decryptedAccessToken, err := params.Encryption.decryptAccessToken(accessTokenResponse.AccessToken, accessTokenResponse.PublicKey, accessTokenResponse.Nonce)
if err != nil {
return err
}
if err := utils.SaveAccessToken(decryptedAccessToken, params.Fsys); err != nil {
return err
}

Expand Down
13 changes: 9 additions & 4 deletions pkg/cast/cast.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ import "math"
// UintToInt converts a uint to an int, handling potential overflow
func UintToInt(value uint) int {
if value <= math.MaxInt {
result := int(value)
return result
return int(value)
}
maxInt := math.MaxInt
return maxInt
return math.MaxInt
}

// IntToUint converts an int to a uint, handling negative values
Expand Down Expand Up @@ -37,3 +35,10 @@ func IntToUintPtr(value *int) *uint {
func Ptr[T any](v T) *T {
return &v
}

func Val[T any](v *T, def T) T {
if v == nil {
return def
}
return *v
}
10 changes: 4 additions & 6 deletions pkg/config/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,15 @@ func (a *api) fromRemoteApiConfig(remoteConfig v1API.PostgrestConfigWithJWTSecre

result.Enabled = true
// Update Schemas if present in remoteConfig
schemas := strings.Split(remoteConfig.DbSchema, ",")
result.Schemas = make([]string, len(schemas))
result.Schemas = strToArr(remoteConfig.DbSchema)
// TODO: use slices.Map when upgrade go version
for i, schema := range schemas {
for i, schema := range result.Schemas {
result.Schemas[i] = strings.TrimSpace(schema)
}

// Update ExtraSearchPath if present in remoteConfig
extraSearchPath := strings.Split(remoteConfig.DbExtraSearchPath, ",")
result.ExtraSearchPath = make([]string, len(extraSearchPath))
for i, path := range extraSearchPath {
result.ExtraSearchPath = strToArr(remoteConfig.DbExtraSearchPath)
for i, path := range result.ExtraSearchPath {
result.ExtraSearchPath[i] = strings.TrimSpace(path)
}

Expand Down
Loading
Loading