diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4dea84c..1e80c0b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -26,13 +26,15 @@ jobs: run: echo "$HOME/go/bin" >> $GITHUB_PATH - name: Run commands generation command run: make gen + - name: Run proto generation command + run: make proto - name: Verify no changes were generated run: | # Check if there are any uncommitted changes in the working directory if [ -z "$(git status --porcelain)" ]; then echo "::notice::Generated files are up to date. No changes detected." else - echo "::error::Detected uncommitted changes after running the generation command. Please run the generator and commit the changes." + echo "::error::Detected uncommitted changes after running the generation command. Please run `make gen` and `make proto` and commit the changes." git status git diff exit 1 diff --git a/Makefile b/Makefile index 073034d..10bd520 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all install gen build test mocks +.PHONY: all install buf-install gen proto build test mocks # Load .env file if it exists (for local development) # In CI/CD, environment variables are provided by the environment @@ -13,7 +13,7 @@ VERSION := $(shell git describe --tags --always --dirty 2>/dev/null) VERSION_PKG := github.com/temporalio/cloud-cli/temporalcloudcli LDFLAGS := $(if $(VERSION),-X $(VERSION_PKG).Version=$(VERSION)) -all: gen build mocks test +all: gen proto build mocks test # we need to install gen-commands directly because gen-commands does not have its # own go.mod @@ -25,6 +25,15 @@ install: gen: install gen-commands -input ./temporalcloudcli/commands.yml -pkg temporalcloudcli > ./temporalcloudcli/commands.gen.go +buf-install: + go install github.com/bufbuild/buf/cmd/buf@v1.50.0 + +# Regenerates the vendored onboarding service client (proto/ -> internal/). +# The protoc plugins are pinned as go tools in go.mod. +proto: buf-install + buf lint + buf generate + build: go build -ldflags "$(LDFLAGS)" ./cmd/temporal-cloud diff --git a/buf.gen.yaml b/buf.gen.yaml new file mode 100644 index 0000000..f3faa39 --- /dev/null +++ b/buf.gen.yaml @@ -0,0 +1,10 @@ +version: v2 +inputs: + - directory: proto +plugins: + - local: ["go", "tool", "protoc-gen-go"] + out: internal + opt: [paths=source_relative] + - local: ["go", "tool", "protoc-gen-go-grpc"] + out: internal + opt: [paths=source_relative] diff --git a/buf.yaml b/buf.yaml new file mode 100644 index 0000000..edddcf7 --- /dev/null +++ b/buf.yaml @@ -0,0 +1,12 @@ +version: v2 +modules: + - path: proto +lint: + use: + - STANDARD + except: + - PACKAGE_DIRECTORY_MATCH + - RPC_REQUEST_RESPONSE_UNIQUE + - RPC_REQUEST_STANDARD_NAME + - RPC_RESPONSE_STANDARD_NAME + - SERVICE_SUFFIX diff --git a/go.mod b/go.mod index 2fac367..4d3524c 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( go.temporal.io/sdk/contrib/envconfig v1.0.0 golang.org/x/oauth2 v0.36.0 golang.org/x/term v0.46.0 + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa google.golang.org/grpc v1.82.1 google.golang.org/protobuf v1.36.11 ) @@ -79,8 +80,12 @@ require ( golang.org/x/time v0.15.0 // indirect golang.org/x/tools v0.51.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) -tool github.com/vektra/mockery/v3 +tool ( + github.com/vektra/mockery/v3 + google.golang.org/grpc/cmd/protoc-gen-go-grpc + google.golang.org/protobuf/cmd/protoc-gen-go +) diff --git a/go.sum b/go.sum index ec83f5e..4764b02 100644 --- a/go.sum +++ b/go.sum @@ -229,6 +229,8 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1: google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE= google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 h1:F29+wU6Ee6qgu9TddPgooOdaqsxTMunOoj8KA5yuS5A= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1/go.mod h1:5KF+wpkbTSbGcR9zteSqZV6fqFOWBl4Yde8En8MryZA= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/onboarding/rejection.go b/internal/onboarding/rejection.go new file mode 100644 index 0000000..f61c1cd --- /dev/null +++ b/internal/onboarding/rejection.go @@ -0,0 +1,37 @@ +package onboarding + +import ( + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Reasons the onboarding service gives, as a google.rpc.ErrorInfo reason on a +// FailedPrecondition, for refusing a CLI signup. +const ( + // ReasonAlreadyOnboarded: the user already had an account before this signup. + ReasonAlreadyOnboarded = "ALREADY_ONBOARDED" + // ReasonTrialSignupUnavailable: CLI signup is turned off. + ReasonTrialSignupUnavailable = "TRIAL_SIGNUP_UNAVAILABLE" + // ReasonBrowserSignupInProgress: the user has a signup running in the browser. + ReasonBrowserSignupInProgress = "BROWSER_SIGNUP_IN_PROGRESS" + // ReasonTrialSignupCancelled: the user's signup was cancelled. + ReasonTrialSignupCancelled = "TRIAL_SIGNUP_CANCELLED" +) + +const errorInfoDomain = "cloud.temporal.io" + +// RejectionReason returns the ErrorInfo reason of a signup refused by the +// onboarding service, or "" when err is not one. err may be wrapped. +func RejectionReason(err error) string { + st, ok := status.FromError(err) + if !ok || st.Code() != codes.FailedPrecondition { + return "" + } + for _, detail := range st.Details() { + if info, ok := detail.(*errdetails.ErrorInfo); ok && info.GetDomain() == errorInfoDomain { + return info.GetReason() + } + } + return "" +} diff --git a/internal/onboarding/rejection_test.go b/internal/onboarding/rejection_test.go new file mode 100644 index 0000000..0480bbf --- /dev/null +++ b/internal/onboarding/rejection_test.go @@ -0,0 +1,66 @@ +package onboarding_test + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/temporalio/cloud-cli/internal/onboarding" +) + +func rejection(t *testing.T, code codes.Code, domain, reason string) error { + t.Helper() + st, err := status.New(code, "refused").WithDetails(&errdetails.ErrorInfo{Domain: domain, Reason: reason}) + require.NoError(t, err) + return st.Err() +} + +func TestRejectionReason(t *testing.T) { + tests := []struct { + name string + err error + expected string + }{ + { + name: "signup rejection", + err: rejection(t, codes.FailedPrecondition, "cloud.temporal.io", onboarding.ReasonAlreadyOnboarded), + expected: onboarding.ReasonAlreadyOnboarded, + }, + { + name: "wrapped signup rejection", + err: fmt.Errorf("failed to get onboarding state: %w", + rejection(t, codes.FailedPrecondition, "cloud.temporal.io", onboarding.ReasonTrialSignupCancelled)), + expected: onboarding.ReasonTrialSignupCancelled, + }, + { + name: "other domain", + err: rejection(t, codes.FailedPrecondition, "example.com", onboarding.ReasonAlreadyOnboarded), + }, + { + name: "other code", + err: rejection(t, codes.PermissionDenied, "cloud.temporal.io", onboarding.ReasonAlreadyOnboarded), + }, + { + name: "no details", + err: status.Error(codes.FailedPrecondition, "refused"), + }, + { + name: "not a grpc error", + err: errors.New("boom"), + }, + { + name: "nil", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, onboarding.RejectionReason(tt.err)) + }) + } +} diff --git a/internal/onboarding/wait.go b/internal/onboarding/wait.go new file mode 100644 index 0000000..0830548 --- /dev/null +++ b/internal/onboarding/wait.go @@ -0,0 +1,117 @@ +package onboarding + +import ( + "context" + "errors" + "fmt" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + onboardingservice "github.com/temporalio/cloud-cli/internal/onboardingservice/v1" +) + +type Client interface { + GetOrCreateCLIOnboardingState( + ctx context.Context, + in *onboardingservice.GetOrCreateCLIOnboardingStateRequest, + opts ...grpc.CallOption, + ) (*onboardingservice.GetOrCreateCLIOnboardingStateResponse, error) +} + +type PollConfig struct { + Interval time.Duration + MaxInterval time.Duration + FastAttempts int + // MaxConsecutiveFailures is how many retryable errors in a row Wait + // tolerates before returning the last one. A successful response resets + // the count. Zero means no limit. + MaxConsecutiveFailures int +} + +// DefaultPollConfig matches the website's waitForStep: +// 1s for 10 polls, then doubling to a 30s cap. 15 failures in a row gives up +// after about 40s if the first polls fail, or about 7.5 minutes once polling +// has slowed to 30s. +var DefaultPollConfig = PollConfig{ + Interval: time.Second, + MaxInterval: 30 * time.Second, + FastAttempts: 10, + MaxConsecutiveFailures: 15, +} + +func IsComplete(resp *onboardingservice.GetOrCreateCLIOnboardingStateResponse) bool { + return resp.GetUserAlreadyExists() || + resp.GetState().GetCurrentStep() == onboardingservice.StepType_STEP_TYPE_END_OF_FUNNEL +} + +// Wait calls GetOrCreateCLIOnboardingState until onboarding is complete. +func Wait( + ctx context.Context, + client Client, + req *onboardingservice.GetOrCreateCLIOnboardingStateRequest, + cfg PollConfig, + onStep func(onboardingservice.StepType), +) (*onboardingservice.GetOrCreateCLIOnboardingStateResponse, error) { + interval := cfg.Interval + lastStep := onboardingservice.StepType(-1) + failures := 0 + + for attempt := 1; ; attempt++ { + resp, err := client.GetOrCreateCLIOnboardingState(ctx, req) + switch { + case ctx.Err() != nil: + return nil, waitError(ctx, lastStep) + case err == nil: + failures = 0 + if IsComplete(resp) { + return resp, nil + } + if step := resp.GetState().GetCurrentStep(); step != lastStep { + lastStep = step + if onStep != nil { + onStep(step) + } + } + case !isRetryable(err): + return nil, fmt.Errorf("failed to get onboarding state: %w", err) + default: + failures++ + if cfg.MaxConsecutiveFailures > 0 && failures >= cfg.MaxConsecutiveFailures { + return nil, fmt.Errorf("failed to get onboarding state: %w", err) + } + } + + if attempt > cfg.FastAttempts { + interval = min(interval*2, cfg.MaxInterval) + } + timer := time.NewTimer(interval) + select { + case <-ctx.Done(): + timer.Stop() + return nil, waitError(ctx, lastStep) + case <-timer.C: + } + } +} + +func isRetryable(err error) bool { + switch status.Code(err) { + case codes.Unavailable, codes.ResourceExhausted: + return true + default: + return false + } +} + +func waitError(ctx context.Context, lastStep onboardingservice.StepType) error { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + if lastStep < 0 { + return errors.New("timed out waiting for onboarding to start") + } + return fmt.Errorf("timed out waiting for onboarding to complete (last step: %s)", lastStep) + } + return ctx.Err() +} diff --git a/internal/onboarding/wait_test.go b/internal/onboarding/wait_test.go new file mode 100644 index 0000000..5304f6b --- /dev/null +++ b/internal/onboarding/wait_test.go @@ -0,0 +1,165 @@ +package onboarding_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/temporalio/cloud-cli/internal/onboarding" + onboardingservice "github.com/temporalio/cloud-cli/internal/onboardingservice/v1" +) + +type result struct { + resp *onboardingservice.GetOrCreateCLIOnboardingStateResponse + err error +} + +// fakeClient returns scripted results in order, repeating the last one. +type fakeClient struct { + results []result + calls int +} + +func (f *fakeClient) GetOrCreateCLIOnboardingState( + context.Context, *onboardingservice.GetOrCreateCLIOnboardingStateRequest, ...grpc.CallOption, +) (*onboardingservice.GetOrCreateCLIOnboardingStateResponse, error) { + r := f.results[min(f.calls, len(f.results)-1)] + f.calls++ + return r.resp, r.err +} + +func atStep(step onboardingservice.StepType) result { + return result{resp: &onboardingservice.GetOrCreateCLIOnboardingStateResponse{ + State: &onboardingservice.OnboardingState{CurrentStep: step}, + }} +} + +var fastPoll = onboarding.PollConfig{Interval: time.Millisecond, MaxInterval: 2 * time.Millisecond, FastAttempts: 2} + +func TestWait(t *testing.T) { + alreadyExists := result{resp: &onboardingservice.GetOrCreateCLIOnboardingStateResponse{UserAlreadyExists: true}} + done := atStep(onboardingservice.StepType_STEP_TYPE_END_OF_FUNNEL) + creating := atStep(onboardingservice.StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION) + + tests := []struct { + name string + results []result + timeout time.Duration + expectedResp *onboardingservice.GetOrCreateCLIOnboardingStateResponse + expectedErr string + expectedCalls int + expectedSteps []onboardingservice.StepType + maxFailures int + }{ + { + name: "user already exists returns immediately", + results: []result{alreadyExists}, + expectedResp: alreadyExists.resp, + expectedCalls: 1, + }, + { + name: "polls until end of funnel and reports each step once", + results: []result{creating, creating, creating, done}, + expectedResp: done.resp, + expectedCalls: 4, + expectedSteps: []onboardingservice.StepType{onboardingservice.StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION}, + }, + { + name: "retries unavailable and rate limited", + results: []result{ + {err: status.Error(codes.Unavailable, "down")}, + {err: status.Error(codes.ResourceExhausted, "slow down")}, + done, + }, + expectedResp: done.resp, + expectedCalls: 3, + }, + { + name: "stops on permission denied", + results: []result{{err: status.Error(codes.PermissionDenied, "user not allowed")}}, + expectedErr: "failed to get onboarding state: rpc error: code = PermissionDenied desc = user not allowed", + expectedCalls: 1, + }, + { + name: "times out with the last step", + results: []result{creating}, + timeout: 20 * time.Millisecond, + expectedErr: "timed out waiting for onboarding to complete (last step: STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION)", + expectedSteps: []onboardingservice.StepType{onboardingservice.StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION}, + }, + { + name: "gives up after too many failures in a row", + results: []result{{err: status.Error(codes.Unavailable, "down")}}, + maxFailures: 3, + expectedErr: "failed to get onboarding state: rpc error: code = Unavailable desc = down", + expectedCalls: 3, + }, + { + name: "a successful response resets the failure count", + results: []result{ + {err: status.Error(codes.Unavailable, "down")}, + {err: status.Error(codes.Unavailable, "down")}, + creating, + {err: status.Error(codes.Unavailable, "down")}, + {err: status.Error(codes.Unavailable, "down")}, + done, + }, + maxFailures: 3, + expectedResp: done.resp, + expectedCalls: 6, + expectedSteps: []onboardingservice.StepType{onboardingservice.StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION}, + }, + { + name: "times out before any state", + results: []result{{err: status.Error(codes.Unavailable, "down")}}, + timeout: 20 * time.Millisecond, + expectedErr: "timed out waiting for onboarding to start", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx := context.Background() + if tt.timeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, tt.timeout) + defer cancel() + } + client := &fakeClient{results: tt.results} + var steps []onboardingservice.StepType + + cfg := fastPoll + cfg.MaxConsecutiveFailures = tt.maxFailures + resp, err := onboarding.Wait(ctx, client, &onboardingservice.GetOrCreateCLIOnboardingStateRequest{}, cfg, + func(s onboardingservice.StepType) { steps = append(steps, s) }) + + if tt.expectedErr != "" { + require.EqualError(t, err, tt.expectedErr) + } else { + require.NoError(t, err) + assert.Equal(t, tt.expectedResp, resp) + } + if tt.expectedCalls > 0 { + assert.Equal(t, tt.expectedCalls, client.calls) + } + assert.Equal(t, tt.expectedSteps, steps) + }) + } +} + +func TestWait_Canceled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, err := onboarding.Wait(ctx, &fakeClient{results: []result{atStep(onboardingservice.StepType_STEP_TYPE_UNSPECIFIED)}}, + &onboardingservice.GetOrCreateCLIOnboardingStateRequest{}, fastPoll, nil) + + require.True(t, errors.Is(err, context.Canceled)) +} diff --git a/internal/onboardingservice/v1/onboarding.pb.go b/internal/onboardingservice/v1/onboarding.pb.go new file mode 100644 index 0000000..88f4151 --- /dev/null +++ b/internal/onboardingservice/v1/onboarding.pb.go @@ -0,0 +1,416 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc (unknown) +// source: onboardingservice/v1/onboarding.proto + +// The subset of the Temporal Cloud onboarding messages that the CLI uses. Field +// numbers and types must match the server exactly. Fields the CLI doesn't use +// are reserved, and the decoder skips them as unknown fields. + +package onboardingservice + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type StepType int32 + +const ( + StepType_STEP_TYPE_UNSPECIFIED StepType = 0 + StepType_STEP_TYPE_CUSTOMER_DETAILS_COLLECTION StepType = 1 + StepType_STEP_TYPE_WAIT_FOR_THROTTLE StepType = 2 + StepType_STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP StepType = 3 + StepType_STEP_TYPE_PAYMENT_COLLECTION StepType = 4 + StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION StepType = 5 + StepType_STEP_TYPE_END_OF_FUNNEL StepType = 6 +) + +// Enum value maps for StepType. +var ( + StepType_name = map[int32]string{ + 0: "STEP_TYPE_UNSPECIFIED", + 1: "STEP_TYPE_CUSTOMER_DETAILS_COLLECTION", + 2: "STEP_TYPE_WAIT_FOR_THROTTLE", + 3: "STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP", + 4: "STEP_TYPE_PAYMENT_COLLECTION", + 5: "STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION", + 6: "STEP_TYPE_END_OF_FUNNEL", + } + StepType_value = map[string]int32{ + "STEP_TYPE_UNSPECIFIED": 0, + "STEP_TYPE_CUSTOMER_DETAILS_COLLECTION": 1, + "STEP_TYPE_WAIT_FOR_THROTTLE": 2, + "STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP": 3, + "STEP_TYPE_PAYMENT_COLLECTION": 4, + "STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION": 5, + "STEP_TYPE_END_OF_FUNNEL": 6, + } +) + +func (x StepType) Enum() *StepType { + p := new(StepType) + *p = x + return p +} + +func (x StepType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (StepType) Descriptor() protoreflect.EnumDescriptor { + return file_onboardingservice_v1_onboarding_proto_enumTypes[0].Descriptor() +} + +func (StepType) Type() protoreflect.EnumType { + return &file_onboardingservice_v1_onboarding_proto_enumTypes[0] +} + +func (x StepType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use StepType.Descriptor instead. +func (StepType) EnumDescriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{0} +} + +type OnboardingState struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Indicates the current step of the funnel the user is on + CurrentStep StepType `protobuf:"varint,1,opt,name=current_step,json=currentStep,proto3,enum=onboardingservice.v1.StepType" json:"current_step,omitempty"` + UserEmail string `protobuf:"bytes,7,opt,name=user_email,json=userEmail,proto3" json:"user_email,omitempty"` + // The Temporal Cloud user id of the user, if available. Empty if the user does not have one yet. + UserId string `protobuf:"bytes,12,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *OnboardingState) Reset() { + *x = OnboardingState{} + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *OnboardingState) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OnboardingState) ProtoMessage() {} + +func (x *OnboardingState) ProtoReflect() protoreflect.Message { + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OnboardingState.ProtoReflect.Descriptor instead. +func (*OnboardingState) Descriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{0} +} + +func (x *OnboardingState) GetCurrentStep() StepType { + if x != nil { + return x.CurrentStep + } + return StepType_STEP_TYPE_UNSPECIFIED +} + +func (x *OnboardingState) GetUserEmail() string { + if x != nil { + return x.UserEmail + } + return "" +} + +func (x *OnboardingState) GetUserId() string { + if x != nil { + return x.UserId + } + return "" +} + +type GetOrCreateCLIOnboardingStateRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Optional, as is every field in it; the CLI sends whatever its login provides. + CustomerDetails *CustomerDetails `protobuf:"bytes,1,opt,name=customer_details,json=customerDetails,proto3" json:"customer_details,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetOrCreateCLIOnboardingStateRequest) Reset() { + *x = GetOrCreateCLIOnboardingStateRequest{} + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetOrCreateCLIOnboardingStateRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetOrCreateCLIOnboardingStateRequest) ProtoMessage() {} + +func (x *GetOrCreateCLIOnboardingStateRequest) ProtoReflect() protoreflect.Message { + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetOrCreateCLIOnboardingStateRequest.ProtoReflect.Descriptor instead. +func (*GetOrCreateCLIOnboardingStateRequest) Descriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{1} +} + +func (x *GetOrCreateCLIOnboardingStateRequest) GetCustomerDetails() *CustomerDetails { + if x != nil { + return x.CustomerDetails + } + return nil +} + +type GetOrCreateCLIOnboardingStateResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserAlreadyExists bool `protobuf:"varint,1,opt,name=user_already_exists,json=userAlreadyExists,proto3" json:"user_already_exists,omitempty"` + // Empty if user_already_exists is true. + State *OnboardingState `protobuf:"bytes,2,opt,name=state,proto3" json:"state,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetOrCreateCLIOnboardingStateResponse) Reset() { + *x = GetOrCreateCLIOnboardingStateResponse{} + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetOrCreateCLIOnboardingStateResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetOrCreateCLIOnboardingStateResponse) ProtoMessage() {} + +func (x *GetOrCreateCLIOnboardingStateResponse) ProtoReflect() protoreflect.Message { + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetOrCreateCLIOnboardingStateResponse.ProtoReflect.Descriptor instead. +func (*GetOrCreateCLIOnboardingStateResponse) Descriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{2} +} + +func (x *GetOrCreateCLIOnboardingStateResponse) GetUserAlreadyExists() bool { + if x != nil { + return x.UserAlreadyExists + } + return false +} + +func (x *GetOrCreateCLIOnboardingStateResponse) GetState() *OnboardingState { + if x != nil { + return x.State + } + return nil +} + +type CustomerDetails struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The first name of the customer. + FirstName string `protobuf:"bytes,1,opt,name=first_name,json=firstName,proto3" json:"first_name,omitempty"` + // The last name of the customer. + LastName string `protobuf:"bytes,2,opt,name=last_name,json=lastName,proto3" json:"last_name,omitempty"` + // The name of the company the user is from. + CompanyName string `protobuf:"bytes,3,opt,name=company_name,json=companyName,proto3" json:"company_name,omitempty"` + // The country of the user. + Country string `protobuf:"bytes,4,opt,name=country,proto3" json:"country,omitempty"` + // Indicates whether the user is interested in receiving marketing emails from Temporal + OptInMarketingEmail bool `protobuf:"varint,7,opt,name=opt_in_marketing_email,json=optInMarketingEmail,proto3" json:"opt_in_marketing_email,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CustomerDetails) Reset() { + *x = CustomerDetails{} + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CustomerDetails) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CustomerDetails) ProtoMessage() {} + +func (x *CustomerDetails) ProtoReflect() protoreflect.Message { + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CustomerDetails.ProtoReflect.Descriptor instead. +func (*CustomerDetails) Descriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{3} +} + +func (x *CustomerDetails) GetFirstName() string { + if x != nil { + return x.FirstName + } + return "" +} + +func (x *CustomerDetails) GetLastName() string { + if x != nil { + return x.LastName + } + return "" +} + +func (x *CustomerDetails) GetCompanyName() string { + if x != nil { + return x.CompanyName + } + return "" +} + +func (x *CustomerDetails) GetCountry() string { + if x != nil { + return x.Country + } + return "" +} + +func (x *CustomerDetails) GetOptInMarketingEmail() bool { + if x != nil { + return x.OptInMarketingEmail + } + return false +} + +var File_onboardingservice_v1_onboarding_proto protoreflect.FileDescriptor + +const file_onboardingservice_v1_onboarding_proto_rawDesc = "" + + "\n" + + "%onboardingservice/v1/onboarding.proto\x12\x14onboardingservice.v1\"\x98\x01\n" + + "\x0fOnboardingState\x12A\n" + + "\fcurrent_step\x18\x01 \x01(\x0e2\x1e.onboardingservice.v1.StepTypeR\vcurrentStep\x12\x1d\n" + + "\n" + + "user_email\x18\a \x01(\tR\tuserEmail\x12\x17\n" + + "\auser_id\x18\f \x01(\tR\x06userIdJ\x04\b\x02\x10\aJ\x04\b\b\x10\f\"x\n" + + "$GetOrCreateCLIOnboardingStateRequest\x12P\n" + + "\x10customer_details\x18\x01 \x01(\v2%.onboardingservice.v1.CustomerDetailsR\x0fcustomerDetails\"\x94\x01\n" + + "%GetOrCreateCLIOnboardingStateResponse\x12.\n" + + "\x13user_already_exists\x18\x01 \x01(\bR\x11userAlreadyExists\x12;\n" + + "\x05state\x18\x02 \x01(\v2%.onboardingservice.v1.OnboardingStateR\x05state\"\xd1\x01\n" + + "\x0fCustomerDetails\x12\x1d\n" + + "\n" + + "first_name\x18\x01 \x01(\tR\tfirstName\x12\x1b\n" + + "\tlast_name\x18\x02 \x01(\tR\blastName\x12!\n" + + "\fcompany_name\x18\x03 \x01(\tR\vcompanyName\x12\x18\n" + + "\acountry\x18\x04 \x01(\tR\acountry\x123\n" + + "\x16opt_in_marketing_email\x18\a \x01(\bR\x13optInMarketingEmailJ\x04\b\x05\x10\x06J\x04\b\x06\x10\aJ\x04\b\b\x10\t*\x88\x02\n" + + "\bStepType\x12\x19\n" + + "\x15STEP_TYPE_UNSPECIFIED\x10\x00\x12)\n" + + "%STEP_TYPE_CUSTOMER_DETAILS_COLLECTION\x10\x01\x12\x1f\n" + + "\x1bSTEP_TYPE_WAIT_FOR_THROTTLE\x10\x02\x12-\n" + + ")STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP\x10\x03\x12 \n" + + "\x1cSTEP_TYPE_PAYMENT_COLLECTION\x10\x04\x12'\n" + + "#STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION\x10\x05\x12\x1b\n" + + "\x17STEP_TYPE_END_OF_FUNNEL\x10\x06BQZOgithub.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingserviceb\x06proto3" + +var ( + file_onboardingservice_v1_onboarding_proto_rawDescOnce sync.Once + file_onboardingservice_v1_onboarding_proto_rawDescData []byte +) + +func file_onboardingservice_v1_onboarding_proto_rawDescGZIP() []byte { + file_onboardingservice_v1_onboarding_proto_rawDescOnce.Do(func() { + file_onboardingservice_v1_onboarding_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_onboardingservice_v1_onboarding_proto_rawDesc), len(file_onboardingservice_v1_onboarding_proto_rawDesc))) + }) + return file_onboardingservice_v1_onboarding_proto_rawDescData +} + +var file_onboardingservice_v1_onboarding_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_onboardingservice_v1_onboarding_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_onboardingservice_v1_onboarding_proto_goTypes = []any{ + (StepType)(0), // 0: onboardingservice.v1.StepType + (*OnboardingState)(nil), // 1: onboardingservice.v1.OnboardingState + (*GetOrCreateCLIOnboardingStateRequest)(nil), // 2: onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest + (*GetOrCreateCLIOnboardingStateResponse)(nil), // 3: onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse + (*CustomerDetails)(nil), // 4: onboardingservice.v1.CustomerDetails +} +var file_onboardingservice_v1_onboarding_proto_depIdxs = []int32{ + 0, // 0: onboardingservice.v1.OnboardingState.current_step:type_name -> onboardingservice.v1.StepType + 4, // 1: onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest.customer_details:type_name -> onboardingservice.v1.CustomerDetails + 1, // 2: onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse.state:type_name -> onboardingservice.v1.OnboardingState + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_onboardingservice_v1_onboarding_proto_init() } +func file_onboardingservice_v1_onboarding_proto_init() { + if File_onboardingservice_v1_onboarding_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_onboardingservice_v1_onboarding_proto_rawDesc), len(file_onboardingservice_v1_onboarding_proto_rawDesc)), + NumEnums: 1, + NumMessages: 4, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_onboardingservice_v1_onboarding_proto_goTypes, + DependencyIndexes: file_onboardingservice_v1_onboarding_proto_depIdxs, + EnumInfos: file_onboardingservice_v1_onboarding_proto_enumTypes, + MessageInfos: file_onboardingservice_v1_onboarding_proto_msgTypes, + }.Build() + File_onboardingservice_v1_onboarding_proto = out.File + file_onboardingservice_v1_onboarding_proto_goTypes = nil + file_onboardingservice_v1_onboarding_proto_depIdxs = nil +} diff --git a/internal/onboardingservice/v1/service.pb.go b/internal/onboardingservice/v1/service.pb.go new file mode 100644 index 0000000..4a9cab8 --- /dev/null +++ b/internal/onboardingservice/v1/service.pb.go @@ -0,0 +1,71 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc (unknown) +// source: onboardingservice/v1/service.proto + +// The subset of the Temporal Cloud onboarding service that the CLI calls. The +// package, service, RPC and message names form the gRPC method path on the +// wire, so they must match the server exactly. + +package onboardingservice + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +var File_onboardingservice_v1_service_proto protoreflect.FileDescriptor + +const file_onboardingservice_v1_service_proto_rawDesc = "" + + "\n" + + "\"onboardingservice/v1/service.proto\x12\x14onboardingservice.v1\x1a%onboardingservice/v1/onboarding.proto2\xb0\x01\n" + + "\x11OnboardingService\x12\x9a\x01\n" + + "\x1dGetOrCreateCLIOnboardingState\x12:.onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest\x1a;.onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse\"\x00BQZOgithub.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingserviceb\x06proto3" + +var file_onboardingservice_v1_service_proto_goTypes = []any{ + (*GetOrCreateCLIOnboardingStateRequest)(nil), // 0: onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest + (*GetOrCreateCLIOnboardingStateResponse)(nil), // 1: onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse +} +var file_onboardingservice_v1_service_proto_depIdxs = []int32{ + 0, // 0: onboardingservice.v1.OnboardingService.GetOrCreateCLIOnboardingState:input_type -> onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest + 1, // 1: onboardingservice.v1.OnboardingService.GetOrCreateCLIOnboardingState:output_type -> onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse + 1, // [1:2] is the sub-list for method output_type + 0, // [0:1] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_onboardingservice_v1_service_proto_init() } +func file_onboardingservice_v1_service_proto_init() { + if File_onboardingservice_v1_service_proto != nil { + return + } + file_onboardingservice_v1_onboarding_proto_init() + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_onboardingservice_v1_service_proto_rawDesc), len(file_onboardingservice_v1_service_proto_rawDesc)), + NumEnums: 0, + NumMessages: 0, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_onboardingservice_v1_service_proto_goTypes, + DependencyIndexes: file_onboardingservice_v1_service_proto_depIdxs, + }.Build() + File_onboardingservice_v1_service_proto = out.File + file_onboardingservice_v1_service_proto_goTypes = nil + file_onboardingservice_v1_service_proto_depIdxs = nil +} diff --git a/internal/onboardingservice/v1/service_grpc.pb.go b/internal/onboardingservice/v1/service_grpc.pb.go new file mode 100644 index 0000000..0a47aba --- /dev/null +++ b/internal/onboardingservice/v1/service_grpc.pb.go @@ -0,0 +1,129 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.5.1 +// - protoc (unknown) +// source: onboardingservice/v1/service.proto + +// The subset of the Temporal Cloud onboarding service that the CLI calls. The +// package, service, RPC and message names form the gRPC method path on the +// wire, so they must match the server exactly. + +package onboardingservice + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + OnboardingService_GetOrCreateCLIOnboardingState_FullMethodName = "/onboardingservice.v1.OnboardingService/GetOrCreateCLIOnboardingState" +) + +// OnboardingServiceClient is the client API for OnboardingService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type OnboardingServiceClient interface { + // Creates or resumes the caller's onboarding and returns its current state. + // The signup command polls it until onboarding completes. + GetOrCreateCLIOnboardingState(ctx context.Context, in *GetOrCreateCLIOnboardingStateRequest, opts ...grpc.CallOption) (*GetOrCreateCLIOnboardingStateResponse, error) +} + +type onboardingServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewOnboardingServiceClient(cc grpc.ClientConnInterface) OnboardingServiceClient { + return &onboardingServiceClient{cc} +} + +func (c *onboardingServiceClient) GetOrCreateCLIOnboardingState(ctx context.Context, in *GetOrCreateCLIOnboardingStateRequest, opts ...grpc.CallOption) (*GetOrCreateCLIOnboardingStateResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetOrCreateCLIOnboardingStateResponse) + err := c.cc.Invoke(ctx, OnboardingService_GetOrCreateCLIOnboardingState_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// OnboardingServiceServer is the server API for OnboardingService service. +// All implementations must embed UnimplementedOnboardingServiceServer +// for forward compatibility. +type OnboardingServiceServer interface { + // Creates or resumes the caller's onboarding and returns its current state. + // The signup command polls it until onboarding completes. + GetOrCreateCLIOnboardingState(context.Context, *GetOrCreateCLIOnboardingStateRequest) (*GetOrCreateCLIOnboardingStateResponse, error) + mustEmbedUnimplementedOnboardingServiceServer() +} + +// UnimplementedOnboardingServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedOnboardingServiceServer struct{} + +func (UnimplementedOnboardingServiceServer) GetOrCreateCLIOnboardingState(context.Context, *GetOrCreateCLIOnboardingStateRequest) (*GetOrCreateCLIOnboardingStateResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetOrCreateCLIOnboardingState not implemented") +} +func (UnimplementedOnboardingServiceServer) mustEmbedUnimplementedOnboardingServiceServer() {} +func (UnimplementedOnboardingServiceServer) testEmbeddedByValue() {} + +// UnsafeOnboardingServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to OnboardingServiceServer will +// result in compilation errors. +type UnsafeOnboardingServiceServer interface { + mustEmbedUnimplementedOnboardingServiceServer() +} + +func RegisterOnboardingServiceServer(s grpc.ServiceRegistrar, srv OnboardingServiceServer) { + // If the following call pancis, it indicates UnimplementedOnboardingServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&OnboardingService_ServiceDesc, srv) +} + +func _OnboardingService_GetOrCreateCLIOnboardingState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetOrCreateCLIOnboardingStateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OnboardingServiceServer).GetOrCreateCLIOnboardingState(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OnboardingService_GetOrCreateCLIOnboardingState_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OnboardingServiceServer).GetOrCreateCLIOnboardingState(ctx, req.(*GetOrCreateCLIOnboardingStateRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// OnboardingService_ServiceDesc is the grpc.ServiceDesc for OnboardingService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var OnboardingService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "onboardingservice.v1.OnboardingService", + HandlerType: (*OnboardingServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetOrCreateCLIOnboardingState", + Handler: _OnboardingService_GetOrCreateCLIOnboardingState_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "onboardingservice/v1/service.proto", +} diff --git a/proto/onboardingservice/v1/onboarding.proto b/proto/onboardingservice/v1/onboarding.proto new file mode 100644 index 0000000..1badee6 --- /dev/null +++ b/proto/onboardingservice/v1/onboarding.proto @@ -0,0 +1,61 @@ +syntax = "proto3"; + +// The subset of the Temporal Cloud onboarding messages that the CLI uses. Field +// numbers and types must match the server exactly. Fields the CLI doesn't use +// are reserved, and the decoder skips them as unknown fields. +package onboardingservice.v1; + +option go_package = "github.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingservice"; + +enum StepType { + STEP_TYPE_UNSPECIFIED = 0; + STEP_TYPE_CUSTOMER_DETAILS_COLLECTION = 1; + STEP_TYPE_WAIT_FOR_THROTTLE = 2; + STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP = 3; + STEP_TYPE_PAYMENT_COLLECTION = 4; + STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION = 5; + STEP_TYPE_END_OF_FUNNEL = 6; +} + +message OnboardingState { + reserved 2 to 6, 8 to 11; + + // Indicates the current step of the funnel the user is on + StepType current_step = 1; + + string user_email = 7; + + // The Temporal Cloud user id of the user, if available. Empty if the user does not have one yet. + string user_id = 12; +} + +message GetOrCreateCLIOnboardingStateRequest { + // Optional, as is every field in it; the CLI sends whatever its login provides. + CustomerDetails customer_details = 1; +} + +message GetOrCreateCLIOnboardingStateResponse { + bool user_already_exists = 1; + + // Empty if user_already_exists is true. + OnboardingState state = 2; +} + +message CustomerDetails { + reserved 5, 6, 8; + + // The first name of the customer. + string first_name = 1; + + // The last name of the customer. + string last_name = 2; + + // The name of the company the user is from. + string company_name = 3; + + // The country of the user. + string country = 4; + + // Indicates whether the user is interested in receiving marketing emails from Temporal + bool opt_in_marketing_email = 7; +} diff --git a/proto/onboardingservice/v1/service.proto b/proto/onboardingservice/v1/service.proto new file mode 100644 index 0000000..00d34ad --- /dev/null +++ b/proto/onboardingservice/v1/service.proto @@ -0,0 +1,17 @@ +syntax = "proto3"; + +// The subset of the Temporal Cloud onboarding service that the CLI calls. The +// package, service, RPC and message names form the gRPC method path on the +// wire, so they must match the server exactly. +package onboardingservice.v1; + +option go_package = "github.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingservice"; + +import "onboardingservice/v1/onboarding.proto"; + +service OnboardingService { + // Creates or resumes the caller's onboarding and returns its current state. + // The signup command polls it until onboarding completes. + rpc GetOrCreateCLIOnboardingState(GetOrCreateCLIOnboardingStateRequest) returns (GetOrCreateCLIOnboardingStateResponse) { + } +} diff --git a/temporalcloudcli/commands.gen.go b/temporalcloudcli/commands.gen.go index 0c4edd8..127a845 100644 --- a/temporalcloudcli/commands.gen.go +++ b/temporalcloudcli/commands.gen.go @@ -309,6 +309,7 @@ func NewCloudCommand(cctx *CommandContext) *CloudCommand { s.Command.AddCommand(&NewCloudProjectCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudRegionCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudServiceAccountCommand(cctx, &s).Command) + s.Command.AddCommand(&NewCloudSignupCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudUserCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudUserGroupCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudWhoamiCommand(cctx, &s).Command) @@ -6307,6 +6308,56 @@ func NewCloudServiceAccountUpdateCommand(cctx *CommandContext, parent *CloudServ return &s } +type CloudSignupCommand struct { + Parent *CloudCommand + Command cobra.Command + Domain string + Audience string + LoginMethod cliext.FlagStringEnum + ClientId string + RedirectUrl string + OnboardingAddress string + OnboardingInsecure bool + NoWait bool +} + +func NewCloudSignupCommand(cctx *CommandContext, parent *CloudCommand) *CloudSignupCommand { + var s CloudSignupCommand + s.Parent = parent + s.Command.DisableFlagsInUseLine = true + s.Command.Use = "signup [flags]" + s.Command.Short = "Sign up for Temporal Cloud (prototype)" + if hasHighlighting { + s.Command.Long = "Sign up for Temporal Cloud from the terminal.\n\nThis command opens your default browser to authenticate, then starts or\nresumes your Temporal Cloud onboarding. The sign-up credential is kept in\nmemory only and is not written to your profile.\n\nExample:\n\n\x1b[1mtemporal cloud signup\x1b[0m" + } else { + s.Command.Long = "Sign up for Temporal Cloud from the terminal.\n\nThis command opens your default browser to authenticate, then starts or\nresumes your Temporal Cloud onboarding. The sign-up credential is kept in\nmemory only and is not written to your profile.\n\nExample:\n\n```\ntemporal cloud signup\n```" + } + s.Command.Args = cobra.NoArgs + s.Command.Flags().StringVar(&s.Domain, "domain", "login.tmprl.cloud", "Authentication domain for the OAuth provider.") + _ = s.Command.Flags().MarkHidden("domain") + s.Command.Flags().StringVar(&s.Audience, "audience", "https://onboarding.tmprl.cloud", "OAuth audience parameter for the sign-up token.") + _ = s.Command.Flags().MarkHidden("audience") + s.LoginMethod = cliext.NewFlagStringEnum([]string{"google", "microsoft", "password"}, "") + s.Command.Flags().Var(&s.LoginMethod, "login-method", "Login method to use, instead of choosing one interactively. Accepted values: google, microsoft, password.") + s.Command.Flags().StringVar(&s.ClientId, "client-id", "Cd2erICRRO9hzuGeoQyqO9iPfiCgCvMZ", "OAuth client identifier for authentication.") + _ = s.Command.Flags().MarkHidden("client-id") + s.Command.Flags().StringVar(&s.RedirectUrl, "redirect-url", "http://127.0.0.1:56628/callback", "Redirect URL for OAuth authentication flow.") + _ = s.Command.Flags().MarkHidden("redirect-url") + s.Command.Flags().StringVar(&s.OnboardingAddress, "onboarding-address", "onboarding.tmprl.cloud:443", "host:port of the Temporal Cloud onboarding service.") + _ = s.Command.Flags().MarkHidden("onboarding-address") + s.Command.Flags().BoolVar(&s.OnboardingInsecure, "onboarding-insecure", false, "Connect to the onboarding service without TLS. For local development only.") + _ = s.Command.Flags().MarkHidden("onboarding-insecure") + s.Command.Flags().BoolVar(&s.NoWait, "no-wait", false, "Return the current onboarding state without waiting. Prototype only.") + _ = s.Command.Flags().MarkHidden("no-wait") + s.Command.Run = func(c *cobra.Command, args []string) { + if err := s.run(cctx, args); err != nil { + cctx.Options.Fail(err) + } + } + s.initCommand(cctx) + return &s +} + type CloudUserCommand struct { Parent *CloudCommand Command cobra.Command diff --git a/temporalcloudcli/commands.login.go b/temporalcloudcli/commands.login.go index f2a1e26..8918376 100644 --- a/temporalcloudcli/commands.login.go +++ b/temporalcloudcli/commands.login.go @@ -37,7 +37,7 @@ func (c *CloudLoginCommand) run(cctx *CommandContext, _ []string) error { } } - oauthToken, err := Login(cctx, oauthConfig.ClientConfig, oauth2.SetAuthURLParam("audience", c.Audience)) + oauthToken, err := Login(cctx, oauthConfig.ClientConfig, !c.Parent.DisablePopUp, oauth2.SetAuthURLParam("audience", c.Audience)) if err != nil { return fmt.Errorf("failed to login: %w", err) } @@ -73,19 +73,25 @@ func parseURL(s string) (*url.URL, error) { } func (c *CloudLoginCommand) generateOauthClientConfig() (*oauth2.Config, error) { - domainURL, err := parseURL(c.Domain) + return newOAuthClientConfig(c.Domain, c.ClientId, c.RedirectUrl) +} + +// newOAuthClientConfig builds the Auth0 authorization-code (PKCE) client config +// shared by `cloud login` and `cloud signup`. +func newOAuthClientConfig(domain, clientID, redirectURL string) (*oauth2.Config, error) { + domainURL, err := parseURL(domain) if err != nil { return nil, fmt.Errorf("failed to parse domain: %w", err) } return &oauth2.Config{ - ClientID: c.ClientId, + ClientID: clientID, Endpoint: oauth2.Endpoint{ AuthURL: domainURL.JoinPath("authorize").String(), TokenURL: domainURL.JoinPath("oauth", "token").String(), AuthStyle: oauth2.AuthStyleInParams, }, - RedirectURL: c.RedirectUrl, + RedirectURL: redirectURL, Scopes: []string{"openid", "profile", "user", "offline_access"}, }, nil } diff --git a/temporalcloudcli/commands.signup.go b/temporalcloudcli/commands.signup.go new file mode 100644 index 0000000..6861260 --- /dev/null +++ b/temporalcloudcli/commands.signup.go @@ -0,0 +1,213 @@ +package temporalcloudcli + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + + "golang.org/x/oauth2" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" + + "github.com/temporalio/cloud-cli/internal/onboarding" + onboardingservice "github.com/temporalio/cloud-cli/internal/onboardingservice/v1" + "github.com/temporalio/cloud-cli/temporalcloudcli/internal/printer" + cliprompter "github.com/temporalio/cloud-cli/temporalcloudcli/prompter" +) + +// initCommand hides the command from help while it is in development. +func (c *CloudSignupCommand) initCommand(*CommandContext) { + c.Command.Hidden = true +} + +func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { + oauthConfig, err := newOAuthClientConfig(c.Domain, c.ClientId, c.RedirectUrl) + if err != nil { + return fmt.Errorf("failed to generate OAuth client config: %w", err) + } + + connection, err := c.chooseLoginMethod(cctx) + if err != nil { + return err + } + authParams := append([]oauth2.AuthCodeOption{oauth2.SetAuthURLParam("audience", c.Audience)}, c.connectionAuthParams(connection)...) + token, err := c.login(cctx, oauthConfig, authParams) + if err != nil { + return fmt.Errorf("failed to login: %w", err) + } + + conn, err := c.dialOnboarding(oauthConfig.TokenSource(cctx, token)) + if err != nil { + return err + } + defer conn.Close() + + client := onboardingservice.NewOnboardingServiceClient(conn) + req := &onboardingservice.GetOrCreateCLIOnboardingStateRequest{} + var resp *onboardingservice.GetOrCreateCLIOnboardingStateResponse + if c.NoWait { + resp, err = client.GetOrCreateCLIOnboardingState(cctx, req) + if err != nil { + err = fmt.Errorf("failed to get onboarding state: %w", err) + } + } else { + resp, err = onboarding.Wait(cctx, client, req, onboarding.DefaultPollConfig, func(step onboardingservice.StepType) { + // The first poll after the server starts the signup can come back without a step yet. + if !cctx.JSONOutput && step != onboardingservice.StepType_STEP_TYPE_UNSPECIFIED { + cctx.Printer.Printlnf("Waiting for your account (step: %s)...", step) + } + }) + } + if onboarding.RejectionReason(err) == onboarding.ReasonAlreadyOnboarded { + // Not a failure: the user can log in to the account they already have. + if cctx.JSONOutput { + return cctx.Printer.PrintStructured( + &onboardingservice.GetOrCreateCLIOnboardingStateResponse{UserAlreadyExists: true}, + printer.StructuredOptions{}, + ) + } + cctx.Printer.Println("You already have a Temporal Cloud account. Run `temporal cloud login` to sign in.") + return nil + } + if err != nil { + return signupRejectionError(err) + } + + if cctx.JSONOutput { + return cctx.Printer.PrintStructured(resp, printer.StructuredOptions{}) + } + // The server reports a finished signup as user_already_exists; a user who had an account before is + // refused with ALREADY_ONBOARDED instead. + if onboarding.IsComplete(resp) { + cctx.Printer.Println("Your Temporal Cloud account is ready. Run `temporal cloud login` to sign in.") + } else { + cctx.Printer.Printlnf("Onboarding step: %s", resp.GetState().GetCurrentStep()) + } + return nil +} + +// login runs the browser login. Auth0 denies a new email + password user until +// they verify their email; signup is safe to rerun, so it asks them to do that. +func (c *CloudSignupCommand) login(cctx *CommandContext, config *oauth2.Config, authParams []oauth2.AuthCodeOption) (*oauth2.Token, error) { + token, err := Login(cctx, config, !c.Parent.DisablePopUp, authParams...) + var authErr *AuthorizationError + if errors.As(err, &authErr) && authErr.IsEmailNotVerified() { + return nil, errors.New("verify your email using the link we sent you, then run `temporal cloud signup` again") + } + return token, err +} + +// signupRejectionMessages are what the user should do when the onboarding +// service refuses the signup for a known reason. +var signupRejectionMessages = map[string]string{ + onboarding.ReasonTrialSignupUnavailable: "sign-up from the CLI isn't available right now; try again later", + onboarding.ReasonBrowserSignupInProgress: "you have a sign-up in progress in the browser; finish it there, then run `temporal cloud login`", + onboarding.ReasonTrialSignupCancelled: "your sign-up was cancelled; contact Temporal support", +} + +// signupRejectionError replaces a known signup refusal with a message saying +// what to do, and returns any other error unchanged. +func signupRejectionError(err error) error { + if msg, ok := signupRejectionMessages[onboarding.RejectionReason(err)]; ok { + return NewFriendlyError(msg, err) + } + return err +} + +var loginMethods = []struct { + value string + label string +}{ + {value: "google", label: "Google"}, + {value: "microsoft", label: "Microsoft"}, + {value: "password", label: "Email + Password"}, +} + +// chooseLoginMethod returns --login-method if set. Otherwise, in an interactive +// terminal, it asks with an arrow-key menu. In any other case (scripts, agents, +// JSON output) it returns "" and Auth0 shows its own provider picker. +func (c *CloudSignupCommand) chooseLoginMethod(cctx *CommandContext) (string, error) { + if c.LoginMethod.Value != "" { + return c.LoginMethod.Value, nil + } + if cctx.JSONOutput || !cliprompter.IsTerminal(cctx.Options.Stdin, cctx.Options.Stdout) { + // Stderr, so JSON on stdout stays parseable and agents still see the hint. + fmt.Fprintln(cctx.Options.Stderr, + "No --login-method set: choose one in the browser, or pass --login-method google|microsoft|password.") + return "", nil + } + labels := make([]string, len(loginMethods)) + for i, conn := range loginMethods { + labels[i] = conn.label + } + i, err := cliprompter.SelectInTerminal(cctx.Options.Stdin, cctx.Options.Stdout, "Sign up with:", labels) + if err != nil { + return "", err + } + return loginMethods[i].value, nil +} + +// connectionAuthParams maps a connection value to Auth0 authorize parameters, +// the same way the /get-cloud sign-up buttons do. +func (c *CloudSignupCommand) connectionAuthParams(connection string) []oauth2.AuthCodeOption { + switch connection { + case "google": + return []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("connection", "google-oauth2")} + case "microsoft": + // The Microsoft connection is named differently per tenant + // (microsoft-v2 in prod, microsoft elsewhere), mirroring the website. + name := "microsoft" + if c.Domain == "login.tmprl.cloud" { + name = "microsoft-v2" + } + return []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("connection", name)} + case "password": + return []oauth2.AuthCodeOption{ + oauth2.SetAuthURLParam("connection", "Username-Password-Authentication"), + oauth2.SetAuthURLParam("screen_hint", "signup"), + } + default: + return nil + } +} + +func (c *CloudSignupCommand) dialOnboarding(tokenSource oauth2.TokenSource) (*grpc.ClientConn, error) { + transport := credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12}) + if c.OnboardingInsecure { + transport = insecure.NewCredentials() + } + conn, err := grpc.NewClient( + c.OnboardingAddress, + grpc.WithTransportCredentials(transport), + grpc.WithPerRPCCredentials(bearerTokenCredentials{ + tokenSource: tokenSource, + requireSecure: !c.OnboardingInsecure, + }), + ) + if err != nil { + return nil, fmt.Errorf("failed to connect to onboarding service: %w", err) + } + return conn, nil +} + +// bearerTokenCredentials attaches an OAuth access token to each RPC. Unlike +// grpc/credentials/oauth.TokenSource, it can be used without TLS so the +// command can reach a local onboarding service. +type bearerTokenCredentials struct { + tokenSource oauth2.TokenSource + requireSecure bool +} + +func (b bearerTokenCredentials) GetRequestMetadata(context.Context, ...string) (map[string]string, error) { + token, err := b.tokenSource.Token() + if err != nil { + return nil, fmt.Errorf("failed to get access token: %w", err) + } + return map[string]string{"authorization": "Bearer " + token.AccessToken}, nil +} + +func (b bearerTokenCredentials) RequireTransportSecurity() bool { + return b.requireSecure +} diff --git a/temporalcloudcli/commands.yml b/temporalcloudcli/commands.yml index 63e821b..d4f31fb 100644 --- a/temporalcloudcli/commands.yml +++ b/temporalcloudcli/commands.yml @@ -137,6 +137,75 @@ commands: Authentication domain for the OAuth provider. default: login.tmprl.cloud + - name: cloud signup + summary: Sign up for Temporal Cloud (prototype) + description: | + Sign up for Temporal Cloud from the terminal. + + This command opens your default browser to authenticate, then starts or + resumes your Temporal Cloud onboarding. The sign-up credential is kept in + memory only and is not written to your profile. + + Example: + + ``` + temporal cloud signup + ``` + has-init: true + docs: + keywords: + - signup + - onboarding + description-header: Sign up + tags: + - login + options: + - name: domain + type: string + hidden: true + description: | + Authentication domain for the OAuth provider. + default: login.tmprl.cloud + - name: audience + type: string + hidden: true + default: https://onboarding.tmprl.cloud + description: | + OAuth audience parameter for the sign-up token. + - name: login-method + type: string-enum + enum-values: [google, microsoft, password] + description: | + Login method to use, instead of choosing one interactively. + - name: client-id + type: string + hidden: true + default: Cd2erICRRO9hzuGeoQyqO9iPfiCgCvMZ + description: | + OAuth client identifier for authentication. + - name: redirect-url + type: string + hidden: true + default: http://127.0.0.1:56628/callback + description: | + Redirect URL for OAuth authentication flow. + - name: onboarding-address + type: string + hidden: true + default: onboarding.tmprl.cloud:443 + description: | + host:port of the Temporal Cloud onboarding service. + - name: onboarding-insecure + type: bool + hidden: true + description: | + Connect to the onboarding service without TLS. For local development only. + - name: no-wait + type: bool + hidden: true + description: | + Return the current onboarding state without waiting. Prototype only. + # Namespace commands - name: cloud namespace summary: Manage Temporal Cloud namespaces diff --git a/temporalcloudcli/oauth.go b/temporalcloudcli/oauth.go index f3b3b6a..d5934f4 100644 --- a/temporalcloudcli/oauth.go +++ b/temporalcloudcli/oauth.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "net/url" + "os" "sync" "time" @@ -20,7 +21,9 @@ type oauthCallbackResult struct { err error } -func Login(ctx context.Context, config *oauth2.Config, options ...oauth2.AuthCodeOption) (*oauth2.Token, error) { +// Login runs the browser-based authorization-code (PKCE) flow. When +// openBrowser is false, it only prints the URL for the user to open. +func Login(ctx context.Context, config *oauth2.Config, openBrowser bool, options ...oauth2.AuthCodeOption) (*oauth2.Token, error) { // Generate PKCE challenge. verifier := oauth2.GenerateVerifier() options = append(options, oauth2.S256ChallengeOption(verifier)) @@ -33,8 +36,14 @@ func Login(ctx context.Context, config *oauth2.Config, options ...oauth2.AuthCod state := base64.RawURLEncoding.EncodeToString(stateBytes[:]) authURL := config.AuthCodeURL(state, options...) - fmt.Printf("Opening browser to authorize. If it doesn't open, visit: %s\n", authURL) - _ = browser.OpenURL(authURL) + // Prompts go to stderr so stdout carries only command output (e.g. -o json). + if openBrowser { + fmt.Fprintf(os.Stderr, "Opening browser to authorize. If it doesn't open, visit: %s\n", authURL) + browser.Stdout = os.Stderr + _ = browser.OpenURL(authURL) + } else { + fmt.Fprintf(os.Stderr, "Open this URL in a browser to authorize: %s\n", authURL) + } // Parse redirect URL to get host and path url, err := url.Parse(config.RedirectURL) @@ -61,12 +70,13 @@ func Login(ctx context.Context, config *oauth2.Config, options ...oauth2.AuthCod // Check for OAuth error response. if errCode := query.Get("error"); errCode != "" { - errDesc := query.Get("error_description") - if errDesc == "" { - errDesc = errCode + authErr := &AuthorizationError{Code: errCode, Description: query.Get("error_description")} + resultCh <- oauthCallbackResult{err: authErr} + if authErr.IsEmailNotVerified() { + http.Error(w, "Check your email for a verification link, then return to your terminal.", http.StatusForbidden) + return } - resultCh <- oauthCallbackResult{err: fmt.Errorf("authorization failed: %s", errDesc)} - http.Error(w, fmt.Sprintf("Authorization failed: %s", errDesc), http.StatusBadRequest) + http.Error(w, "Authorization failed: "+authErr.reason(), http.StatusBadRequest) return } @@ -124,6 +134,32 @@ func Login(ctx context.Context, config *oauth2.Config, options ...oauth2.AuthCod return token, nil } +// AuthorizationError is an OAuth error returned to the callback, such as a +// login denied by an Auth0 action. +type AuthorizationError struct { + Code string + Description string +} + +func (e *AuthorizationError) Error() string { + return "authorization failed: " + e.reason() +} + +func (e *AuthorizationError) reason() string { + if e.Description != "" { + return e.Description + } + return e.Code +} + +// IsEmailNotVerified reports whether the login was denied because the user's +// email address is not verified yet. +// AIDEV-NOTE: the post-login email-verify action denies password logins with +// api.access.deny('verify_email'); the website checks for the same value. +func (e *AuthorizationError) IsEmailNotVerified() bool { + return e.Code == "access_denied" && e.Description == "verify_email" +} + var ErrLoginRequired = errors.New("login required") func GetToken(ctx context.Context, config *oauth2.Config, token *oauth2.Token) (*oauth2.Token, bool, error) { diff --git a/temporalcloudcli/prompter/select.go b/temporalcloudcli/prompter/select.go new file mode 100644 index 0000000..23a2b75 --- /dev/null +++ b/temporalcloudcli/prompter/select.go @@ -0,0 +1,174 @@ +package prompter + +import ( + "bufio" + "errors" + "fmt" + "io" + + "golang.org/x/term" +) + +// ErrSelectCanceled is returned when the user cancels a selection (Ctrl-C, Ctrl-D or q). +var ErrSelectCanceled = errors.New("selection canceled") + +// Input bytes. Raw mode delivers keys as bytes instead of acting on them. +const ( + keyCtrlC = '\x03' + keyCtrlD = '\x04' + keyEsc = '\x1b' + + // Arrow keys arrive as ESC, a prefix, then a direction: ESC [ A, or ESC O A + // when the terminal is in application cursor mode. + arrowPrefixCSI = '[' + arrowPrefixSS3 = 'O' + arrowUp = 'A' + arrowDown = 'B' +) + +// Output escape sequences (ANSI/VT100). +const ( + hideCursor = "\x1b[?25l" + showCursor = "\x1b[?25h" + cursorUp = "\x1b[1A" // move the cursor up one line + clearLine = "\x1b[2K" // erase the line the cursor is on + // Raw mode disables output post-processing, so lines must end in \r\n. + newline = "\r\n" +) + +// fdFile is satisfied by *os.File, the only kind of stream that can be a terminal. +type fdFile interface { + Fd() uintptr +} + +// IsTerminal reports whether in and out are both interactive terminals, so an +// arrow-key prompt can be shown. +func IsTerminal(in io.Reader, out io.Writer) bool { + return isTerminal(in) && isTerminal(out) +} + +func isTerminal(stream any) bool { + f, ok := stream.(fdFile) + return ok && term.IsTerminal(int(f.Fd())) +} + +// SelectInTerminal puts in into raw mode, shows an arrow-key menu on out and +// returns the index of the chosen option. The caller must check IsTerminal +// first. +func SelectInTerminal(in io.Reader, out io.Writer, message string, options []string) (int, error) { + f, ok := in.(fdFile) + if !ok { + return 0, errors.New("input is not a terminal") + } + fd := int(f.Fd()) + oldState, err := term.MakeRaw(fd) + if err != nil { + return 0, fmt.Errorf("failed to read from terminal: %w", err) + } + defer func() { _ = term.Restore(fd, oldState) }() + + return Select(in, out, message, options) +} + +// Select runs an arrow-key menu over in and out, which must already be in raw +// mode. Up/Down (or k/j) move, Enter chooses, and Ctrl-C, Ctrl-D or q cancel. +// It returns the index of the chosen option. +func Select(in io.Reader, out io.Writer, message string, options []string) (int, error) { + if len(options) == 0 { + return 0, errors.New("no options to select from") + } + + r := bufio.NewReader(in) + selected := 0 + + fmt.Fprint(out, hideCursor, message, newline) + defer fmt.Fprint(out, showCursor) + drawOptions(out, options, selected) + + for { + key, err := readKey(r) + if err != nil { + return 0, err + } + switch key { + case keyUp: + selected = (selected - 1 + len(options)) % len(options) + case keyDown: + selected = (selected + 1) % len(options) + case keyEnter: + clearOptions(out, len(options)) + fmt.Fprint(out, cursorUp, clearLine, message, " ", options[selected], newline) + return selected, nil + case keyCancel: + clearOptions(out, len(options)) + return 0, ErrSelectCanceled + default: + continue + } + clearOptions(out, len(options)) + drawOptions(out, options, selected) + } +} + +type key int + +const ( + keyOther key = iota + keyUp + keyDown + keyEnter + keyCancel +) + +func readKey(r *bufio.Reader) (key, error) { + b, err := r.ReadByte() + if errors.Is(err, io.EOF) { + return keyCancel, nil + } + if err != nil { + return keyOther, fmt.Errorf("failed to read from terminal: %w", err) + } + switch b { + case '\r', '\n': + return keyEnter, nil + case keyCtrlC, keyCtrlD, 'q': + return keyCancel, nil + case 'k': + return keyUp, nil + case 'j': + return keyDown, nil + case keyEsc: + prefix, err := r.ReadByte() + if err != nil || (prefix != arrowPrefixCSI && prefix != arrowPrefixSS3) { + return keyOther, nil + } + code, err := r.ReadByte() + if err != nil { + return keyOther, nil + } + switch code { + case arrowUp: + return keyUp, nil + case arrowDown: + return keyDown, nil + } + } + return keyOther, nil +} + +func drawOptions(out io.Writer, options []string, selected int) { + for i, opt := range options { + marker := " " + if i == selected { + marker = "> " + } + fmt.Fprint(out, marker, opt, newline) + } +} + +// clearOptions moves the cursor back over the drawn options and erases them. +func clearOptions(out io.Writer, n int) { + for range n { + fmt.Fprint(out, cursorUp, clearLine) + } +} diff --git a/temporalcloudcli/prompter/select_test.go b/temporalcloudcli/prompter/select_test.go new file mode 100644 index 0000000..1e7d4cf --- /dev/null +++ b/temporalcloudcli/prompter/select_test.go @@ -0,0 +1,66 @@ +package prompter_test + +import ( + "bytes" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/temporalio/cloud-cli/temporalcloudcli/prompter" +) + +func TestSelect(t *testing.T) { + options := []string{"Google", "Microsoft", "Email + Password"} + + tests := []struct { + name string + input string + expectedIndex int + expectedErr error + }{ + {name: "enter picks the first option", input: "\r", expectedIndex: 0}, + {name: "down arrow", input: "\x1b[B\r", expectedIndex: 1}, + {name: "application mode down arrow", input: "\x1bOB\r", expectedIndex: 1}, + {name: "down twice", input: "\x1b[B\x1b[B\r", expectedIndex: 2}, + {name: "down wraps to the top", input: "\x1b[B\x1b[B\x1b[B\r", expectedIndex: 0}, + {name: "up wraps to the bottom", input: "\x1b[A\r", expectedIndex: 2}, + {name: "j and k", input: "jjk\r", expectedIndex: 1}, + {name: "other keys are ignored", input: "x\x1b[C\n", expectedIndex: 0}, + {name: "ctrl-c cancels", input: "\x1b[B\x03", expectedErr: prompter.ErrSelectCanceled}, + {name: "q cancels", input: "q", expectedErr: prompter.ErrSelectCanceled}, + {name: "eof cancels", input: "\x1b[B", expectedErr: prompter.ErrSelectCanceled}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var out bytes.Buffer + + index, err := prompter.Select(strings.NewReader(tt.input), &out, "Sign up with:", options) + + if tt.expectedErr != nil { + require.ErrorIs(t, err, tt.expectedErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.expectedIndex, index) + assert.Contains(t, out.String(), "Sign up with: "+options[tt.expectedIndex]) + }) + } +} + +func TestSelect_NoOptions(t *testing.T) { + _, err := prompter.Select(strings.NewReader("\r"), &bytes.Buffer{}, "Pick:", nil) + + require.EqualError(t, err, "no options to select from") +} + +func TestIsTerminal_NonFileStreams(t *testing.T) { + assert.False(t, prompter.IsTerminal(strings.NewReader(""), &bytes.Buffer{})) +} + +func TestSelectInTerminal_NonFileInput(t *testing.T) { + _, err := prompter.SelectInTerminal(strings.NewReader(""), &bytes.Buffer{}, "Pick:", []string{"a"}) + require.Error(t, err) +}