Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(action): simplify internal client construction (#19800)

p0nyd764861e84e3
diff --git a/.sonarcloud.properties b/.sonarcloud.properties
index c8aa56d375..eab3febdb1 100644
--- a/.sonarcloud.properties
+++ b/.sonarcloud.properties
@@ -12,6 +12,7 @@ sonar.exclusions=\
# Path to tests — identify test files so they are analyzed as tests, not source
sonar.test.inclusions=\
+ action/**/*_test.go,\
backend/**/*_test.go,\
backend/**/testdata/**,\
backend/**/test-data/**,\
@@ -63,6 +64,7 @@ sonar.issue.ignore.multicriteria.fp_role_sql.resourceKey=backend/plugin/db/*/rol
# Exclusions for copy-paste detection
sonar.cpd.exclusions=\
+ action/**/*_test.go,\
backend/**/*_test.go,\
backend/**/testdata/**,\
backend/**/test-data/**,\
diff --git a/action/command/api.go b/action/command/api.go
index 57bc5afd2a..d03eb02dee 100644
--- a/action/command/api.go
+++ b/action/command/api.go
@@ -16,43 +16,43 @@ import (
"github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"
)
-// RetryConfig configures retry behavior
-type RetryConfig struct {
- // MaxAttempts is the maximum number of retry attempts
- MaxAttempts int
- // InitialInterval is the initial retry interval
- InitialInterval time.Duration
- // MaxInterval is the maximum retry interval
- MaxInterval time.Duration
-}
-
-// ClientOptions configures the Client behavior
-type ClientOptions struct {
- // PageSize controls the number of items per page in list operations
- PageSize int32
- // HTTPClient allows providing a custom HTTP client
- HTTPClient *http.Client
- // Timeout for RPC calls (applies only if HTTPClient is not provided)
- Timeout time.Duration
- // RetryConfig configures retry behavior for transient errors
- RetryConfig *RetryConfig
+// retryConfig controls retry behavior for transient errors.
+type retryConfig struct {
+ // maxAttempts is the maximum number of retry attempts.
+ maxAttempts int
+ // initialInterval is the initial retry interval.
+ initialInterval time.Duration
+ // maxInterval is the maximum retry interval.
+ maxInterval time.Duration
}
-// DefaultClientOptions returns the default client options
-func DefaultClientOptions() ClientOptions {
- return ClientOptions{
- PageSize: 100,
- Timeout: 120 * time.Second,
- RetryConfig: &RetryConfig{
- MaxAttempts: 3,
- InitialInterval: 1 * time.Second,
- MaxInterval: 30 * time.Second,
+// clientOptions configures client behavior.
+type clientOptions struct {
+ // pageSize controls the number of items per page in list operations.
+ pageSize int32
+ // httpClient allows providing a custom HTTP client.
+ httpClient *http.Client
+ // timeout applies only if httpClient is not provided.
+ timeout time.Duration
+ // retryConfig controls retry behavior for transient errors.
+ retryConfig *retryConfig
+}
+
+// defaultClientOptions returns the default client options.
+func defaultClientOptions() clientOptions {
+ return clientOptions{
+ pageSize: 100,
+ timeout: 120 * time.Second,
+ retryConfig: &retryConfig{
+ maxAttempts: 3,
+ initialInterval: 1 * time.Second,
+ maxInterval: 30 * time.Second,
},
}
}
-// Client is the API message for Bytebase API Client.
-type Client struct {
+// client is the Bytebase API client used inside the action command package.
+type client struct {
// HTTP client for Connect RPC
httpClient *http.Client
@@ -70,36 +70,21 @@ type Client struct {
actuatorClient v1connect.ActuatorServiceClient
// Client options
- options ClientOptions
-}
-
-// NewClient returns the new Bytebase API client with default options using service account auth.
-func NewClient(url, serviceAccount, serviceAccountSecret string) (*Client, error) {
- return NewClientWithOptions(url, serviceAccount, serviceAccountSecret, DefaultClientOptions())
-}
-
-// NewClientWithAccessToken returns a new Bytebase API client using a pre-obtained access token.
-func NewClientWithAccessToken(url, accessToken string) (*Client, error) {
- return createClient(url, accessToken, "", "", DefaultClientOptions())
-}
-
-// NewClientWithOptions returns a new Bytebase API client with custom options using service account auth.
-func NewClientWithOptions(url, serviceAccount, serviceAccountSecret string, opts ClientOptions) (*Client, error) {
- return createClient(url, "", serviceAccount, serviceAccountSecret, opts)
+ options clientOptions
}
-func createClient(url, accessToken, serviceAccount, serviceAccountSecret string, opts ClientOptions) (*Client, error) {
- if opts.PageSize <= 0 {
- opts.PageSize = 100
+// newClient creates a client using either access-token or service-account authentication.
+func newClient(url, accessToken, serviceAccount, serviceAccountSecret string, opts clientOptions) (*client, error) {
+ if opts.pageSize <= 0 {
+ opts.pageSize = 100
}
- if opts.PageSize > 1000 {
- opts.PageSize = 1000
+ if opts.pageSize > 1000 {
+ opts.pageSize = 1000
}
- // Use provided HTTP client or create a new one
- httpClient := opts.HTTPClient
+ httpClient := opts.httpClient
if httpClient == nil {
- timeout := opts.Timeout
+ timeout := opts.timeout
if timeout == 0 {
timeout = 120 * time.Second
}
@@ -116,11 +101,11 @@ func createClient(url, accessToken, serviceAccount, serviceAccountSecret string,
tokenRefresher = getTokenRefresher(httpClient, serviceAccount, serviceAccountSecret, url)
}
- // Create unified interceptor
- unifiedInt := newUnifiedInterceptor(opts.RetryConfig, tokenRefresher)
+ // Create unified interceptor.
+ unifiedInt := newUnifiedInterceptor(opts.retryConfig, tokenRefresher)
interceptors := connect.WithInterceptors(unifiedInt)
- return &Client{
+ return &client{
httpClient: httpClient,
url: url,
serviceAccount: serviceAccount,
@@ -151,7 +136,7 @@ func getTokenRefresher(httpClient connect.HTTPClient, email, password, url strin
}
}
-func (c *Client) CheckRelease(ctx context.Context, r *v1pb.CheckReleaseRequest) (*v1pb.CheckReleaseResponse, error) {
+func (c *client) checkRelease(ctx context.Context, r *v1pb.CheckReleaseRequest) (*v1pb.CheckReleaseResponse, error) {
resp, err := c.releaseClient.CheckRelease(ctx, connect.NewRequest(r))
if err != nil {
return nil, errors.Wrapf(err, "failed to check release")
@@ -159,7 +144,7 @@ func (c *Client) CheckRelease(ctx context.Context, r *v1pb.CheckReleaseRequest)
return resp.Msg, nil
}
-func (c *Client) CreateRelease(ctx context.Context, project string, r *v1pb.Release, releaseIDTemplate, releaseIDTimezone string) (*v1pb.Release, error) {
+func (c *client) createRelease(ctx context.Context, project string, r *v1pb.Release, releaseIDTemplate, releaseIDTimezone string) (*v1pb.Release, error) {
req := connect.NewRequest(&v1pb.CreateReleaseRequest{
Parent: project,
Release: r,
@@ -173,7 +158,7 @@ func (c *Client) CreateRelease(ctx context.Context, project string, r *v1pb.Rele
return resp.Msg, nil
}
-func (c *Client) GetPlan(ctx context.Context, planName string) (*v1pb.Plan, error) {
+func (c *client) getPlan(ctx context.Context, planName string) (*v1pb.Plan, error) {
resp, err := c.planClient.GetPlan(ctx,
connect.NewRequest(&v1pb.GetPlanRequest{
Name: planName,
@@ -184,7 +169,7 @@ func (c *Client) GetPlan(ctx context.Context, planName string) (*v1pb.Plan, erro
return resp.Msg, nil
}
-func (c *Client) CreatePlan(ctx context.Context, project string, r *v1pb.Plan) (*v1pb.Plan, error) {
+func (c *client) createPlan(ctx context.Context, project string, r *v1pb.Plan) (*v1pb.Plan, error) {
req := connect.NewRequest(&v1pb.CreatePlanRequest{
Parent: project,
Plan: r,
@@ -196,7 +181,7 @@ func (c *Client) CreatePlan(ctx context.Context, project string, r *v1pb.Plan) (
return resp.Msg, nil
}
-func (c *Client) GetRollout(ctx context.Context, rolloutName string) (*v1pb.Rollout, error) {
+func (c *client) getRollout(ctx context.Context, rolloutName string) (*v1pb.Rollout, error) {
resp, err := c.rolloutClient.GetRollout(ctx,
connect.NewRequest(&v1pb.GetRolloutRequest{
Name: rolloutName,
@@ -207,7 +192,7 @@ func (c *Client) GetRollout(ctx context.Context, rolloutName string) (*v1pb.Roll
return resp.Msg, nil
}
-func (c *Client) CreateRollout(ctx context.Context, r *v1pb.CreateRolloutRequest) (*v1pb.Rollout, error) {
+func (c *client) createRollout(ctx context.Context, r *v1pb.CreateRolloutRequest) (*v1pb.Rollout, error) {
resp, err := c.rolloutClient.CreateRollout(ctx, connect.NewRequest(r))
if err != nil {
return nil, errors.Wrapf(err, "failed to create rollout")
@@ -215,7 +200,7 @@ func (c *Client) CreateRollout(ctx context.Context, r *v1pb.CreateRolloutRequest
return resp.Msg, nil
}
-func (c *Client) BatchRunTasks(ctx context.Context, r *v1pb.BatchRunTasksRequest) (*v1pb.BatchRunTasksResponse, error) {
+func (c *client) batchRunTasks(ctx context.Context, r *v1pb.BatchRunTasksRequest) (*v1pb.BatchRunTasksResponse, error) {
resp, err := c.rolloutClient.BatchRunTasks(ctx, connect.NewRequest(r))
if err != nil {
return nil, errors.Wrapf(err, "failed to batch run tasks")
@@ -223,7 +208,7 @@ func (c *Client) BatchRunTasks(ctx context.Context, r *v1pb.BatchRunTasksRequest
return resp.Msg, nil
}
-func (c *Client) ListTaskRuns(ctx context.Context, r *v1pb.ListTaskRunsRequest) (*v1pb.ListTaskRunsResponse, error) {
+func (c *client) listTaskRuns(ctx context.Context, r *v1pb.ListTaskRunsRequest) (*v1pb.ListTaskRunsResponse, error) {
resp, err := c.rolloutClient.ListTaskRuns(ctx, connect.NewRequest(r))
if err != nil {
return nil, errors.Wrapf(err, "failed to list task runs")
@@ -231,13 +216,13 @@ func (c *Client) ListTaskRuns(ctx context.Context, r *v1pb.ListTaskRunsRequest)
return resp.Msg, nil
}
-func (c *Client) ListAllTaskRuns(ctx context.Context, rolloutName string) (*v1pb.ListTaskRunsResponse, error) {
- return c.ListTaskRuns(ctx, &v1pb.ListTaskRunsRequest{
+func (c *client) listAllTaskRuns(ctx context.Context, rolloutName string) (*v1pb.ListTaskRunsResponse, error) {
+ return c.listTaskRuns(ctx, &v1pb.ListTaskRunsRequest{
Parent: rolloutName + "/stages/-/tasks/-",
})
}
-func (c *Client) BatchCancelTaskRuns(ctx context.Context, r *v1pb.BatchCancelTaskRunsRequest) (*v1pb.BatchCancelTaskRunsResponse, error) {
+func (c *client) batchCancelTaskRuns(ctx context.Context, r *v1pb.BatchCancelTaskRunsRequest) (*v1pb.BatchCancelTaskRunsResponse, error) {
resp, err := c.rolloutClient.BatchCancelTaskRuns(ctx, connect.NewRequest(r))
if err != nil {
return nil, errors.Wrapf(err, "failed to batch cancel task runs")
@@ -245,7 +230,7 @@ func (c *Client) BatchCancelTaskRuns(ctx context.Context, r *v1pb.BatchCancelTas
return resp.Msg, nil
}
-func (c *Client) GetActuatorInfo(ctx context.Context) (*v1pb.ActuatorInfo, error) {
+func (c *client) getActuatorInfo(ctx context.Context) (*v1pb.ActuatorInfo, error) {
resp, err := c.actuatorClient.GetActuatorInfo(ctx,
connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))
if err != nil {
@@ -254,12 +239,10 @@ func (c *Client) GetActuatorInfo(ctx context.Context) (*v1pb.ActuatorInfo, error
return resp.Msg, nil
}
-// Close cleans up resources used by the Client
-func (c *Client) Close() error {
+func (c *client) close() {
if c.httpClient != nil {
c.httpClient.CloseIdleConnections()
}
- return nil
}
// isRetryableError determines if an error should trigger a retry
@@ -313,16 +296,16 @@ type unifiedInterceptor struct {
refreshGroup singleflight.Group
}
-func newUnifiedInterceptor(config *RetryConfig, tokenRefresher func(ctx context.Context) (string, error)) *unifiedInterceptor {
+func newUnifiedInterceptor(config *retryConfig, tokenRefresher func(ctx context.Context) (string, error)) *unifiedInterceptor {
ui := &unifiedInterceptor{
tokenMgr: newTokenManager(),
tokenRefresher: tokenRefresher,
}
- if config != nil && config.MaxAttempts > 1 {
- ui.maxAttempts = config.MaxAttempts
- ui.initialInterval = config.InitialInterval
- ui.maxInterval = config.MaxInterval
+ if config != nil && config.maxAttempts > 1 {
+ ui.maxAttempts = config.maxAttempts
+ ui.initialInterval = config.initialInterval
+ ui.maxInterval = config.maxInterval
} else {
// Default retry config for auth errors
ui.maxAttempts = 2
diff --git a/action/command/api_test.go b/action/command/api_test.go
new file mode 100644
index 0000000000..6eba2dfd49
--- /dev/null
+++ b/action/command/api_test.go
@@ -0,0 +1,63 @@
+package command
+
+import (
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/action/world"
+)
+
+func TestNewClientWithOptionsUsesServiceAccountAuth(t *testing.T) {
+ t.Parallel()
+
+ httpClient := &http.Client{}
+ client, err := newClient("https://example.com", "", "[email protected]", "secret", clientOptions{
+ httpClient: httpClient,
+ pageSize: -1,
+ })
+ require.NoError(t, err)
+
+ t.Cleanup(client.close)
+
+ require.Same(t, httpClient, client.httpClient)
+ require.Equal(t, int32(100), client.options.pageSize)
+ require.Equal(t, "[email protected]", client.serviceAccount)
+ require.Equal(t, "secret", client.serviceAccountSecret)
+}
+
+func TestNewClientWithAccessTokenUsesAccessTokenAuth(t *testing.T) {
+ t.Parallel()
+
+ client, err := newClient("https://example.com", "token", "", "", defaultClientOptions())
+ require.NoError(t, err)
+
+ t.Cleanup(client.close)
+
+ require.Equal(t, "", client.serviceAccount)
+ require.Equal(t, "", client.serviceAccountSecret)
+ require.Equal(t, 120*time.Second, client.httpClient.Timeout)
+}
+
+func TestNewClientFromWorldPrefersAccessToken(t *testing.T) {
+ t.Parallel()
+
+ w := &world.World{
+ URL: "https://example.com",
+ Timeout: 5 * time.Second,
+ AccessToken: "token",
+ ServiceAccount: "[email protected]",
+ ServiceAccountSecret: "secret",
+ }
+
+ client, err := newClientFromWorld(w)
+ require.NoError(t, err)
+
+ t.Cleanup(client.close)
+
+ require.Equal(t, 5*time.Second, client.httpClient.Timeout)
+ require.Equal(t, "", client.serviceAccount)
+ require.Equal(t, "", client.serviceAccountSecret)
+}
diff --git a/action/command/check.go b/action/command/check.go
index f047dabe62..94fc619429 100644
--- a/action/command/check.go
+++ b/action/command/check.go
@@ -53,14 +53,14 @@ func runCheck(w *world.World) func(*cobra.Command, []string) error {
}()
platform := w.Platform
w.Logger.Info("running on platform", "platform", platform.String())
- client, err := NewClientFromWorld(w)
+ client, err := newClientFromWorld(w)
if err != nil {
return err
}
- defer client.Close()
+ defer client.close()
// Check version compatibility
- CheckVersionCompatibility(w, client, args.Version)
+ checkVersionCompatibility(w, client, args.Version)
releaseFiles, err := getReleaseFiles(w)
if err != nil {
@@ -70,7 +70,7 @@ func runCheck(w *world.World) func(*cobra.Command, []string) error {
if w.Declarative {
releaseType = v1pb.Release_DECLARATIVE
}
- checkReleaseResponse, err := client.CheckRelease(cmd.Context(), &v1pb.CheckReleaseRequest{
+ checkReleaseResponse, err := client.checkRelease(cmd.Context(), &v1pb.CheckReleaseRequest{
Parent: w.Project,
Release: &v1pb.Release{
Files: releaseFiles,
diff --git a/action/command/rollout.go b/action/command/rollout.go
index fbea41d60a..dd973ae024 100644
--- a/action/command/rollout.go
+++ b/action/command/rollout.go
@@ -55,18 +55,18 @@ func runRollout(w *world.World) func(command *cobra.Command, _ []string) error {
}()
w.IsRollout = true
ctx := command.Context()
- client, err := NewClientFromWorld(w)
+ client, err := newClientFromWorld(w)
if err != nil {
return errors.Wrapf(err, "failed to create client")
}
- defer client.Close()
+ defer client.close()
// Check version compatibility
- CheckVersionCompatibility(w, client, args.Version)
+ checkVersionCompatibility(w, client, args.Version)
var plan *v1pb.Plan
if w.Plan != "" {
- planP, err := client.GetPlan(ctx, w.Plan)
+ planP, err := client.getPlan(ctx, w.Plan)
if err != nil {
return errors.Wrapf(err, "failed to get plan")
}
@@ -82,7 +82,7 @@ func runRollout(w *world.World) func(command *cobra.Command, _ []string) error {
if w.Declarative {
releaseType = v1pb.Release_DECLARATIVE
}
- createReleaseResponse, err := client.CreateRelease(ctx, w.Project, &v1pb.Release{
+ createReleaseResponse, err := client.createRelease(ctx, w.Project, &v1pb.Release{
Files: releaseFiles,
VcsSource: getVCSSource(w),
Type: releaseType,
@@ -97,7 +97,7 @@ func runRollout(w *world.World) func(command *cobra.Command, _ []string) error {
// Extract release ID from release name (format: projects/{project}/releases/{release_id})
releaseID := strings.TrimPrefix(release, w.Project+"/releases/")
- planCreated, err := client.CreatePlan(ctx, w.Project, &v1pb.Plan{
+ planCreated, err := client.createPlan(ctx, w.Project, &v1pb.Plan{
Title: releaseID,
Specs: []*v1pb.Plan_Spec{
{
@@ -127,9 +127,9 @@ func runRollout(w *world.World) func(command *cobra.Command, _ []string) error {
}
}
-func runAndWaitForRollout(ctx context.Context, w *world.World, client *Client, planName string) error {
+func runAndWaitForRollout(ctx context.Context, w *world.World, client *client, planName string) error {
// create rollout with all stages created
- rollout, err := client.CreateRollout(ctx, &v1pb.CreateRolloutRequest{
+ rollout, err := client.createRollout(ctx, &v1pb.CreateRolloutRequest{
Parent: planName,
Target: nil, // all stages
})
@@ -144,7 +144,7 @@ func runAndWaitForRollout(ctx context.Context, w *world.World, client *Client, p
return waitForRollout(ctx, w, client, rollout.Name)
}
-func waitForRollout(ctx context.Context, w *world.World, client *Client, rolloutName string) error {
+func waitForRollout(ctx context.Context, w *world.World, client *client, rolloutName string) error {
if w.TargetStage == "" {
w.Logger.Info("target stage is not specified, exiting...")
return nil
@@ -160,7 +160,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, rollout
}
}()
- rollout, err := client.GetRollout(ctx, rolloutName)
+ rollout, err := client.getRollout(ctx, rolloutName)
if err != nil {
return errors.Wrapf(err, "failed to get rollout")
}
@@ -198,7 +198,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, rollout
return errors.Wrapf(ctx.Err(), "context cancelled")
}
// get rollout to refresh status
- rollout, err := client.GetRollout(ctx, rolloutName)
+ rollout, err := client.getRollout(ctx, rolloutName)
if err != nil {
return errors.Wrapf(err, "failed to get rollout")
}
@@ -256,7 +256,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, rollout
// run stage tasks
if len(notStartedTasks) > 0 {
w.Logger.Info("running stage tasks", "stage", stage.Environment, "taskCount", len(notStartedTasks))
- if _, err := client.BatchRunTasks(ctx, &v1pb.BatchRunTasksRequest{
+ if _, err := client.batchRunTasks(ctx, &v1pb.BatchRunTasksRequest{
Parent: stage.Name,
Tasks: notStartedTasks,
}); err != nil {
@@ -270,8 +270,8 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, rollout
return nil
}
-func cancelRollout(ctx context.Context, client *Client, rolloutName string) error {
- taskRuns, err := client.ListAllTaskRuns(ctx, rolloutName)
+func cancelRollout(ctx context.Context, client *client, rolloutName string) error {
+ taskRuns, err := client.listAllTaskRuns(ctx, rolloutName)
if err != nil {
return errors.Wrapf(err, "failed to list task runs")
}
@@ -284,7 +284,7 @@ func cancelRollout(ctx context.Context, client *Client, rolloutName string) erro
}
var errs error
for stage, taskRuns := range taskRunsToCancelByStage {
- _, err := client.BatchCancelTaskRuns(ctx, &v1pb.BatchCancelTaskRunsRequest{
+ _, err := client.batchCancelTaskRuns(ctx, &v1pb.BatchCancelTaskRunsRequest{
Parent: stage + "/tasks/-",
TaskRuns: taskRuns,
})
diff --git a/action/command/root.go b/action/command/root.go
index 442e16f6c8..4ae5cc866c 100644
--- a/action/command/root.go
+++ b/action/command/root.go
@@ -56,26 +56,27 @@ func rootPreRun(w *world.World) func(cmd *cobra.Command, args []string) error {
}
}
-// NewClientFromWorld creates a Client using the authentication method configured in World.
-func NewClientFromWorld(w *world.World) (*Client, error) {
- clientOptions := DefaultClientOptions()
+// newClientFromWorld creates a client using the authentication configured in World.
+func newClientFromWorld(w *world.World) (*client, error) {
+ options := defaultClientOptions()
if w.Timeout > 0 {
- clientOptions.Timeout = w.Timeout
+ options.timeout = w.Timeout
}
+ // Access tokens take precedence when both auth modes are populated.
if w.AccessToken != "" {
- return createClient(w.URL, w.AccessToken, "", "", clientOptions)
+ return newClient(w.URL, w.AccessToken, "", "", options)
}
- return NewClientWithOptions(w.URL, w.ServiceAccount, w.ServiceAccountSecret, clientOptions)
+ return newClient(w.URL, "", w.ServiceAccount, w.ServiceAccountSecret, options)
}
-func CheckVersionCompatibility(w *world.World, client *Client, cliVersion string) {
+func checkVersionCompatibility(w *world.World, client *client, cliVersion string) {
if cliVersion == "unknown" {
w.Logger.Warn("CLI version unknown, unable to check compatibility")
return
}
- actuatorInfo, err := client.GetActuatorInfo(context.Background())
+ actuatorInfo, err := client.getActuatorInfo(context.Background())
if err != nil {
w.Logger.Warn("Unable to get server version for compatibility check", "error", err)
return