From 4a3225b6df3478ad8cb345ca2671b9fef4469842 Mon Sep 17 00:00:00 2001 From: "parth.bansal" Date: Tue, 1 Dec 2026 16:31:59 +0000 Subject: [PATCH 1/9] Add a modular Go SDK client factory and the DATABRICKS_CLI_GO_SDK selector libs/sdkgo turns the CLI's resolved classic config into sdk-go client options. Options sends each sdk-go request through a classic API client built from the config, so it gets the classic retries, timeouts, rate limit, User-Agent segments and debug logs. The files client now takes only ConfigOptions (routing and auth), with no change in behavior. UseModular reads DATABRICKS_CLI_GO_SDK (unset, classic or modular) through libs/env, with an empty per-group default table, and WithClassicHint adds a hint to internal errors of the modular path. Co-authored-by: Isaac Signed-off-by: parth.bansal --- libs/filer/files_client.go | 18 +- libs/httptransport/transport.go | 3 +- .../credentials.go} | 18 +- libs/sdkgo/defaults.go | 5 + libs/sdkgo/options.go | 52 +++ libs/sdkgo/selector.go | 82 +++++ libs/sdkgo/selector_test.go | 157 +++++++++ libs/sdkgo/transport.go | 256 ++++++++++++++ libs/sdkgo/transport_test.go | 327 ++++++++++++++++++ 9 files changed, 894 insertions(+), 24 deletions(-) rename libs/{filer/files_client_auth.go => sdkgo/credentials.go} (71%) create mode 100644 libs/sdkgo/defaults.go create mode 100644 libs/sdkgo/options.go create mode 100644 libs/sdkgo/selector.go create mode 100644 libs/sdkgo/selector_test.go create mode 100644 libs/sdkgo/transport.go create mode 100644 libs/sdkgo/transport_test.go diff --git a/libs/filer/files_client.go b/libs/filer/files_client.go index 58ba7b3e0a3..5e94c339aab 100644 --- a/libs/filer/files_client.go +++ b/libs/filer/files_client.go @@ -17,9 +17,9 @@ import ( "syscall" "time" - "github.com/databricks/cli/libs/databrickscfg/profile" "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/log" + "github.com/databricks/cli/libs/sdkgo" "github.com/databricks/databricks-sdk-go" "github.com/databricks/databricks-sdk-go/config" "github.com/databricks/sdk-go/core/apierr" @@ -27,7 +27,6 @@ import ( "github.com/databricks/sdk-go/core/ops" files "github.com/databricks/sdk-go/files/v2" "github.com/databricks/sdk-go/options/call" - "github.com/databricks/sdk-go/options/client" "golang.org/x/sync/errgroup" ) @@ -359,19 +358,10 @@ func newTransferClient(n int) *http.Client { // newFilesAPIClient builds the files/v2 client from the CLI's already resolved // config, reusing its auth instead of re-reading a profile. cfg is passed by // pointer because config.Config embeds a sync.Mutex and must not be copied. +// It takes only sdkgo.ConfigOptions because the filer retries its calls itself +// and relies on the files/v2 call timeouts. func newFilesAPIClient(ctx context.Context, cfg *config.Config) (*files.Client, error) { - copts := []client.Option{ - client.WithHost(cfg.Host), - client.WithCredentials(configCredentials{cfg: cfg}), - client.WithoutConfigFile(), - client.WithoutEnv(), - } - // The workspace routing header is needed on unified ("SPOG") hosts; the CLI's - // "none" sentinel means "no workspace ID", so it is not forwarded. - if id := cfg.WorkspaceID; id != "" && id != profile.WorkspaceIDNone { - copts = append(copts, client.WithWorkspaceID(id)) - } - return files.NewClient(ctx, copts...) + return files.NewClient(ctx, sdkgo.ConfigOptions(cfg)...) } func (w *FilesClient) Write(ctx context.Context, name string, reader io.Reader, mode ...WriteMode) error { diff --git a/libs/httptransport/transport.go b/libs/httptransport/transport.go index 3a72c61acec..5fbdd4730fd 100644 --- a/libs/httptransport/transport.go +++ b/libs/httptransport/transport.go @@ -25,7 +25,8 @@ const ( // newHealthCheckedTransport mirrors the SDK's default transport (httpclient.makeDefaultTransport, // which is unexported) and adds the HTTP/2 health check. Keep the two in sync on SDK upgrades. // experimental/ssh/internal/client/releases.go (newHTTP11Transport) is another hand copy of the -// same defaults, HTTP/1.1-only; check it too. +// same defaults, HTTP/1.1-only, and libs/sdkgo (newDefaultTransport) one without the health check; +// check them too. func newHealthCheckedTransport(insecureSkipVerify bool) *http.Transport { t := &http.Transport{ Proxy: http.ProxyFromEnvironment, diff --git a/libs/filer/files_client_auth.go b/libs/sdkgo/credentials.go similarity index 71% rename from libs/filer/files_client_auth.go rename to libs/sdkgo/credentials.go index 6ed9098532f..f3884a1826e 100644 --- a/libs/filer/files_client_auth.go +++ b/libs/sdkgo/credentials.go @@ -1,4 +1,4 @@ -package filer +package sdkgo import ( "context" @@ -9,19 +9,19 @@ import ( ) // configCredentials adapts the CLI's resolved SDK config into the credentials -// interface expected by the files/v2 client. It signs a throwaway +// interface expected by sdk-go clients. It signs a throwaway // request with config.Authenticate and hands the resulting headers to the -// client, so the files/v2 client reuses the exact auth the rest of the CLI +// client, so an sdk-go client reuses the exact auth the rest of the CLI // already resolved instead of re-reading a profile. type configCredentials struct { cfg *config.Config } -// Name reports the resolved auth mechanism (e.g. "pat", "oauth-m2m"), which the -// files/v2 client folds into its User-Agent. The CLI resolves auth when it -// builds the workspace client, so AuthType is normally set before the filer is -// created; fall back to "unk" when it is empty because the files/v2 client -// rejects an empty auth name with an "invalid value" error at construction. +// Name reports the resolved auth mechanism (e.g. "pat", "oauth-m2m"), which an +// sdk-go client folds into its User-Agent. The CLI resolves auth when it +// builds the workspace client, so AuthType is normally set before an sdk-go +// client is created; fall back to "unk" when it is empty because sdk-go clients +// reject an empty auth name with an "invalid value" error at construction. func (c configCredentials) Name() string { if c.cfg.AuthType == "" { return "unk" @@ -31,7 +31,7 @@ func (c configCredentials) Name() string { func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, error) { // The URL is irrelevant: config.Authenticate only reads it to pick the auth - // scheme, and every files/v2 request targets the same workspace host. + // scheme, and every sdk-go request targets the same host. req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.cfg.Host, nil) if err != nil { return nil, err diff --git a/libs/sdkgo/defaults.go b/libs/sdkgo/defaults.go new file mode 100644 index 00000000000..db00f1d68c6 --- /dev/null +++ b/libs/sdkgo/defaults.go @@ -0,0 +1,5 @@ +package sdkgo + +// modularByDefault lists the command groups that use the modular Go SDK when +// DATABRICKS_CLI_GO_SDK is unset. A group that isn't listed uses the classic SDK. +var modularByDefault = map[string]bool{} diff --git a/libs/sdkgo/options.go b/libs/sdkgo/options.go new file mode 100644 index 00000000000..aab1ea1454d --- /dev/null +++ b/libs/sdkgo/options.go @@ -0,0 +1,52 @@ +// Package sdkgo builds clients of the modular Go SDK (github.com/databricks/sdk-go) from the +// CLI's resolved classic SDK config, and selects which of the two SDKs serves a command. +package sdkgo + +import ( + "log/slog" + + "github.com/databricks/cli/libs/databrickscfg/profile" + "github.com/databricks/databricks-sdk-go/config" + "github.com/databricks/sdk-go/options/client" +) + +// ConfigOptions returns the options that point an sdk-go client at the host, workspace and +// account of cfg and authenticate it with cfg's resolved credentials. sdk-go reads neither a +// profile nor the environment, which the CLI already resolved into cfg. cfg is passed by +// pointer because config.Config embeds a sync.Mutex and must not be copied. +func ConfigOptions(cfg *config.Config) []client.Option { + opts := []client.Option{ + client.WithHost(cfg.Host), + client.WithCredentials(configCredentials{cfg: cfg}), + client.WithoutConfigFile(), + client.WithoutEnv(), + } + // The workspace routing header is needed on unified ("SPOG") hosts; the CLI's + // "none" sentinel means "no workspace ID", so it is not forwarded. + if id := cfg.WorkspaceID; id != "" && id != profile.WorkspaceIDNone { + opts = append(opts, client.WithWorkspaceID(id)) + } + if cfg.AccountID != "" { + opts = append(opts, client.WithAccountID(cfg.AccountID)) + } + return opts +} + +// Options returns ConfigOptions plus an HTTP client that sends every request through a classic +// SDK API client built from cfg, so that each request gets the classic path's retries, +// per-request timeout, rate limit, User-Agent and --debug logs. Clients built from the same +// options share one rate limit, as the services of one classic WorkspaceClient do. +func Options(cfg *config.Config) ([]client.Option, error) { + httpClient, err := newHTTPClient(cfg) + if err != nil { + return nil, err + } + return append(ConfigOptions(cfg), + client.WithHTTPClient(httpClient), + // The classic client bounds each attempt and the retry window but not a whole call, so + // sdk-go's call timeout, which would cut a retry window longer than it, is turned off. + client.WithTimeout(0), + // The classic client logs every request, so sdk-go must not log them again. + client.WithLogger(slog.New(slog.DiscardHandler)), + ), nil +} diff --git a/libs/sdkgo/selector.go b/libs/sdkgo/selector.go new file mode 100644 index 00000000000..59cdee48a74 --- /dev/null +++ b/libs/sdkgo/selector.go @@ -0,0 +1,82 @@ +package sdkgo + +import ( + "context" + "errors" + "fmt" + "net/url" + + "github.com/databricks/cli/libs/env" + "github.com/databricks/cli/libs/log" + "github.com/databricks/sdk-go/core/apierr" +) + +// EnvVar names the environment variable that selects the Go SDK of the commands that support +// both SDKs. +const EnvVar = "DATABRICKS_CLI_GO_SDK" + +const ( + classicSDK = "classic" + modularSDK = "modular" +) + +// UseModular reports whether the commands of group use the modular Go SDK. With +// DATABRICKS_CLI_GO_SDK unset, group uses its entry in modularByDefault; "classic" and +// "modular" select that SDK for every command that supports both. Any other value is an +// error, which the command returns before it sends a request. Only the environment decides: +// the CLI never switches SDKs by itself, as after a failure. +func UseModular(ctx context.Context, group string) (bool, error) { + return useModular(ctx, group, modularByDefault) +} + +func useModular(ctx context.Context, group string, defaults map[string]bool) (bool, error) { + var modular bool + switch value := env.Get(ctx, EnvVar); value { + case "": + modular = defaults[group] + case classicSDK: + modular = false + case modularSDK: + modular = true + default: + return false, fmt.Errorf("invalid value %q for %s: valid values are %q and %q, or unset for the default of each command", value, EnvVar, classicSDK, modularSDK) + } + sdk := classicSDK + if modular { + sdk = modularSDK + } + log.Debugf(ctx, "Using the %s Go SDK for %s commands", sdk, group) + return modular, nil +} + +// classicHint follows the text of an internal error of the modular Go SDK. +const classicHint = "Set " + EnvVar + "=" + classicSDK + " to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues." + +// WithClassicHint returns err with a hint to switch back to the classic SDK when err is an +// internal error of the modular SDK, such as a response it could not decode. An API error, a +// failed request and a cancellation come from the server, the network or the caller, so they +// are returned as is. +func WithClassicHint(err error) error { + if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return err + } + if _, ok := errors.AsType[*apierr.APIError](err); ok { + return err + } + if _, ok := errors.AsType[*url.Error](err); ok { + return err + } + return modularError{err: err} +} + +type modularError struct { + err error +} + +func (e modularError) Error() string { + return e.err.Error() + "\n\n" + classicHint +} + +func (e modularError) Unwrap() error { + return e.err +} diff --git a/libs/sdkgo/selector_test.go b/libs/sdkgo/selector_test.go new file mode 100644 index 00000000000..3c53cc59215 --- /dev/null +++ b/libs/sdkgo/selector_test.go @@ -0,0 +1,157 @@ +package sdkgo + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "net/http" + "net/url" + "slices" + "testing" + + "github.com/databricks/cli/libs/env" + "github.com/databricks/databricks-sdk-go" + "github.com/databricks/sdk-go/core/apierr" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestUseModular(t *testing.T) { + testCases := []struct { + name string + value string + group string + defaults map[string]bool + want bool + wantLog string + wantErr string + }{ + { + name: "unset", + group: "jobs", + want: false, + wantLog: "Using the classic Go SDK for jobs commands", + }, + { + name: "unset uses the default table", + group: "jobs", + defaults: map[string]bool{"jobs": true}, + want: true, + wantLog: "Using the modular Go SDK for jobs commands", + }, + { + name: "unset for a group not in the default table", + group: "clusters", + defaults: map[string]bool{"jobs": true}, + want: false, + wantLog: "Using the classic Go SDK for clusters commands", + }, + { + name: "classic overrides the default table", + value: "classic", + group: "jobs", + defaults: map[string]bool{"jobs": true}, + want: false, + wantLog: "Using the classic Go SDK for jobs commands", + }, + { + name: "modular", + value: "modular", + group: "clusters", + want: true, + wantLog: "Using the modular Go SDK for clusters commands", + }, + { + name: "invalid value", + value: "new", + group: "jobs", + wantErr: `invalid value "new" for DATABRICKS_CLI_GO_SDK: valid values are "classic" and "modular", or unset for the default of each command`, + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + ctx, logs := captureLogs(env.Set(t.Context(), EnvVar, tc.value)) + got, err := useModular(ctx, tc.group, tc.defaults) + if tc.wantErr != "" { + assert.EqualError(t, err, tc.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tc.want, got) + assert.Contains(t, logs.String(), tc.wantLog) + }) + } +} + +func TestUseModularUsesDefaultTable(t *testing.T) { + ctx := env.Set(t.Context(), EnvVar, "") + groups := slices.Collect(maps.Keys(modularByDefault)) + for _, group := range append(groups, "not-a-group") { + got, err := UseModular(ctx, group) + require.NoError(t, err) + assert.Equal(t, modularByDefault[group], got, group) + } +} + +func TestWithClassicHint(t *testing.T) { + var syntaxErr *json.SyntaxError + decodeErr := json.Unmarshal([]byte("not json"), &struct{}{}) + require.ErrorAs(t, decodeErr, &syntaxErr) + apiErr := apierr.FromHTTPError(http.StatusNotFound, http.Header{}, []byte(`{"error_code": "NOT_FOUND", "message": "no such file"}`)) + urlErr := &url.Error{Op: "Post", URL: "https://example.test", Err: errors.New("connection refused")} + + testCases := []struct { + name string + err error + want error + }{ + { + name: "no error", + }, + { + name: "API error", + err: apiErr, + want: apiErr, + }, + { + name: "wrapped API error", + err: fmt.Errorf("create: %w", apiErr), + want: fmt.Errorf("create: %w", apiErr), + }, + { + name: "failed request", + err: urlErr, + want: urlErr, + }, + { + name: "cancellation", + err: context.Canceled, + want: context.Canceled, + }, + { + name: "decoding error", + err: decodeErr, + want: modularError{err: decodeErr}, + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, WithClassicHint(tc.err)) + }) + } +} + +func TestWithClassicHintOnUndecodableResponse(t *testing.T) { + server := newTestServer(t) + _, c := clients(t, server, &databricks.Config{}) + + var err error + server.record(func() { err = createModular(t.Context(), c) }, respond(http.StatusOK, nil, "not json")) + + var syntaxErr *json.SyntaxError + err = WithClassicHint(err) + assert.ErrorAs(t, err, &syntaxErr) + assert.ErrorContains(t, err, "\n\nSet DATABRICKS_CLI_GO_SDK=classic to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues.") +} diff --git a/libs/sdkgo/transport.go b/libs/sdkgo/transport.go new file mode 100644 index 00000000000..38d05678a63 --- /dev/null +++ b/libs/sdkgo/transport.go @@ -0,0 +1,256 @@ +package sdkgo + +import ( + "bytes" + "context" + "crypto/tls" + "errors" + "io" + "net" + "net/http" + "net/url" + "runtime" + "slices" + "strings" + "time" + + "github.com/databricks/databricks-sdk-go/apierr" + "github.com/databricks/databricks-sdk-go/config" + "github.com/databricks/databricks-sdk-go/httpclient" + "github.com/databricks/databricks-sdk-go/version" +) + +// classicSDKSegment is the User-Agent segment that names the classic SDK. +const classicSDKSegment = "databricks-sdk-go/" + version.Version + +// newHTTPClient returns the HTTP client for sdk-go. It hands each request to a classic API +// client built from cfg exactly as a classic WorkspaceClient builds its own, so the classic +// code decides the retries, timeouts and rate limit, authenticates each attempt and writes +// the debug log. +func newHTTPClient(cfg *config.Config) (*http.Client, error) { + clientCfg, err := config.HTTPClientConfigFromConfig(cfg) + if err != nil { + return nil, err + } + host, err := url.Parse(cfg.Host) + if err != nil { + return nil, err + } + base := cfg.HTTPTransport + if base == nil { + base = newDefaultTransport(cfg.InsecureSkipVerify) + } + clientCfg.Transport = sendTransport{base: base} + clientCfg.Visitors = append(clientCfg.Visitors, copyRequest) + return &http.Client{Transport: transport{api: httpclient.NewApiClient(clientCfg), base: base, host: host}}, nil +} + +// newDefaultTransport returns a transport with the settings of the classic client's default +// transport (httpclient.makeDefaultTransport, which is unexported), which the classic client +// uses when the config has no HTTPTransport. libs/httptransport has the CLI's other copy, but +// its tests import libs/retry, which imports libs/filer, which imports this package. +func newDefaultTransport(insecureSkipVerify bool) *http.Transport { + t := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + ForceAttemptHTTP2: true, + MaxIdleConns: 100, + MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, + IdleConnTimeout: 180 * time.Second, + TLSHandshakeTimeout: 30 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + } + if insecureSkipVerify { + // The classic client applies InsecureSkipVerify only to its own transport, so it is carried over. + t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //nolint:gosec // the user opted in via skip_verify + } + return t +} + +// exchange carries one sdk-go request through the classic client, and its response back. +type exchange struct { + // request is the request sdk-go sent. + request *http.Request + + // stream is the body of request when the classic client gets it as a stream. + stream io.Closer + + // queryMethodBody is the body of request when its method is GET, DELETE or HEAD. The + // classic client sends request data on these methods as a query, so copyRequest sets it. + queryMethodBody []byte + + // sent reports whether the classic client handed a request to its transport. + sent bool + + // response is the response to the classic client's latest attempt. + response *http.Response + + // errorBody holds the body of response as the classic client read it, when response has + // an error status. + errorBody bytes.Buffer +} + +type exchangeKey struct{} + +func exchangeFrom(ctx context.Context) *exchange { + return ctx.Value(exchangeKey{}).(*exchange) +} + +// transport is the transport of sdk-go's HTTP client. +type transport struct { + api *httpclient.ApiClient + base http.RoundTripper + + // host is the config's host, the only one the classic client sends requests to. + host *url.URL +} + +func (t transport) RoundTrip(req *http.Request) (*http.Response, error) { + // The classic client sends a request to the config's host with the config's credentials + // whatever its URL, so a request to another host goes out as sdk-go built it. + if req.URL.Scheme != t.host.Scheme || req.URL.Host != t.host.Host { + return t.base.RoundTrip(req) + } + + ex := &exchange{request: req} + opts, err := requestOptions(ex) + if err != nil { + return nil, err + } + err = t.api.Do(context.WithValue(req.Context(), exchangeKey{}, ex), req.Method, req.URL.String(), opts...) + // The classic client's transport closes a stream it sends, but no one closes one it never + // sends, as when waiting for the rate limit fails. + if ex.stream != nil && !ex.sent { + _ = ex.stream.Close() + } + if err == nil { + return ex.response, nil + } + + // The classic client turns an error status into an error, which sdk-go makes from the + // response itself. + if _, ok := errors.AsType[*apierr.APIError](err); ok && ex.response != nil && ex.response.StatusCode >= http.StatusBadRequest { + // The classic client reads an error body it streams without closing it. + _ = ex.response.Body.Close() + ex.response.Body = io.NopCloser(bytes.NewReader(ex.errorBody.Bytes())) + return ex.response, nil + } + + // net/http wraps an error of a transport in a *url.Error, so returning the cause of the + // classic client's one keeps the error text of the classic path. + if urlErr, ok := errors.AsType[*url.Error](err); ok { + return nil, urlErr.Err + } + return nil, err +} + +// requestOptions hands the body of ex's request to the classic client. A JSON body, which +// sdk-go holds in memory, goes as bytes, which the classic client replays on a retry and shows +// in its debug log, as it does the JSON of a classic call. Any other body goes as a stream, +// which it sends once, as it does the io.Reader of a classic call. +func requestOptions(ex *exchange) ([]httpclient.DoOption, error) { + req := ex.request + if req.Body == nil { + return nil, nil + } + queryMethod := req.Method == http.MethodGet || req.Method == http.MethodDelete || req.Method == http.MethodHead + if !queryMethod && !strings.HasPrefix(req.Header.Get("Content-Type"), "application/json") { + ex.stream = req.Body + return []httpclient.DoOption{httpclient.WithRequestData(req.Body)}, nil + } + body, err := io.ReadAll(req.Body) + _ = req.Body.Close() + if err != nil { + return nil, err + } + if queryMethod { + ex.queryMethodBody = body + return nil, nil + } + return []httpclient.DoOption{httpclient.WithRequestData(body)}, nil +} + +// copyRequest is a classic request visitor that copies sdk-go's request onto the classic one. +// It sets the headers the classic client didn't set: the classic client authenticates each +// attempt itself, so its auth headers stay. +func copyRequest(r *http.Request) error { + ex := exchangeFrom(r.Context()) + if len(ex.queryMethodBody) > 0 { + r.Body = io.NopCloser(bytes.NewReader(ex.queryMethodBody)) + r.ContentLength = int64(len(ex.queryMethodBody)) + } else { + // The classic client can't tell the length of a stream. + r.ContentLength = ex.request.ContentLength + } + for key, values := range ex.request.Header { + if _, ok := r.Header[key]; ok { + continue + } + for _, value := range values { + r.Header.Add(key, value) + } + } + // Classic calls ask for JSON unless they stream a download, as sdk-go's downloads ask for + // a stream. The classic client reads a response to a request for JSON in full and shows it + // in its debug log. + if r.Header.Get("Accept") == "" { + r.Header.Set("Accept", "application/json") + } + return nil +} + +// sendTransport is the classic client's transport. It records each response for transport, +// and names sdk-go instead of the classic SDK in the User-Agent. +type sendTransport struct { + base http.RoundTripper +} + +func (t sendTransport) RoundTrip(req *http.Request) (*http.Response, error) { + ex := exchangeFrom(req.Context()) + ex.sent = true + // The classic client sets the User-Agent after its visitors run, so only its transport can + // replace it. The header is set on the request in place because the classic client builds + // the request for this attempt alone and logs its headers after sending it. + req.Header.Set("User-Agent", userAgent(req.Header.Get("User-Agent"), ex.request.Header.Get("User-Agent"))) + ex.response = nil + ex.errorBody.Reset() + resp, err := t.base.RoundTrip(req) + if err != nil { + return nil, err + } + if resp.StatusCode >= http.StatusBadRequest { + // The classic client reads an error body to make an error of it; keep a copy for sdk-go. + resp.Body = readCloser{Reader: io.TeeReader(resp.Body, &ex.errorBody), Closer: resp.Body} + } + ex.response = resp + return resp, nil +} + +type readCloser struct { + io.Reader + io.Closer +} + +// userAgent returns the classic User-Agent with the segment that names the classic SDK +// replaced by the segments of sdk-go's User-Agent that name sdk-go and its modules. The +// product, cli/, stays the first segment, as the classic SDK sends it, because usage +// monitoring attributes a request to the CLI by that segment. +func userAgent(classic, modular string) string { + var sdk []string + for segment := range strings.FieldsSeq(modular) { + if strings.HasPrefix(segment, "sdk-go-") { + sdk = append(sdk, segment) + } + } + segments := strings.Fields(classic) + i := slices.Index(segments, classicSDKSegment) + if i < 0 { + // The request of a redirect copies the headers of the one it follows, whose + // User-Agent was already replaced. + return classic + } + return strings.Join(slices.Replace(segments, i, i+1, sdk...), " ") +} diff --git a/libs/sdkgo/transport_test.go b/libs/sdkgo/transport_test.go new file mode 100644 index 00000000000..9cd0e866a0c --- /dev/null +++ b/libs/sdkgo/transport_test.go @@ -0,0 +1,327 @@ +package sdkgo + +import ( + "bytes" + "context" + "errors" + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "sync" + "testing" + + "github.com/databricks/cli/libs/log" + "github.com/databricks/databricks-sdk-go" + classicapierr "github.com/databricks/databricks-sdk-go/apierr" + classicfiles "github.com/databricks/databricks-sdk-go/service/files" + "github.com/databricks/databricks-sdk-go/useragent" + "github.com/databricks/sdk-go/core/apierr" + files "github.com/databricks/sdk-go/files/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const createPath = "/api/2.0/dbfs/create" + +// recordedRequest is a request the test server received at createPath. +type recordedRequest struct { + header http.Header + body []byte +} + +// testServer answers the n-th request at createPath with the n-th of its handlers, and every +// later one with the last handler. +type testServer struct { + *httptest.Server + + mu sync.Mutex + handlers []http.HandlerFunc + requests []recordedRequest +} + +func newTestServer(t *testing.T) *testServer { + s := &testServer{} + s.Server = httptest.NewServer(http.HandlerFunc(s.serve)) + t.Cleanup(s.Close) + return s +} + +func (s *testServer) serve(w http.ResponseWriter, r *http.Request) { + // Config resolution asks for the host's metadata, which these tests don't count. + if r.URL.Path == "/.well-known/databricks-config" { + _, _ = w.Write([]byte(`{}`)) + return + } + body, _ := io.ReadAll(r.Body) + s.mu.Lock() + s.requests = append(s.requests, recordedRequest{header: r.Header.Clone(), body: body}) + handler := s.handlers[min(len(s.requests), len(s.handlers))-1] + s.mu.Unlock() + handler(w, r) +} + +// record runs call against handlers and returns the requests it made. +func (s *testServer) record(call func(), handlers ...http.HandlerFunc) []recordedRequest { + s.mu.Lock() + s.handlers = handlers + s.requests = nil + s.mu.Unlock() + call() + s.mu.Lock() + defer s.mu.Unlock() + return s.requests +} + +func respond(status int, header map[string]string, body string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + for k, v := range header { + w.Header().Set(k, v) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + } +} + +var created = respond(http.StatusOK, nil, `{"handle": 7}`) + +// resetConnection closes the connection with a TCP reset instead of a response. +func resetConnection(w http.ResponseWriter, r *http.Request) { + conn, _, err := http.NewResponseController(w).Hijack() + if err != nil { + panic(err) + } + _ = conn.(*net.TCPConn).SetLinger(0) + _ = conn.Close() +} + +// clients returns a classic workspace client for the server and an sdk-go files client built +// with Options from the classic client's config. +func clients(t *testing.T, server *testServer, cfg *databricks.Config) (*databricks.WorkspaceClient, *files.Client) { + cfg.Host = server.URL + cfg.Token = "test-token" + cfg.WorkspaceID = "1234" + w, err := databricks.NewWorkspaceClient(cfg) + require.NoError(t, err) + opts, err := Options(w.Config) + require.NoError(t, err) + c, err := files.NewClient(t.Context(), opts...) + require.NoError(t, err) + return w, c +} + +func createClassic(ctx context.Context, w *databricks.WorkspaceClient) error { + _, err := w.Dbfs.Create(ctx, classicfiles.Create{Path: "/a", Overwrite: true}) + return err +} + +func createModular(ctx context.Context, c *files.Client) error { + path, overwrite := "/a", true + _, err := c.Create(ctx, files.CreateRequest{Path: &path, Overwrite: &overwrite}) + return err +} + +// segmentsWithoutSDK returns the segments of userAgent other than those that name an SDK. +func segmentsWithoutSDK(userAgent string) []string { + var segments []string + for segment := range strings.FieldsSeq(userAgent) { + if !strings.HasPrefix(segment, "databricks-sdk-go/") && !strings.HasPrefix(segment, "sdk-go-") { + segments = append(segments, segment) + } + } + return segments +} + +func TestOptionsSendClassicHeaders(t *testing.T) { + server := newTestServer(t) + w, c := clients(t, server, &databricks.Config{}) + ctx := useragent.InContext(t.Context(), "cmd", "sdkgo-test") + + classic := server.record(func() { require.NoError(t, createClassic(ctx, w)) }, created) + modular := server.record(func() { require.NoError(t, createModular(ctx, c)) }, created) + require.Len(t, classic, 1) + require.Len(t, modular, 1) + classicHeader, modularHeader := classic[0].header, modular[0].header + + classicUA, modularUA := classicHeader.Get("User-Agent"), modularHeader.Get("User-Agent") + assert.ElementsMatch(t, segmentsWithoutSDK(classicUA), segmentsWithoutSDK(modularUA)) + // The product comes first in both. + assert.Equal(t, segmentsWithoutSDK(classicUA)[0], strings.Fields(classicUA)[0]) + assert.Equal(t, strings.Fields(classicUA)[0], strings.Fields(modularUA)[0]) + assert.Contains(t, segmentsWithoutSDK(modularUA), "cmd/sdkgo-test") + assert.Contains(t, classicUA, classicSDKSegment) + assert.NotContains(t, modularUA, "databricks-sdk-go/") + assert.Contains(t, modularUA, "sdk-go-core/") + assert.Contains(t, modularUA, "sdk-go-files/") + + // The traceparent is random for each request. + assert.NotEmpty(t, classicHeader.Get("Traceparent")) + assert.NotEmpty(t, modularHeader.Get("Traceparent")) + for _, h := range []http.Header{classicHeader, modularHeader} { + h.Del("User-Agent") + h.Del("Traceparent") + } + assert.Equal(t, classicHeader, modularHeader) + assert.Equal(t, "Bearer test-token", modularHeader.Get("Authorization")) + assert.Equal(t, "1234", modularHeader.Get("X-Databricks-Workspace-Id")) + assert.JSONEq(t, string(classic[0].body), string(modular[0].body)) +} + +func TestOptionsRetryLikeClassic(t *testing.T) { + tooManyRequests := respond(http.StatusTooManyRequests, map[string]string{"Retry-After": "1"}, + `{"error_code": "TOO_MANY_REQUESTS", "message": "slow down"}`) + unavailable := respond(http.StatusServiceUnavailable, nil, + `{"error_code": "TEMPORARILY_UNAVAILABLE", "message": "try again"}`) + + testCases := []struct { + name string + // retryTimeoutSeconds is the classic retry window. + retryTimeoutSeconds int + handlers []http.HandlerFunc + wantAttempts int + wantStatus int + }{ + { + name: "429 with Retry-After", + handlers: []http.HandlerFunc{tooManyRequests, created}, + wantAttempts: 2, + }, + { + name: "503", + handlers: []http.HandlerFunc{unavailable, created}, + wantAttempts: 2, + }, + { + name: "connection reset", + handlers: []http.HandlerFunc{resetConnection, created}, + wantAttempts: 2, + }, + { + // The first retry waits at least 1s, past the end of a 1s retry window. + name: "503 past the retry window", + retryTimeoutSeconds: 1, + handlers: []http.HandlerFunc{unavailable}, + wantAttempts: 1, + wantStatus: http.StatusServiceUnavailable, + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + server := newTestServer(t) + w, c := clients(t, server, &databricks.Config{RetryTimeoutSeconds: tc.retryTimeoutSeconds}) + + var classicErr, modularErr error + classic := server.record(func() { classicErr = createClassic(t.Context(), w) }, tc.handlers...) + modular := server.record(func() { modularErr = createModular(t.Context(), c) }, tc.handlers...) + + assert.Len(t, modular, len(classic)) + // Go on Windows reports a reset as "forcibly closed", which the classic client + // doesn't retry. + if tc.name != "connection reset" || runtime.GOOS != "windows" { + assert.Len(t, classic, tc.wantAttempts) + } + assert.Equal(t, classicErr == nil, modularErr == nil) + if tc.wantStatus == 0 { + return + } + classicAPIErr, ok := errors.AsType[*classicapierr.APIError](classicErr) + require.True(t, ok, "classic error: %v", classicErr) + modularAPIErr, ok := errors.AsType[*apierr.APIError](modularErr) + require.True(t, ok, "modular error: %v", modularErr) + assert.Equal(t, tc.wantStatus, classicAPIErr.StatusCode) + assert.Equal(t, tc.wantStatus, modularAPIErr.HTTPStatusCode()) + assert.Equal(t, classicAPIErr.Message, modularAPIErr.Message()) + }) + } +} + +// captureLogs returns a context whose debug logs go to the returned buffer, without times. +func captureLogs(ctx context.Context) (context.Context, *bytes.Buffer) { + var buf bytes.Buffer + handler := slog.NewTextHandler(&buf, &slog.HandlerOptions{ + Level: log.LevelDebug, + ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { + if a.Key == slog.TimeKey { + return slog.Attr{} + } + return a + }, + }) + return log.NewContext(ctx, slog.New(handler)), &buf +} + +func TestOptionsLogLikeClassic(t *testing.T) { + server := newTestServer(t) + w, c := clients(t, server, &databricks.Config{}) + withToken := respond(http.StatusOK, nil, `{"handle": 7, "token": "dapi-secret-value"}`) + + classicCtx, classicLogs := captureLogs(t.Context()) + server.record(func() { require.NoError(t, createClassic(classicCtx, w)) }, withToken) + modularCtx, modularLogs := captureLogs(t.Context()) + server.record(func() { require.NoError(t, createModular(modularCtx, c)) }, withToken) + + assert.Equal(t, classicLogs.String(), modularLogs.String()) + assert.Equal(t, 1, strings.Count(modularLogs.String(), "POST "+createPath)) + assert.Contains(t, modularLogs.String(), "**REDACTED**") + assert.NotContains(t, modularLogs.String(), "dapi-secret-value") +} + +func TestOptionsTimeOutLikeClassic(t *testing.T) { + server := newTestServer(t) + w, c := clients(t, server, &databricks.Config{HTTPTimeoutSeconds: 1}) + stall := func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() } + + var classicErr, modularErr error + classic := server.record(func() { classicErr = createClassic(t.Context(), w) }, stall) + modular := server.record(func() { modularErr = createModular(t.Context(), c) }, stall) + + assert.Len(t, classic, 1) + assert.Len(t, modular, 1) + require.ErrorContains(t, classicErr, "request timed out after 1s of inactivity") + require.Error(t, modularErr) + assert.Equal(t, classicErr.Error(), modularErr.Error()) +} + +func TestOptionsSendOtherHostsUnchanged(t *testing.T) { + server := newTestServer(t) + w, _ := clients(t, server, &databricks.Config{}) + httpClient, err := newHTTPClient(w.Config) + require.NoError(t, err) + + var header http.Header + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + header = r.Header.Clone() + })) + t.Cleanup(other.Close) + + resp, err := httpClient.Get(other.URL + "/presigned") + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + assert.Equal(t, http.StatusOK, resp.StatusCode) + assert.Empty(t, header.Get("Authorization")) + assert.Empty(t, header.Get("Traceparent")) +} + +func TestOptionsSendBodyOfGet(t *testing.T) { + server := newTestServer(t) + w, _ := clients(t, server, &databricks.Config{}) + httpClient, err := newHTTPClient(w.Config) + require.NoError(t, err) + + requests := server.record(func() { + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, server.URL+createPath, strings.NewReader(`{"path": "/a"}`)) + require.NoError(t, err) + resp, err := httpClient.Do(req) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + }, created) + + require.Len(t, requests, 1) + assert.JSONEq(t, `{"path": "/a"}`, string(requests[0].body)) + assert.Equal(t, "Bearer test-token", requests[0].header.Get("Authorization")) +} From 2a365d7312535a649af7326da300ac9e90e1c641 Mon Sep 17 00:00:00 2001 From: "parth.bansal" Date: Tue, 1 Dec 2026 16:37:27 +0000 Subject: [PATCH 2/9] sdkgo: mask credentials in debug header logs; test traceparent and call deadline With debug_headers on, the classic client logs the Authorization header unmasked. The modular path masks it in its debug log until the owner decides whether to match classic. Tests now check the W3C format of the traceparent both paths send, and that neither path puts a deadline on a call, since Options turns off sdk-go's 5-minute call timeout. Co-authored-by: Isaac Signed-off-by: parth.bansal --- libs/sdkgo/transport.go | 37 +++++++++++++++++++++++-- libs/sdkgo/transport_test.go | 52 +++++++++++++++++++++++++++++++++--- 2 files changed, 84 insertions(+), 5 deletions(-) diff --git a/libs/sdkgo/transport.go b/libs/sdkgo/transport.go index 38d05678a63..21698ea9b6b 100644 --- a/libs/sdkgo/transport.go +++ b/libs/sdkgo/transport.go @@ -5,18 +5,22 @@ import ( "context" "crypto/tls" "errors" + "fmt" "io" "net" "net/http" "net/url" + "regexp" "runtime" "slices" "strings" + "sync" "time" "github.com/databricks/databricks-sdk-go/apierr" "github.com/databricks/databricks-sdk-go/config" "github.com/databricks/databricks-sdk-go/httpclient" + "github.com/databricks/databricks-sdk-go/logger" "github.com/databricks/databricks-sdk-go/version" ) @@ -42,7 +46,12 @@ func newHTTPClient(cfg *config.Config) (*http.Client, error) { } clientCfg.Transport = sendTransport{base: base} clientCfg.Visitors = append(clientCfg.Visitors, copyRequest) - return &http.Client{Transport: transport{api: httpclient.NewApiClient(clientCfg), base: base, host: host}}, nil + return &http.Client{Transport: transport{ + api: httpclient.NewApiClient(clientCfg), + base: base, + host: host, + maskAuthorization: cfg.DebugHeaders, + }}, nil } // newDefaultTransport returns a transport with the settings of the classic client's default @@ -106,6 +115,10 @@ type transport struct { // host is the config's host, the only one the classic client sends requests to. host *url.URL + + // maskAuthorization reports whether the debug log shows request headers, whose + // credentials the classic client logs unmasked. + maskAuthorization bool } func (t transport) RoundTrip(req *http.Request) (*http.Response, error) { @@ -120,7 +133,11 @@ func (t transport) RoundTrip(req *http.Request) (*http.Response, error) { if err != nil { return nil, err } - err = t.api.Do(context.WithValue(req.Context(), exchangeKey{}, ex), req.Method, req.URL.String(), opts...) + ctx := context.WithValue(req.Context(), exchangeKey{}, ex) + if t.maskAuthorization { + ctx = logger.NewContext(ctx, maskingLogger{Logger: logger.Get(ctx)}) + } + err = t.api.Do(ctx, req.Method, req.URL.String(), opts...) // The classic client's transport closes a stream it sends, but no one closes one it never // sends, as when waiting for the rate limit fails. if ex.stream != nil && !ex.sent { @@ -254,3 +271,19 @@ func userAgent(classic, modular string) string { } return strings.Join(slices.Replace(segments, i, i+1, sdk...), " ") } + +// authorizationLine matches a request header line of the classic debug log that holds +// credentials, the headers the classic log masks when it masks any. +var authorizationLine = sync.OnceValue(func() *regexp.Regexp { + return regexp.MustCompile(`(?mi)^(> \* (?:Authorization|X-Databricks-Azure-Sp-Management-Token|X-Databricks-Gcp-Sa-Access-Token): ).*$`) +}) + +// maskingLogger is a classic SDK logger that masks the credentials in the request headers +// of the debug log, which the classic client logs unmasked when it logs headers. +type maskingLogger struct { + logger.Logger +} + +func (l maskingLogger) Debugf(ctx context.Context, format string, v ...any) { + l.Logger.Debugf(ctx, "%s", authorizationLine().ReplaceAllString(fmt.Sprintf(format, v...), "${1}REDACTED")) +} diff --git a/libs/sdkgo/transport_test.go b/libs/sdkgo/transport_test.go index 9cd0e866a0c..4c0cbe88fb6 100644 --- a/libs/sdkgo/transport_test.go +++ b/libs/sdkgo/transport_test.go @@ -158,9 +158,10 @@ func TestOptionsSendClassicHeaders(t *testing.T) { assert.Contains(t, modularUA, "sdk-go-core/") assert.Contains(t, modularUA, "sdk-go-files/") - // The traceparent is random for each request. - assert.NotEmpty(t, classicHeader.Get("Traceparent")) - assert.NotEmpty(t, modularHeader.Get("Traceparent")) + // The traceparent is a random W3C trace context for each request. + traceparent := `^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$` + assert.Regexp(t, traceparent, classicHeader.Get("Traceparent")) + assert.Regexp(t, traceparent, modularHeader.Get("Traceparent")) for _, h := range []http.Header{classicHeader, modularHeader} { h.Del("User-Agent") h.Del("Traceparent") @@ -325,3 +326,48 @@ func TestOptionsSendBodyOfGet(t *testing.T) { assert.JSONEq(t, `{"path": "/a"}`, string(requests[0].body)) assert.Equal(t, "Bearer test-token", requests[0].header.Get("Authorization")) } + +// deadlineTransport records whether the context of each request at createPath has a deadline. +type deadlineTransport struct { + mu sync.Mutex + deadlines []bool +} + +func (t *deadlineTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.Path == createPath { + _, ok := req.Context().Deadline() + t.mu.Lock() + t.deadlines = append(t.deadlines, ok) + t.mu.Unlock() + } + return http.DefaultTransport.RoundTrip(req) +} + +func TestOptionsSetNoCallDeadline(t *testing.T) { + server := newTestServer(t) + recorder := &deadlineTransport{} + w, c := clients(t, server, &databricks.Config{HTTPTransport: recorder}) + + server.record(func() { require.NoError(t, createClassic(t.Context(), w)) }, created) + server.record(func() { require.NoError(t, createModular(t.Context(), c)) }, created) + + // The classic client bounds attempts and the retry window but not a call, and sdk-go's + // 5-minute call deadline would show here. + assert.Equal(t, []bool{false, false}, recorder.deadlines) +} + +func TestOptionsMaskAuthorizationInDebugHeaders(t *testing.T) { + server := newTestServer(t) + w, c := clients(t, server, &databricks.Config{DebugHeaders: true}) + + classicCtx, classicLogs := captureLogs(t.Context()) + server.record(func() { require.NoError(t, createClassic(classicCtx, w)) }, created) + modularCtx, modularLogs := captureLogs(t.Context()) + server.record(func() { require.NoError(t, createModular(modularCtx, c)) }, created) + + // The classic log shows the token, which the modular path masks. + assert.Contains(t, classicLogs.String(), "> * Authorization: Bearer test-token") + assert.Contains(t, modularLogs.String(), "> * Authorization: REDACTED") + assert.NotContains(t, modularLogs.String(), "test-token") + assert.Contains(t, modularLogs.String(), "> * X-Databricks-Workspace-Id: 1234") +} From 879e6f753ee36dcfbe7d7e0b206ab64e16ab39b9 Mon Sep 17 00:00:00 2001 From: "parth.bansal" Date: Wed, 2 Dec 2026 16:03:00 +0000 Subject: [PATCH 3/9] sdkgo: rename the classic selector value to legacy; fix Codex findings DATABRICKS_CLI_GO_SDK now takes legacy and modular, and WithClassicHint is WithLegacyHint, at the owner's request. Fixes from a Codex review of the whole PR: - A request to a host other than the config's skipped the classic client's timeout while sdk-go's call timeout is off, so a server that never answered could hang it. It now waits for the response header no longer than the classic per-request timeout. - A login failure from the credentials bridge got the hint to switch SDKs, though both SDKs share the credentials. The bridge marks its errors, which WithLegacyHint leaves as is. - The test server indexed an empty handler list for a request outside the endpoint under test, such as a port watcher's probe, and panicked while holding its lock. Co-authored-by: Isaac Signed-off-by: parth.bansal --- libs/sdkgo/credentials.go | 16 ++++++++++- libs/sdkgo/defaults.go | 2 +- libs/sdkgo/selector.go | 27 ++++++++++--------- libs/sdkgo/selector_test.go | 52 ++++++++++++++++++++++++++++-------- libs/sdkgo/transport.go | 32 +++++++++++++++++++--- libs/sdkgo/transport_test.go | 30 +++++++++++++++++++-- 6 files changed, 128 insertions(+), 31 deletions(-) diff --git a/libs/sdkgo/credentials.go b/libs/sdkgo/credentials.go index f3884a1826e..60f3dfe8e8d 100644 --- a/libs/sdkgo/credentials.go +++ b/libs/sdkgo/credentials.go @@ -37,7 +37,7 @@ func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, e return nil, err } if err := c.cfg.Authenticate(req); err != nil { - return nil, err + return nil, credentialsError{err: err} } headers := make([]sdkauth.Header, 0, len(req.Header)) @@ -48,3 +48,17 @@ func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, e } return headers, nil } + +// credentialsError is an error of the CLI's credentials, which both Go SDKs share, so +// WithLegacyHint doesn't blame the modular SDK for it. +type credentialsError struct { + err error +} + +func (e credentialsError) Error() string { + return e.err.Error() +} + +func (e credentialsError) Unwrap() error { + return e.err +} diff --git a/libs/sdkgo/defaults.go b/libs/sdkgo/defaults.go index db00f1d68c6..acc45c38df1 100644 --- a/libs/sdkgo/defaults.go +++ b/libs/sdkgo/defaults.go @@ -1,5 +1,5 @@ package sdkgo // modularByDefault lists the command groups that use the modular Go SDK when -// DATABRICKS_CLI_GO_SDK is unset. A group that isn't listed uses the classic SDK. +// DATABRICKS_CLI_GO_SDK is unset. A group that isn't listed uses the legacy SDK. var modularByDefault = map[string]bool{} diff --git a/libs/sdkgo/selector.go b/libs/sdkgo/selector.go index 59cdee48a74..e86838e02aa 100644 --- a/libs/sdkgo/selector.go +++ b/libs/sdkgo/selector.go @@ -16,12 +16,12 @@ import ( const EnvVar = "DATABRICKS_CLI_GO_SDK" const ( - classicSDK = "classic" + legacySDK = "legacy" modularSDK = "modular" ) // UseModular reports whether the commands of group use the modular Go SDK. With -// DATABRICKS_CLI_GO_SDK unset, group uses its entry in modularByDefault; "classic" and +// DATABRICKS_CLI_GO_SDK unset, group uses its entry in modularByDefault; "legacy" and // "modular" select that SDK for every command that supports both. Any other value is an // error, which the command returns before it sends a request. Only the environment decides: // the CLI never switches SDKs by itself, as after a failure. @@ -34,14 +34,14 @@ func useModular(ctx context.Context, group string, defaults map[string]bool) (bo switch value := env.Get(ctx, EnvVar); value { case "": modular = defaults[group] - case classicSDK: + case legacySDK: modular = false case modularSDK: modular = true default: - return false, fmt.Errorf("invalid value %q for %s: valid values are %q and %q, or unset for the default of each command", value, EnvVar, classicSDK, modularSDK) + return false, fmt.Errorf("invalid value %q for %s: valid values are %q and %q, or unset for the default of each command", value, EnvVar, legacySDK, modularSDK) } - sdk := classicSDK + sdk := legacySDK if modular { sdk = modularSDK } @@ -49,14 +49,14 @@ func useModular(ctx context.Context, group string, defaults map[string]bool) (bo return modular, nil } -// classicHint follows the text of an internal error of the modular Go SDK. -const classicHint = "Set " + EnvVar + "=" + classicSDK + " to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues." +// legacyHint follows the text of an internal error of the modular Go SDK. +const legacyHint = "Set " + EnvVar + "=" + legacySDK + " to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues." -// WithClassicHint returns err with a hint to switch back to the classic SDK when err is an +// WithLegacyHint returns err with a hint to switch back to the legacy SDK when err is an // internal error of the modular SDK, such as a response it could not decode. An API error, a -// failed request and a cancellation come from the server, the network or the caller, so they -// are returned as is. -func WithClassicHint(err error) error { +// failed request, a credentials error and a cancellation come from the server, the network, +// the CLI's login or the caller, so they are returned as is. +func WithLegacyHint(err error) error { if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return err } @@ -66,6 +66,9 @@ func WithClassicHint(err error) error { if _, ok := errors.AsType[*url.Error](err); ok { return err } + if _, ok := errors.AsType[credentialsError](err); ok { + return err + } return modularError{err: err} } @@ -74,7 +77,7 @@ type modularError struct { } func (e modularError) Error() string { - return e.err.Error() + "\n\n" + classicHint + return e.err.Error() + "\n\n" + legacyHint } func (e modularError) Unwrap() error { diff --git a/libs/sdkgo/selector_test.go b/libs/sdkgo/selector_test.go index 3c53cc59215..4864a306d8a 100644 --- a/libs/sdkgo/selector_test.go +++ b/libs/sdkgo/selector_test.go @@ -13,6 +13,8 @@ import ( "github.com/databricks/cli/libs/env" "github.com/databricks/databricks-sdk-go" + "github.com/databricks/databricks-sdk-go/config" + "github.com/databricks/databricks-sdk-go/config/credentials" "github.com/databricks/sdk-go/core/apierr" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -32,7 +34,7 @@ func TestUseModular(t *testing.T) { name: "unset", group: "jobs", want: false, - wantLog: "Using the classic Go SDK for jobs commands", + wantLog: "Using the legacy Go SDK for jobs commands", }, { name: "unset uses the default table", @@ -46,15 +48,15 @@ func TestUseModular(t *testing.T) { group: "clusters", defaults: map[string]bool{"jobs": true}, want: false, - wantLog: "Using the classic Go SDK for clusters commands", + wantLog: "Using the legacy Go SDK for clusters commands", }, { - name: "classic overrides the default table", - value: "classic", + name: "legacy overrides the default table", + value: "legacy", group: "jobs", defaults: map[string]bool{"jobs": true}, want: false, - wantLog: "Using the classic Go SDK for jobs commands", + wantLog: "Using the legacy Go SDK for jobs commands", }, { name: "modular", @@ -67,7 +69,7 @@ func TestUseModular(t *testing.T) { name: "invalid value", value: "new", group: "jobs", - wantErr: `invalid value "new" for DATABRICKS_CLI_GO_SDK: valid values are "classic" and "modular", or unset for the default of each command`, + wantErr: `invalid value "new" for DATABRICKS_CLI_GO_SDK: valid values are "legacy" and "modular", or unset for the default of each command`, }, } for _, tc := range testCases { @@ -95,7 +97,7 @@ func TestUseModularUsesDefaultTable(t *testing.T) { } } -func TestWithClassicHint(t *testing.T) { +func TestWithLegacyHint(t *testing.T) { var syntaxErr *json.SyntaxError decodeErr := json.Unmarshal([]byte("not json"), &struct{}{}) require.ErrorAs(t, decodeErr, &syntaxErr) @@ -130,6 +132,11 @@ func TestWithClassicHint(t *testing.T) { err: context.Canceled, want: context.Canceled, }, + { + name: "credentials error", + err: credentialsError{err: errors.New("refresh token is invalid")}, + want: credentialsError{err: errors.New("refresh token is invalid")}, + }, { name: "decoding error", err: decodeErr, @@ -138,12 +145,12 @@ func TestWithClassicHint(t *testing.T) { } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, WithClassicHint(tc.err)) + assert.Equal(t, tc.want, WithLegacyHint(tc.err)) }) } } -func TestWithClassicHintOnUndecodableResponse(t *testing.T) { +func TestWithLegacyHintOnUndecodableResponse(t *testing.T) { server := newTestServer(t) _, c := clients(t, server, &databricks.Config{}) @@ -151,7 +158,30 @@ func TestWithClassicHintOnUndecodableResponse(t *testing.T) { server.record(func() { err = createModular(t.Context(), c) }, respond(http.StatusOK, nil, "not json")) var syntaxErr *json.SyntaxError - err = WithClassicHint(err) + err = WithLegacyHint(err) assert.ErrorAs(t, err, &syntaxErr) - assert.ErrorContains(t, err, "\n\nSet DATABRICKS_CLI_GO_SDK=classic to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues.") + assert.ErrorContains(t, err, "\n\nSet DATABRICKS_CLI_GO_SDK=legacy to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues.") +} + +// failingCredentials is a classic credentials strategy that fails, as an expired login does. +type failingCredentials struct { + err error +} + +func (c failingCredentials) Name() string { + return "failing" +} + +func (c failingCredentials) Configure(context.Context, *config.Config) (credentials.CredentialsProvider, error) { + return nil, c.err +} + +func TestWithLegacyHintKeepsLoginErrors(t *testing.T) { + server := newTestServer(t) + errLogin := errors.New("refresh token is invalid") + cfg := &config.Config{Host: server.URL, Credentials: failingCredentials{err: errLogin}} + + _, err := configCredentials{cfg: cfg}.AuthHeaders(t.Context()) + require.ErrorIs(t, err, errLogin) + assert.Equal(t, err, WithLegacyHint(err)) } diff --git a/libs/sdkgo/transport.go b/libs/sdkgo/transport.go index 21698ea9b6b..5e2d6878af0 100644 --- a/libs/sdkgo/transport.go +++ b/libs/sdkgo/transport.go @@ -27,6 +27,10 @@ import ( // classicSDKSegment is the User-Agent segment that names the classic SDK. const classicSDKSegment = "databricks-sdk-go/" + version.Version +// defaultHTTPTimeout is the classic client's per-request timeout when the config sets none +// (httpclient.defaultHTTPTimeout, which is unexported). +const defaultHTTPTimeout = 60 * time.Second + // newHTTPClient returns the HTTP client for sdk-go. It hands each request to a classic API // client built from cfg exactly as a classic WorkspaceClient builds its own, so the classic // code decides the retries, timeouts and rate limit, authenticates each attempt and writes @@ -48,12 +52,30 @@ func newHTTPClient(cfg *config.Config) (*http.Client, error) { clientCfg.Visitors = append(clientCfg.Visitors, copyRequest) return &http.Client{Transport: transport{ api: httpclient.NewApiClient(clientCfg), - base: base, + otherHosts: otherHostTransport(base, clientCfg.HTTPTimeout), host: host, maskAuthorization: cfg.DebugHeaders, }}, nil } +// otherHostTransport returns the transport for requests to hosts other than the config's, +// which the classic client doesn't send. sdk-go's call timeout is off, so it bounds the wait +// for a response header by the classic per-request timeout. It doesn't bound the body, which +// would cut a long transfer, as libs/filer's transfer client doesn't. A transport the config +// sets that isn't an *http.Transport, as tests set, is used as is. +func otherHostTransport(base http.RoundTripper, timeout time.Duration) http.RoundTripper { + t, ok := base.(*http.Transport) + if !ok { + return base + } + if timeout == 0 { + timeout = defaultHTTPTimeout + } + t = t.Clone() + t.ResponseHeaderTimeout = timeout + return t +} + // newDefaultTransport returns a transport with the settings of the classic client's default // transport (httpclient.makeDefaultTransport, which is unexported), which the classic client // uses when the config has no HTTPTransport. libs/httptransport has the CLI's other copy, but @@ -110,8 +132,10 @@ func exchangeFrom(ctx context.Context) *exchange { // transport is the transport of sdk-go's HTTP client. type transport struct { - api *httpclient.ApiClient - base http.RoundTripper + api *httpclient.ApiClient + + // otherHosts sends the requests to hosts other than host. + otherHosts http.RoundTripper // host is the config's host, the only one the classic client sends requests to. host *url.URL @@ -125,7 +149,7 @@ func (t transport) RoundTrip(req *http.Request) (*http.Response, error) { // The classic client sends a request to the config's host with the config's credentials // whatever its URL, so a request to another host goes out as sdk-go built it. if req.URL.Scheme != t.host.Scheme || req.URL.Host != t.host.Host { - return t.base.RoundTrip(req) + return t.otherHosts.RoundTrip(req) } ex := &exchange{request: req} diff --git a/libs/sdkgo/transport_test.go b/libs/sdkgo/transport_test.go index 4c0cbe88fb6..c70019d3b49 100644 --- a/libs/sdkgo/transport_test.go +++ b/libs/sdkgo/transport_test.go @@ -51,10 +51,17 @@ func newTestServer(t *testing.T) *testServer { } func (s *testServer) serve(w http.ResponseWriter, r *http.Request) { - // Config resolution asks for the host's metadata, which these tests don't count. - if r.URL.Path == "/.well-known/databricks-config" { + switch r.URL.Path { + case createPath: + case "/.well-known/databricks-config": + // Config resolution asks for the host's metadata, which these tests don't count. _, _ = w.Write([]byte(`{}`)) return + default: + // Other requests, such as the probe of a port watcher (see + // testserver.IsLocalhostProbe), can come before a test installs its handlers. + http.NotFound(w, r) + return } body, _ := io.ReadAll(r.Body) s.mu.Lock() @@ -371,3 +378,22 @@ func TestOptionsMaskAuthorizationInDebugHeaders(t *testing.T) { assert.NotContains(t, modularLogs.String(), "test-token") assert.Contains(t, modularLogs.String(), "> * X-Databricks-Workspace-Id: 1234") } + +func TestOptionsTimeOutOtherHosts(t *testing.T) { + server := newTestServer(t) + w, _ := clients(t, server, &databricks.Config{HTTPTimeoutSeconds: 1}) + httpClient, err := newHTTPClient(w.Config) + require.NoError(t, err) + + // The other host accepts the request and never answers it. + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-r.Context().Done() + })) + t.Cleanup(other.Close) + + resp, err := httpClient.Get(other.URL + "/presigned") + if resp != nil { + _ = resp.Body.Close() + } + require.ErrorContains(t, err, "timeout awaiting response headers") +} From 49f8d2d15929390cff180f6bcfda2e1aabb9e524 Mon Sep 17 00:00:00 2001 From: "parth.bansal" Date: Wed, 2 Dec 2026 17:04:37 +0000 Subject: [PATCH 4/9] CODEOWNERS: add eng-deco-platform as an owner of libs/sdkgo Co-authored-by: Isaac Signed-off-by: parth.bansal --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0f9d6f0d28d..13f2286ee61 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -79,6 +79,7 @@ /libs/telemetry/ @databricks/eng-deco-cli @databricks/eng-deco-platform /libs/process/ @databricks/eng-deco-cli @databricks/eng-deco-platform /libs/git/ @databricks/eng-deco-cli @databricks/eng-deco-platform +/libs/sdkgo/ @databricks/eng-deco-cli @databricks/eng-deco-platform # Integration tests /integration/ @databricks/eng-deco-cli @databricks/eng-deco-platform From eb6ecd33eb0b826e66c971613f96ea35c2e531af Mon Sep 17 00:00:00 2001 From: "parth.bansal" Date: Wed, 2 Dec 2026 17:32:18 +0000 Subject: [PATCH 5/9] sdkgo: keep the files client's login errors as they were The auth bridge that the files client uses returns config.Authenticate's error unchanged again, as it did in libs/filer. Only the clients that Options builds mark a failed login, so that WithLegacyHint doesn't add its hint to it. Co-authored-by: Isaac Signed-off-by: parth.bansal --- libs/sdkgo/credentials.go | 21 ++++++++++++++++--- libs/sdkgo/options.go | 9 ++++++-- libs/sdkgo/selector_test.go | 41 ++++++++++++++++++++++++++++++++----- 3 files changed, 61 insertions(+), 10 deletions(-) diff --git a/libs/sdkgo/credentials.go b/libs/sdkgo/credentials.go index 60f3dfe8e8d..c3b5a6d7fc0 100644 --- a/libs/sdkgo/credentials.go +++ b/libs/sdkgo/credentials.go @@ -37,7 +37,7 @@ func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, e return nil, err } if err := c.cfg.Authenticate(req); err != nil { - return nil, credentialsError{err: err} + return nil, err } headers := make([]sdkauth.Header, 0, len(req.Header)) @@ -49,8 +49,23 @@ func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, e return headers, nil } -// credentialsError is an error of the CLI's credentials, which both Go SDKs share, so -// WithLegacyHint doesn't blame the modular SDK for it. +// modularCredentials are the configCredentials of the clients that Options builds. They mark +// a failure to authenticate as a credentialsError, so WithLegacyHint doesn't blame the +// modular SDK for an error of the credentials that both Go SDKs share. The files client +// takes configCredentials, so its errors stay as they were. +type modularCredentials struct { + configCredentials +} + +func (c modularCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, error) { + headers, err := c.configCredentials.AuthHeaders(ctx) + if err != nil { + return nil, credentialsError{err: err} + } + return headers, nil +} + +// credentialsError is an error of the CLI's credentials. type credentialsError struct { err error } diff --git a/libs/sdkgo/options.go b/libs/sdkgo/options.go index aab1ea1454d..13bf555d326 100644 --- a/libs/sdkgo/options.go +++ b/libs/sdkgo/options.go @@ -7,6 +7,7 @@ import ( "github.com/databricks/cli/libs/databrickscfg/profile" "github.com/databricks/databricks-sdk-go/config" + sdkauth "github.com/databricks/sdk-go/auth" "github.com/databricks/sdk-go/options/client" ) @@ -15,9 +16,13 @@ import ( // profile nor the environment, which the CLI already resolved into cfg. cfg is passed by // pointer because config.Config embeds a sync.Mutex and must not be copied. func ConfigOptions(cfg *config.Config) []client.Option { + return configOptions(cfg, configCredentials{cfg: cfg}) +} + +func configOptions(cfg *config.Config, credentials sdkauth.Credentials) []client.Option { opts := []client.Option{ client.WithHost(cfg.Host), - client.WithCredentials(configCredentials{cfg: cfg}), + client.WithCredentials(credentials), client.WithoutConfigFile(), client.WithoutEnv(), } @@ -41,7 +46,7 @@ func Options(cfg *config.Config) ([]client.Option, error) { if err != nil { return nil, err } - return append(ConfigOptions(cfg), + return append(configOptions(cfg, modularCredentials{configCredentials{cfg: cfg}}), client.WithHTTPClient(httpClient), // The classic client bounds each attempt and the retry window but not a whole call, so // sdk-go's call timeout, which would cut a retry window longer than it, is turned off. diff --git a/libs/sdkgo/selector_test.go b/libs/sdkgo/selector_test.go index 4864a306d8a..6f761b31bda 100644 --- a/libs/sdkgo/selector_test.go +++ b/libs/sdkgo/selector_test.go @@ -16,6 +16,8 @@ import ( "github.com/databricks/databricks-sdk-go/config" "github.com/databricks/databricks-sdk-go/config/credentials" "github.com/databricks/sdk-go/core/apierr" + files "github.com/databricks/sdk-go/files/v2" + "github.com/databricks/sdk-go/options/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -176,12 +178,41 @@ func (c failingCredentials) Configure(context.Context, *config.Config) (credenti return nil, c.err } -func TestWithLegacyHintKeepsLoginErrors(t *testing.T) { +// loginError returns the error that a files/v2 call through a client built with options +// returns for a failed login, and the error that config.Authenticate returns for it. +func loginError(t *testing.T, options func(*config.Config) ([]client.Option, error)) (callErr, authErr error) { server := newTestServer(t) errLogin := errors.New("refresh token is invalid") - cfg := &config.Config{Host: server.URL, Credentials: failingCredentials{err: errLogin}} + newConfig := func() *config.Config { + return &config.Config{Host: server.URL, Credentials: failingCredentials{err: errLogin}} + } + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, server.URL, nil) + require.NoError(t, err) + authErr = newConfig().Authenticate(req) + require.ErrorIs(t, authErr, errLogin) + + opts, err := options(newConfig()) + require.NoError(t, err) + c, err := files.NewClient(t.Context(), opts...) + require.NoError(t, err) + callErr = createModular(t.Context(), c) + require.ErrorIs(t, callErr, errLogin) + return callErr, authErr +} - _, err := configCredentials{cfg: cfg}.AuthHeaders(t.Context()) - require.ErrorIs(t, err, errLogin) - assert.Equal(t, err, WithLegacyHint(err)) +func TestConfigOptionsReturnLoginErrorsUnchanged(t *testing.T) { + // The files client builds its client with ConfigOptions, and returns the error of + // config.Authenticate as it did before it moved onto this package. + callErr, authErr := loginError(t, func(cfg *config.Config) ([]client.Option, error) { + return ConfigOptions(cfg), nil + }) + assert.Equal(t, authErr, callErr) + _, marked := errors.AsType[credentialsError](callErr) + assert.False(t, marked) +} + +func TestWithLegacyHintKeepsLoginErrors(t *testing.T) { + callErr, authErr := loginError(t, Options) + assert.Equal(t, credentialsError{err: authErr}, callErr) + assert.Equal(t, callErr, WithLegacyHint(callErr)) } From 87e088a907af2c4bc08c0404ee9935e9fa74591d Mon Sep 17 00:00:00 2001 From: "parth.bansal" Date: Wed, 2 Dec 2026 17:44:51 +0000 Subject: [PATCH 6/9] sdkgo: drop the login-error handling for WithLegacyHint Keeping WithLegacyHint's hint off login failures needed a credentials wrapper, an error type and a second options helper, though no command calls WithLegacyHint yet. That moves to its own PR. ConfigOptions, Options and the auth bridge are back to the first commit's code. Co-authored-by: Isaac Signed-off-by: parth.bansal --- libs/sdkgo/credentials.go | 29 ------------------ libs/sdkgo/options.go | 9 ++---- libs/sdkgo/selector.go | 7 ++--- libs/sdkgo/selector_test.go | 61 ------------------------------------- 4 files changed, 4 insertions(+), 102 deletions(-) diff --git a/libs/sdkgo/credentials.go b/libs/sdkgo/credentials.go index c3b5a6d7fc0..f3884a1826e 100644 --- a/libs/sdkgo/credentials.go +++ b/libs/sdkgo/credentials.go @@ -48,32 +48,3 @@ func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, e } return headers, nil } - -// modularCredentials are the configCredentials of the clients that Options builds. They mark -// a failure to authenticate as a credentialsError, so WithLegacyHint doesn't blame the -// modular SDK for an error of the credentials that both Go SDKs share. The files client -// takes configCredentials, so its errors stay as they were. -type modularCredentials struct { - configCredentials -} - -func (c modularCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, error) { - headers, err := c.configCredentials.AuthHeaders(ctx) - if err != nil { - return nil, credentialsError{err: err} - } - return headers, nil -} - -// credentialsError is an error of the CLI's credentials. -type credentialsError struct { - err error -} - -func (e credentialsError) Error() string { - return e.err.Error() -} - -func (e credentialsError) Unwrap() error { - return e.err -} diff --git a/libs/sdkgo/options.go b/libs/sdkgo/options.go index 13bf555d326..aab1ea1454d 100644 --- a/libs/sdkgo/options.go +++ b/libs/sdkgo/options.go @@ -7,7 +7,6 @@ import ( "github.com/databricks/cli/libs/databrickscfg/profile" "github.com/databricks/databricks-sdk-go/config" - sdkauth "github.com/databricks/sdk-go/auth" "github.com/databricks/sdk-go/options/client" ) @@ -16,13 +15,9 @@ import ( // profile nor the environment, which the CLI already resolved into cfg. cfg is passed by // pointer because config.Config embeds a sync.Mutex and must not be copied. func ConfigOptions(cfg *config.Config) []client.Option { - return configOptions(cfg, configCredentials{cfg: cfg}) -} - -func configOptions(cfg *config.Config, credentials sdkauth.Credentials) []client.Option { opts := []client.Option{ client.WithHost(cfg.Host), - client.WithCredentials(credentials), + client.WithCredentials(configCredentials{cfg: cfg}), client.WithoutConfigFile(), client.WithoutEnv(), } @@ -46,7 +41,7 @@ func Options(cfg *config.Config) ([]client.Option, error) { if err != nil { return nil, err } - return append(configOptions(cfg, modularCredentials{configCredentials{cfg: cfg}}), + return append(ConfigOptions(cfg), client.WithHTTPClient(httpClient), // The classic client bounds each attempt and the retry window but not a whole call, so // sdk-go's call timeout, which would cut a retry window longer than it, is turned off. diff --git a/libs/sdkgo/selector.go b/libs/sdkgo/selector.go index e86838e02aa..06f27564388 100644 --- a/libs/sdkgo/selector.go +++ b/libs/sdkgo/selector.go @@ -54,8 +54,8 @@ const legacyHint = "Set " + EnvVar + "=" + legacySDK + " to use the previous Go // WithLegacyHint returns err with a hint to switch back to the legacy SDK when err is an // internal error of the modular SDK, such as a response it could not decode. An API error, a -// failed request, a credentials error and a cancellation come from the server, the network, -// the CLI's login or the caller, so they are returned as is. +// failed request and a cancellation come from the server, the network or the caller, so they +// are returned as is. func WithLegacyHint(err error) error { if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return err @@ -66,9 +66,6 @@ func WithLegacyHint(err error) error { if _, ok := errors.AsType[*url.Error](err); ok { return err } - if _, ok := errors.AsType[credentialsError](err); ok { - return err - } return modularError{err: err} } diff --git a/libs/sdkgo/selector_test.go b/libs/sdkgo/selector_test.go index 6f761b31bda..22bc8986a45 100644 --- a/libs/sdkgo/selector_test.go +++ b/libs/sdkgo/selector_test.go @@ -13,11 +13,7 @@ import ( "github.com/databricks/cli/libs/env" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/config" - "github.com/databricks/databricks-sdk-go/config/credentials" "github.com/databricks/sdk-go/core/apierr" - files "github.com/databricks/sdk-go/files/v2" - "github.com/databricks/sdk-go/options/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -134,11 +130,6 @@ func TestWithLegacyHint(t *testing.T) { err: context.Canceled, want: context.Canceled, }, - { - name: "credentials error", - err: credentialsError{err: errors.New("refresh token is invalid")}, - want: credentialsError{err: errors.New("refresh token is invalid")}, - }, { name: "decoding error", err: decodeErr, @@ -164,55 +155,3 @@ func TestWithLegacyHintOnUndecodableResponse(t *testing.T) { assert.ErrorAs(t, err, &syntaxErr) assert.ErrorContains(t, err, "\n\nSet DATABRICKS_CLI_GO_SDK=legacy to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues.") } - -// failingCredentials is a classic credentials strategy that fails, as an expired login does. -type failingCredentials struct { - err error -} - -func (c failingCredentials) Name() string { - return "failing" -} - -func (c failingCredentials) Configure(context.Context, *config.Config) (credentials.CredentialsProvider, error) { - return nil, c.err -} - -// loginError returns the error that a files/v2 call through a client built with options -// returns for a failed login, and the error that config.Authenticate returns for it. -func loginError(t *testing.T, options func(*config.Config) ([]client.Option, error)) (callErr, authErr error) { - server := newTestServer(t) - errLogin := errors.New("refresh token is invalid") - newConfig := func() *config.Config { - return &config.Config{Host: server.URL, Credentials: failingCredentials{err: errLogin}} - } - req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, server.URL, nil) - require.NoError(t, err) - authErr = newConfig().Authenticate(req) - require.ErrorIs(t, authErr, errLogin) - - opts, err := options(newConfig()) - require.NoError(t, err) - c, err := files.NewClient(t.Context(), opts...) - require.NoError(t, err) - callErr = createModular(t.Context(), c) - require.ErrorIs(t, callErr, errLogin) - return callErr, authErr -} - -func TestConfigOptionsReturnLoginErrorsUnchanged(t *testing.T) { - // The files client builds its client with ConfigOptions, and returns the error of - // config.Authenticate as it did before it moved onto this package. - callErr, authErr := loginError(t, func(cfg *config.Config) ([]client.Option, error) { - return ConfigOptions(cfg), nil - }) - assert.Equal(t, authErr, callErr) - _, marked := errors.AsType[credentialsError](callErr) - assert.False(t, marked) -} - -func TestWithLegacyHintKeepsLoginErrors(t *testing.T) { - callErr, authErr := loginError(t, Options) - assert.Equal(t, credentialsError{err: authErr}, callErr) - assert.Equal(t, callErr, WithLegacyHint(callErr)) -} From 80492267efec04564e40fef176b8d8301cc4b85f Mon Sep 17 00:00:00 2001 From: "parth.bansal" Date: Wed, 2 Dec 2026 18:05:58 +0000 Subject: [PATCH 7/9] sdkgo: keep the legacy-SDK hint off login failures Both Go SDKs share the CLI's credentials, so switching SDKs can't fix a failed login, such as a cached token without a refresh token. The credentials of the clients that Options builds now return such a failure as a loginError, which keeps the message and unwraps to the original error, and WithLegacyHint returns it as is. ConfigOptions, which the files client uses, keeps the credentials unchanged, so the files client's errors stay exactly as they were. Co-authored-by: Isaac Signed-off-by: parth.bansal --- libs/sdkgo/credentials.go | 16 +++++++++++ libs/sdkgo/options.go | 2 ++ libs/sdkgo/selector.go | 7 +++-- libs/sdkgo/selector_test.go | 56 +++++++++++++++++++++++++++++++++++++ 4 files changed, 79 insertions(+), 2 deletions(-) diff --git a/libs/sdkgo/credentials.go b/libs/sdkgo/credentials.go index f3884a1826e..67158602166 100644 --- a/libs/sdkgo/credentials.go +++ b/libs/sdkgo/credentials.go @@ -15,6 +15,9 @@ import ( // already resolved instead of re-reading a profile. type configCredentials struct { cfg *config.Config + + // markLoginErrors makes AuthHeaders return a failure to authenticate as a loginError. + markLoginErrors bool } // Name reports the resolved auth mechanism (e.g. "pat", "oauth-m2m"), which an @@ -37,6 +40,9 @@ func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, e return nil, err } if err := c.cfg.Authenticate(req); err != nil { + if c.markLoginErrors { + return nil, loginError{err} + } return nil, err } @@ -48,3 +54,13 @@ func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, e } return headers, nil } + +// loginError is a failure to authenticate with the CLI's credentials, which both Go SDKs share, +// so WithLegacyHint returns it as is. +type loginError struct { + error +} + +func (e loginError) Unwrap() error { + return e.error +} diff --git a/libs/sdkgo/options.go b/libs/sdkgo/options.go index aab1ea1454d..c638df86c0c 100644 --- a/libs/sdkgo/options.go +++ b/libs/sdkgo/options.go @@ -42,6 +42,8 @@ func Options(cfg *config.Config) ([]client.Option, error) { return nil, err } return append(ConfigOptions(cfg), + // Takes the place of ConfigOptions' credentials, so a failed login is a loginError. + client.WithCredentials(configCredentials{cfg: cfg, markLoginErrors: true}), client.WithHTTPClient(httpClient), // The classic client bounds each attempt and the retry window but not a whole call, so // sdk-go's call timeout, which would cut a retry window longer than it, is turned off. diff --git a/libs/sdkgo/selector.go b/libs/sdkgo/selector.go index 06f27564388..05922de48a5 100644 --- a/libs/sdkgo/selector.go +++ b/libs/sdkgo/selector.go @@ -54,8 +54,8 @@ const legacyHint = "Set " + EnvVar + "=" + legacySDK + " to use the previous Go // WithLegacyHint returns err with a hint to switch back to the legacy SDK when err is an // internal error of the modular SDK, such as a response it could not decode. An API error, a -// failed request and a cancellation come from the server, the network or the caller, so they -// are returned as is. +// failed request, a failed login of a client built with Options and a cancellation come from +// the server, the network, the CLI's credentials or the caller, so they are returned as is. func WithLegacyHint(err error) error { if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return err @@ -66,6 +66,9 @@ func WithLegacyHint(err error) error { if _, ok := errors.AsType[*url.Error](err); ok { return err } + if _, ok := errors.AsType[loginError](err); ok { + return err + } return modularError{err: err} } diff --git a/libs/sdkgo/selector_test.go b/libs/sdkgo/selector_test.go index 22bc8986a45..ce888145a6c 100644 --- a/libs/sdkgo/selector_test.go +++ b/libs/sdkgo/selector_test.go @@ -13,7 +13,11 @@ import ( "github.com/databricks/cli/libs/env" "github.com/databricks/databricks-sdk-go" + "github.com/databricks/databricks-sdk-go/config" + "github.com/databricks/databricks-sdk-go/config/credentials" "github.com/databricks/sdk-go/core/apierr" + files "github.com/databricks/sdk-go/files/v2" + "github.com/databricks/sdk-go/options/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -155,3 +159,55 @@ func TestWithLegacyHintOnUndecodableResponse(t *testing.T) { assert.ErrorAs(t, err, &syntaxErr) assert.ErrorContains(t, err, "\n\nSet DATABRICKS_CLI_GO_SDK=legacy to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues.") } + +// failingLogin is a classic credentials strategy whose every request fails to authenticate +// with err, as an expired login does. +type failingLogin struct { + err error +} + +func (f failingLogin) Name() string { + return "failing-login" +} + +func (f failingLogin) Configure(context.Context, *config.Config) (credentials.CredentialsProvider, error) { + return credentials.CredentialsProviderFn(func(*http.Request) error { return f.err }), nil +} + +// createWithFailingLogin returns the error of a files/v2 call through a client built with +// options from a config whose login fails with errLogin. +func createWithFailingLogin(t *testing.T, options func(*config.Config) ([]client.Option, error), errLogin error) error { + server := newTestServer(t) + cfg := &config.Config{Host: server.URL, Credentials: failingLogin{err: errLogin}} + opts, err := options(cfg) + require.NoError(t, err) + c, err := files.NewClient(t.Context(), opts...) + require.NoError(t, err) + + requests := server.record(func() { err = createModular(t.Context(), c) }, created) + assert.Empty(t, requests) + return err +} + +func TestWithLegacyHintKeepsLoginErrorsOfOptions(t *testing.T) { + errLogin := errors.New("refresh token is invalid") + err := createWithFailingLogin(t, Options, errLogin) + assert.ErrorIs(t, err, errLogin) + assert.EqualError(t, err, errLogin.Error()) + assert.Equal(t, err, WithLegacyHint(err)) +} + +func TestConfigOptionsReturnLoginErrorsUnchanged(t *testing.T) { + // The files client builds its client with ConfigOptions and returns the error of + // config.Authenticate itself. + errLogin := errors.New("refresh token is invalid") + cfg := &config.Config{Host: newTestServer(t).URL, Credentials: failingLogin{err: errLogin}} + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, cfg.Host, nil) + require.NoError(t, err) + require.Same(t, errLogin, cfg.Authenticate(req)) + + err = createWithFailingLogin(t, func(cfg *config.Config) ([]client.Option, error) { + return ConfigOptions(cfg), nil + }, errLogin) + assert.Same(t, errLogin, err) +} From 8ee2de56fee7a41632c9cd9e63b7c0bbfbe9b800 Mon Sep 17 00:00:00 2001 From: "parth.bansal" Date: Wed, 2 Dec 2026 18:34:05 +0000 Subject: [PATCH 8/9] sdkgo: say in Options' doc that it replaces the credentials of ConfigOptions Co-authored-by: Isaac Signed-off-by: parth.bansal --- libs/sdkgo/options.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/libs/sdkgo/options.go b/libs/sdkgo/options.go index c638df86c0c..8833a3dc6be 100644 --- a/libs/sdkgo/options.go +++ b/libs/sdkgo/options.go @@ -35,14 +35,16 @@ func ConfigOptions(cfg *config.Config) []client.Option { // Options returns ConfigOptions plus an HTTP client that sends every request through a classic // SDK API client built from cfg, so that each request gets the classic path's retries, // per-request timeout, rate limit, User-Agent and --debug logs. Clients built from the same -// options share one rate limit, as the services of one classic WorkspaceClient do. +// options share one rate limit, as the services of one classic WorkspaceClient do. Their +// credentials return a failed login as a loginError, which WithLegacyHint returns as is. func Options(cfg *config.Config) ([]client.Option, error) { httpClient, err := newHTTPClient(cfg) if err != nil { return nil, err } return append(ConfigOptions(cfg), - // Takes the place of ConfigOptions' credentials, so a failed login is a loginError. + // sdk-go keeps the last WithCredentials, so this replaces the credentials of + // ConfigOptions. It must stay after ConfigOptions(cfg). client.WithCredentials(configCredentials{cfg: cfg, markLoginErrors: true}), client.WithHTTPClient(httpClient), // The classic client bounds each attempt and the retry window but not a whole call, so From ebca03b5b8c7ef6e4fab6645da35e61825768030 Mon Sep 17 00:00:00 2001 From: "parth.bansal" Date: Wed, 2 Dec 2026 21:55:30 +0000 Subject: [PATCH 9/9] sdkgo: remove the legacy-SDK hint WithLegacyHint added "Set DATABRICKS_CLI_GO_SDK=legacy to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues." to modular-SDK errors. The owner wants it gone, since telling a user to switch SDKs causes more problems than it solves: it also reached errors that switching can't fix, such as a failed login. Nothing calls it yet. This removes WithLegacyHint, modularError and legacyHint with their tests, and drops the change that kept the hint off login failures, so credentials.go and options.go match main again. Co-authored-by: Isaac Signed-off-by: parth.bansal --- libs/sdkgo/credentials.go | 16 ----- libs/sdkgo/options.go | 6 +- libs/sdkgo/selector.go | 38 ----------- libs/sdkgo/selector_test.go | 125 ------------------------------------ 4 files changed, 1 insertion(+), 184 deletions(-) diff --git a/libs/sdkgo/credentials.go b/libs/sdkgo/credentials.go index 67158602166..f3884a1826e 100644 --- a/libs/sdkgo/credentials.go +++ b/libs/sdkgo/credentials.go @@ -15,9 +15,6 @@ import ( // already resolved instead of re-reading a profile. type configCredentials struct { cfg *config.Config - - // markLoginErrors makes AuthHeaders return a failure to authenticate as a loginError. - markLoginErrors bool } // Name reports the resolved auth mechanism (e.g. "pat", "oauth-m2m"), which an @@ -40,9 +37,6 @@ func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, e return nil, err } if err := c.cfg.Authenticate(req); err != nil { - if c.markLoginErrors { - return nil, loginError{err} - } return nil, err } @@ -54,13 +48,3 @@ func (c configCredentials) AuthHeaders(ctx context.Context) ([]sdkauth.Header, e } return headers, nil } - -// loginError is a failure to authenticate with the CLI's credentials, which both Go SDKs share, -// so WithLegacyHint returns it as is. -type loginError struct { - error -} - -func (e loginError) Unwrap() error { - return e.error -} diff --git a/libs/sdkgo/options.go b/libs/sdkgo/options.go index 8833a3dc6be..aab1ea1454d 100644 --- a/libs/sdkgo/options.go +++ b/libs/sdkgo/options.go @@ -35,17 +35,13 @@ func ConfigOptions(cfg *config.Config) []client.Option { // Options returns ConfigOptions plus an HTTP client that sends every request through a classic // SDK API client built from cfg, so that each request gets the classic path's retries, // per-request timeout, rate limit, User-Agent and --debug logs. Clients built from the same -// options share one rate limit, as the services of one classic WorkspaceClient do. Their -// credentials return a failed login as a loginError, which WithLegacyHint returns as is. +// options share one rate limit, as the services of one classic WorkspaceClient do. func Options(cfg *config.Config) ([]client.Option, error) { httpClient, err := newHTTPClient(cfg) if err != nil { return nil, err } return append(ConfigOptions(cfg), - // sdk-go keeps the last WithCredentials, so this replaces the credentials of - // ConfigOptions. It must stay after ConfigOptions(cfg). - client.WithCredentials(configCredentials{cfg: cfg, markLoginErrors: true}), client.WithHTTPClient(httpClient), // The classic client bounds each attempt and the retry window but not a whole call, so // sdk-go's call timeout, which would cut a retry window longer than it, is turned off. diff --git a/libs/sdkgo/selector.go b/libs/sdkgo/selector.go index 05922de48a5..797571e4c2e 100644 --- a/libs/sdkgo/selector.go +++ b/libs/sdkgo/selector.go @@ -2,13 +2,10 @@ package sdkgo import ( "context" - "errors" "fmt" - "net/url" "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/log" - "github.com/databricks/sdk-go/core/apierr" ) // EnvVar names the environment variable that selects the Go SDK of the commands that support @@ -48,38 +45,3 @@ func useModular(ctx context.Context, group string, defaults map[string]bool) (bo log.Debugf(ctx, "Using the %s Go SDK for %s commands", sdk, group) return modular, nil } - -// legacyHint follows the text of an internal error of the modular Go SDK. -const legacyHint = "Set " + EnvVar + "=" + legacySDK + " to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues." - -// WithLegacyHint returns err with a hint to switch back to the legacy SDK when err is an -// internal error of the modular SDK, such as a response it could not decode. An API error, a -// failed request, a failed login of a client built with Options and a cancellation come from -// the server, the network, the CLI's credentials or the caller, so they are returned as is. -func WithLegacyHint(err error) error { - if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - return err - } - if _, ok := errors.AsType[*apierr.APIError](err); ok { - return err - } - if _, ok := errors.AsType[*url.Error](err); ok { - return err - } - if _, ok := errors.AsType[loginError](err); ok { - return err - } - return modularError{err: err} -} - -type modularError struct { - err error -} - -func (e modularError) Error() string { - return e.err.Error() + "\n\n" + legacyHint -} - -func (e modularError) Unwrap() error { - return e.err -} diff --git a/libs/sdkgo/selector_test.go b/libs/sdkgo/selector_test.go index ce888145a6c..41b338287ff 100644 --- a/libs/sdkgo/selector_test.go +++ b/libs/sdkgo/selector_test.go @@ -1,23 +1,11 @@ package sdkgo import ( - "context" - "encoding/json" - "errors" - "fmt" "maps" - "net/http" - "net/url" "slices" "testing" "github.com/databricks/cli/libs/env" - "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/config" - "github.com/databricks/databricks-sdk-go/config/credentials" - "github.com/databricks/sdk-go/core/apierr" - files "github.com/databricks/sdk-go/files/v2" - "github.com/databricks/sdk-go/options/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -98,116 +86,3 @@ func TestUseModularUsesDefaultTable(t *testing.T) { assert.Equal(t, modularByDefault[group], got, group) } } - -func TestWithLegacyHint(t *testing.T) { - var syntaxErr *json.SyntaxError - decodeErr := json.Unmarshal([]byte("not json"), &struct{}{}) - require.ErrorAs(t, decodeErr, &syntaxErr) - apiErr := apierr.FromHTTPError(http.StatusNotFound, http.Header{}, []byte(`{"error_code": "NOT_FOUND", "message": "no such file"}`)) - urlErr := &url.Error{Op: "Post", URL: "https://example.test", Err: errors.New("connection refused")} - - testCases := []struct { - name string - err error - want error - }{ - { - name: "no error", - }, - { - name: "API error", - err: apiErr, - want: apiErr, - }, - { - name: "wrapped API error", - err: fmt.Errorf("create: %w", apiErr), - want: fmt.Errorf("create: %w", apiErr), - }, - { - name: "failed request", - err: urlErr, - want: urlErr, - }, - { - name: "cancellation", - err: context.Canceled, - want: context.Canceled, - }, - { - name: "decoding error", - err: decodeErr, - want: modularError{err: decodeErr}, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, WithLegacyHint(tc.err)) - }) - } -} - -func TestWithLegacyHintOnUndecodableResponse(t *testing.T) { - server := newTestServer(t) - _, c := clients(t, server, &databricks.Config{}) - - var err error - server.record(func() { err = createModular(t.Context(), c) }, respond(http.StatusOK, nil, "not json")) - - var syntaxErr *json.SyntaxError - err = WithLegacyHint(err) - assert.ErrorAs(t, err, &syntaxErr) - assert.ErrorContains(t, err, "\n\nSet DATABRICKS_CLI_GO_SDK=legacy to use the previous Go SDK, and report the issue at https://github.com/databricks/cli/issues.") -} - -// failingLogin is a classic credentials strategy whose every request fails to authenticate -// with err, as an expired login does. -type failingLogin struct { - err error -} - -func (f failingLogin) Name() string { - return "failing-login" -} - -func (f failingLogin) Configure(context.Context, *config.Config) (credentials.CredentialsProvider, error) { - return credentials.CredentialsProviderFn(func(*http.Request) error { return f.err }), nil -} - -// createWithFailingLogin returns the error of a files/v2 call through a client built with -// options from a config whose login fails with errLogin. -func createWithFailingLogin(t *testing.T, options func(*config.Config) ([]client.Option, error), errLogin error) error { - server := newTestServer(t) - cfg := &config.Config{Host: server.URL, Credentials: failingLogin{err: errLogin}} - opts, err := options(cfg) - require.NoError(t, err) - c, err := files.NewClient(t.Context(), opts...) - require.NoError(t, err) - - requests := server.record(func() { err = createModular(t.Context(), c) }, created) - assert.Empty(t, requests) - return err -} - -func TestWithLegacyHintKeepsLoginErrorsOfOptions(t *testing.T) { - errLogin := errors.New("refresh token is invalid") - err := createWithFailingLogin(t, Options, errLogin) - assert.ErrorIs(t, err, errLogin) - assert.EqualError(t, err, errLogin.Error()) - assert.Equal(t, err, WithLegacyHint(err)) -} - -func TestConfigOptionsReturnLoginErrorsUnchanged(t *testing.T) { - // The files client builds its client with ConfigOptions and returns the error of - // config.Authenticate itself. - errLogin := errors.New("refresh token is invalid") - cfg := &config.Config{Host: newTestServer(t).URL, Credentials: failingLogin{err: errLogin}} - req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, cfg.Host, nil) - require.NoError(t, err) - require.Same(t, errLogin, cfg.Authenticate(req)) - - err = createWithFailingLogin(t, func(cfg *config.Config) ([]client.Option, error) { - return ConfigOptions(cfg), nil - }, errLogin) - assert.Same(t, errLogin, err) -}