diff --git a/acceptance/cmd/workspace/export-dir-dashboard/imported.lvdash.json b/acceptance/cmd/workspace/export-dir-dashboard/imported.lvdash.json new file mode 100644 index 00000000000..240c3154233 --- /dev/null +++ b/acceptance/cmd/workspace/export-dir-dashboard/imported.lvdash.json @@ -0,0 +1 @@ +{"pages":[{"name":"imported","displayName":"Imported Page"}]} diff --git a/acceptance/cmd/workspace/export-dir-dashboard/output.txt b/acceptance/cmd/workspace/export-dir-dashboard/output.txt index 21c8b788853..71c3cd691b2 100644 --- a/acceptance/cmd/workspace/export-dir-dashboard/output.txt +++ b/acceptance/cmd/workspace/export-dir-dashboard/output.txt @@ -7,3 +7,53 @@ Exporting files from /Workspace/Users/[USERNAME]/export-dir-dashboard-[UNIQUE_NA Export complete >>> assert_exists.py [TEST_TMP_DIR]/export/export-dir-dashboard-[UNIQUE_NAME].lvdash.json + +>>> echo /Users/[USERNAME]/export-dir-dashboard-[UNIQUE_NAME]/export-dir-dashboard-[UNIQUE_NAME].lvdash.json +/Users/[USERNAME]/export-dir-dashboard-[UNIQUE_NAME]/export-dir-dashboard-[UNIQUE_NAME].lvdash.json + +=== Overwrite the dashboard with new content through the workspace import API, at the path Lakeview reports + +>>> [CLI] workspace import /Users/[USERNAME]/export-dir-dashboard-[UNIQUE_NAME]/export-dir-dashboard-[UNIQUE_NAME].lvdash.json --file imported.lvdash.json --format AUTO --overwrite + +=== The workspace object still names the same dashboard, under both spellings of its path + +>>> [CLI] workspace get-status /Users/[USERNAME]/export-dir-dashboard-[UNIQUE_NAME]/export-dir-dashboard-[UNIQUE_NAME].lvdash.json +{ + "object_type": "DASHBOARD", + "resource_id": "[DASHBOARD_ID]" +} + +>>> [CLI] workspace get-status /Workspace/Users/[USERNAME]/export-dir-dashboard-[UNIQUE_NAME]/export-dir-dashboard-[UNIQUE_NAME].lvdash.json +{ + "object_type": "DASHBOARD", + "resource_id": "[DASHBOARD_ID]" +} + +=== The dashboard has the imported content + +>>> jq .serialized_dashboard | fromjson | [.pages[].name] after.json +[ + "imported" +] + +=== Compared with the create response, the import changed only etag and update_time + +>>> jq -n --slurpfile b created.json --slurpfile a after.json $b[0] as $b | $a[0] as $a | { + updated: ([$a | keys[] | . as $k | select(($b | has($k)) and $b[$k] != $a[$k])] - ["serialized_dashboard"]), + inserted: [$a | keys[] | . as $k | select($b | has($k) | not)], + deleted: ([$b | keys[] | . as $k | select($a | has($k) | not)] - ["warehouse_id"]) +} +{ + "updated": [ + "etag", + "update_time" + ], + "inserted": [], + "deleted": [] +} + +=== Creating a dashboard with the same name in the same folder is a conflict + +>>> contains.py 409 + +>>> contains.py ALREADY_EXISTS diff --git a/acceptance/cmd/workspace/export-dir-dashboard/script b/acceptance/cmd/workspace/export-dir-dashboard/script index febb56173c4..fdfa0aaf8c0 100644 --- a/acceptance/cmd/workspace/export-dir-dashboard/script +++ b/acceptance/cmd/workspace/export-dir-dashboard/script @@ -12,12 +12,13 @@ trap cleanup EXIT trace $CLI workspace mkdirs "$DASHBOARD_DIR" -dashboard_id=$($CLI lakeview create \ +$CLI lakeview create \ --display-name "$DASHBOARD_NAME" \ --warehouse-id "$TEST_DEFAULT_WAREHOUSE_ID" \ --serialized-dashboard "$(cat dashboard.lvdash.json)" \ --json "{\"parent_path\": \"$DASHBOARD_DIR\"}" \ - -o json | jq -r '.dashboard_id') + -o json > created.json +dashboard_id=$(jq -r '.dashboard_id' created.json) add_repl "$dashboard_id" DASHBOARD_ID mkdir -p "$TEST_TMP_DIR/export" @@ -27,3 +28,38 @@ trace $CLI workspace export-dir "$DASHBOARD_DIR" "$TEST_TMP_DIR/export" # drops an empty "layout": []), so the exported content is not byte-identical to # the input. Assert the dashboard was exported rather than diffing the content. trace assert_exists.py "$TEST_TMP_DIR/export/$DASHBOARD_NAME.lvdash.json" + +# Importing a .lvdash.json over a dashboard's path through the workspace import API updates +# that dashboard in place: bundle generate --existing-path and the direct engine's create +# recovery look a dashboard up by its file path, so the file must keep naming the same dashboard. +# Lakeview reports the path without the /Workspace prefix; both spellings name the same object. +DASHBOARD_PATH="$DASHBOARD_DIR/$DASHBOARD_NAME.lvdash.json" +LAKEVIEW_PATH=$(jq -r .path created.json) +trace echo "$LAKEVIEW_PATH" + +title "Overwrite the dashboard with new content through the workspace import API, at the path Lakeview reports" +trace $CLI workspace import "$LAKEVIEW_PATH" --file imported.lvdash.json --format AUTO --overwrite + +title "The workspace object still names the same dashboard, under both spellings of its path" +trace $CLI workspace get-status "$LAKEVIEW_PATH" | jq '{object_type, resource_id}' +trace $CLI workspace get-status "$DASHBOARD_PATH" | jq '{object_type, resource_id}' + +title "The dashboard has the imported content" +# Wait for the import to be visible: the etag changes on every write. +retry --until-not "$(jq -r .etag created.json)" $CLI lakeview get "$dashboard_id" > after.json +trace jq '.serialized_dashboard | fromjson | [.pages[].name]' after.json + +title "Compared with the create response, the import changed only etag and update_time" +# serialized_dashboard changed on purpose; the backend drops warehouse_id on some versions. +trace jq -n --slurpfile b created.json --slurpfile a after.json '$b[0] as $b | $a[0] as $a | { + updated: ([$a | keys[] | . as $k | select(($b | has($k)) and $b[$k] != $a[$k])] - ["serialized_dashboard"]), + inserted: [$a | keys[] | . as $k | select($b | has($k) | not)], + deleted: ([$b | keys[] | . as $k | select($a | has($k) | not)] - ["warehouse_id"]) +}' + +title "Creating a dashboard with the same name in the same folder is a conflict" +# Create recovery treats ALREADY_EXISTS and RESOURCE_ALREADY_EXISTS alike; the backend returns +# either, with wording that varies by version, so only the final status and the code are checked. +musterr $CLI lakeview create --display-name "$DASHBOARD_NAME" --serialized-dashboard "$(cat imported.lvdash.json)" --json "{\"parent_path\": \"$DASHBOARD_DIR\"}" --debug 2> LOG.conflict +grep '< HTTP/' LOG.conflict | tail -n 1 | trace contains.py ' 409' > /dev/null +trace contains.py 'ALREADY_EXISTS' < LOG.conflict > /dev/null diff --git a/acceptance/cmd/workspace/export-dir-dashboard/test.toml b/acceptance/cmd/workspace/export-dir-dashboard/test.toml index db3893d343c..3c39ad11156 100644 --- a/acceptance/cmd/workspace/export-dir-dashboard/test.toml +++ b/acceptance/cmd/workspace/export-dir-dashboard/test.toml @@ -5,6 +5,13 @@ Cloud = true # so cover it on Linux/macOS only. GOOS.windows = false +# Lakeview reads after a write can stay stale on cloud for longer than retry.py's ~2s +# default (5 attempts x 500ms), as in acceptance/bundle/resources/dashboards. +Env.RETRY_MAX_ATTEMPTS = "20" +Env.RETRY_INTERVAL_MS = "1000" + Ignore = [ "export", + "created.json", + "after.json", ] diff --git a/integration/assumptions/dashboard_assumptions_test.go b/integration/assumptions/dashboard_assumptions_test.go deleted file mode 100644 index 111482a6f81..00000000000 --- a/integration/assumptions/dashboard_assumptions_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package assumptions_test - -import ( - "encoding/base64" - "testing" - - "github.com/databricks/cli/integration/internal/acc" - "github.com/databricks/cli/internal/testutil" - "github.com/databricks/cli/libs/dyn" - "github.com/databricks/cli/libs/dyn/convert" - "github.com/databricks/cli/libs/dyn/merge" - "github.com/databricks/databricks-sdk-go/apierr" - "github.com/databricks/databricks-sdk-go/service/dashboards" - "github.com/databricks/databricks-sdk-go/service/workspace" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// Verify that importing a dashboard through the Workspace API retains the identity of the underying resource, -// as well as properties exclusively accessible through the dashboards API. -func TestDashboardAssumptions_WorkspaceImport(t *testing.T) { - ctx, wt := acc.WorkspaceTest(t) - - t.Parallel() - - dashboardName := "New Dashboard" - dashboardPayload := []byte(`{"pages":[{"name":"2506f97a","displayName":"New Page"}]}`) - warehouseId := testutil.GetEnvOrSkipTest(t, "TEST_DEFAULT_WAREHOUSE_ID") - - dir := acc.TemporaryWorkspaceDir(wt, "dashboard-assumptions-") - - dashboard, err := wt.W.Lakeview.Create(ctx, dashboards.CreateDashboardRequest{ - Dashboard: dashboards.Dashboard{ - DisplayName: dashboardName, - ParentPath: dir, - SerializedDashboard: string(dashboardPayload), - WarehouseId: warehouseId, - }, - }) - require.NoError(t, err) - t.Logf("Dashboard ID (per Lakeview API): %s", dashboard.DashboardId) - - // Overwrite the dashboard via the workspace API. - { - err := wt.W.Workspace.Import(ctx, workspace.Import{ - Format: workspace.ImportFormatAuto, - Path: dashboard.Path, - Content: base64.StdEncoding.EncodeToString(dashboardPayload), - Overwrite: true, - }) - require.NoError(t, err) - } - - // Cross-check consistency with the workspace object. - { - obj, err := wt.W.Workspace.GetStatusByPath(ctx, dashboard.Path) - require.NoError(t, err) - - // Confirm that the resource ID included in the response is equal to the dashboard ID. - require.Equal(t, dashboard.DashboardId, obj.ResourceId) - t.Logf("Dashboard ID (per workspace object status): %s", obj.ResourceId) - } - - // Try to overwrite the dashboard via the Lakeview API (and expect failure). - { - _, err := wt.W.Lakeview.Create(ctx, dashboards.CreateDashboardRequest{ - Dashboard: dashboards.Dashboard{ - DisplayName: dashboardName, - ParentPath: dir, - SerializedDashboard: string(dashboardPayload), - }, - }) - // Lakeview returns the generic gRPC error_code ALREADY_EXISTS, not - // Databricks' RESOURCE_ALREADY_EXISTS, so the SDK unwraps to - // ErrAlreadyExists rather than ErrResourceAlreadyExists. Assert the - // common 409 parent to stay resilient to either code. - require.ErrorIs(t, err, apierr.ErrResourceConflict) - } - - // Retrieve the dashboard object and confirm that only select fields were updated by the import. - { - previousDashboard := dashboard - currentDashboard, err := wt.W.Lakeview.Get(ctx, dashboards.GetDashboardRequest{ - DashboardId: dashboard.DashboardId, - }) - require.NoError(t, err) - - // Convert the dashboard object to a [dyn.Value] to make comparison easier. - previous, err := convert.FromTyped(previousDashboard, dyn.NilValue) - require.NoError(t, err) - current, err := convert.FromTyped(currentDashboard, dyn.NilValue) - require.NoError(t, err) - - // Collect updated and deleted paths. - var updatedFieldPaths []string - var deletedFieldPaths []string - _, err = merge.Override(previous, current, merge.OverrideVisitor{ - VisitDelete: func(basePath dyn.Path, left dyn.Value) error { - deletedFieldPaths = append(deletedFieldPaths, basePath.String()) - return nil - }, - VisitInsert: func(basePath dyn.Path, right dyn.Value) (dyn.Value, error) { - assert.Fail(t, "unexpected insert operation") - return right, nil - }, - VisitUpdate: func(basePath dyn.Path, left, right dyn.Value) (dyn.Value, error) { - updatedFieldPaths = append(updatedFieldPaths, basePath.String()) - return right, nil - }, - }) - require.NoError(t, err) - - // etag and update_time always change after workspace import. serialized_dashboard and - // warehouse_id vary by Lakeview server version: observed on AWS staging but not GCP prod. - assert.Subset(t, updatedFieldPaths, []string{"etag", "update_time"}) - assert.Subset(t, []string{"etag", "update_time", "serialized_dashboard"}, updatedFieldPaths) - assert.Subset(t, []string{"warehouse_id"}, deletedFieldPaths) - } -} diff --git a/libs/testserver/dashboards.go b/libs/testserver/dashboards.go index 809849609c4..756a865e244 100644 --- a/libs/testserver/dashboards.go +++ b/libs/testserver/dashboards.go @@ -208,18 +208,9 @@ func (s *FakeWorkspace) DashboardUpdate(req Request) Response { } } updated := *dashboard - - // Bump etag on every write, matching cloud behavior. - prevEtag, err := strconv.Atoi(updated.Etag) - if err != nil { - return Response{ - Body: map[string]string{ - "message": "Invalid etag: " + updated.Etag, - }, - StatusCode: 400, - } + if resp, ok := updated.bumpEtag(); !ok { + return resp } - updated.Etag = strconv.Itoa(prevEtag + 1) if updateReq.SerializedDashboard != updated.InputSerializedDashboard { updated.InputSerializedDashboard = updateReq.SerializedDashboard @@ -378,3 +369,74 @@ func (s *FakeWorkspace) moveDashboardFile(oldPath, newPath, dashboardId string) s.files[entry.Info.Path] = entry } } + +// dashboardEntry finds the workspace object of a dashboard by the path Lakeview returns for it +// (Dashboard.Path, without the /Workspace prefix), which the real Workspace API accepts as well. +// Only dashboards are resolved this way. The caller must hold the lock. +func (s *FakeWorkspace) dashboardEntry(filePath string) (FileEntry, bool) { + if strings.HasPrefix(filePath, "/Workspace/") { + return FileEntry{}, false + } + entry, ok := s.files[path.Join("/Workspace", filePath)] + if !ok || entry.Info.ObjectType != workspace.ObjectTypeDashboard { + return FileEntry{}, false + } + return entry, true +} + +// bumpEtag advances the etag, as the cloud does on every write. ok is false, with the response to +// return, when the stored etag is not a number. +func (d *fakeDashboard) bumpEtag() (Response, bool) { + prevEtag, err := strconv.Atoi(d.Etag) + if err != nil { + return Response{ + Body: map[string]string{ + "message": "Invalid etag: " + d.Etag, + }, + StatusCode: 400, + }, false + } + d.Etag = strconv.Itoa(prevEtag + 1) + return Response{}, true +} + +// WorkspaceImportOverDashboard serves an AUTO-format /workspace/import with overwrite onto the +// .lvdash.json path of an existing dashboard. The real API updates that dashboard in place: the +// path keeps the dashboard's identity (get-status resource_id), and the import sets its +// serialized_dashboard, etag and update_time. ok is false when the request is not such an import. +func (s *FakeWorkspace) WorkspaceImportOverDashboard(filePath string, body []byte, overwrite bool) (Response, bool) { + if !overwrite { + return Response{}, false + } + filePath = path.Clean("/" + filePath) + + defer s.LockUnlock()() + + entry, ok := s.files[filePath] + if !ok { + entry, ok = s.dashboardEntry(filePath) + filePath = entry.Info.Path + } + if !ok || entry.Info.ObjectType != workspace.ObjectTypeDashboard { + return Response{}, false + } + dashboard, ok := s.Dashboards.ReadStrong(entry.Info.ResourceId) + if !ok { + return Response{ + StatusCode: http.StatusInternalServerError, + Body: fmt.Sprintf("internal error: no dashboard %s for workspace object %s", entry.Info.ResourceId, filePath), + }, true + } + updated := *dashboard + if resp, ok := updated.bumpEtag(); !ok { + return resp, true + } + updated.InputSerializedDashboard = string(body) + updated.SerializedDashboard = transformSerializedDashboard(string(body), "", "") + updated.UpdateTime = nextTimestamp() + s.Dashboards.Write(updated.DashboardId, &updated) + + entry.Data = []byte(updated.SerializedDashboard) + s.files[filePath] = entry + return Response{}, true +} diff --git a/libs/testserver/fake_workspace.go b/libs/testserver/fake_workspace.go index 2f26de954c8..9bd3639f755 100644 --- a/libs/testserver/fake_workspace.go +++ b/libs/testserver/fake_workspace.go @@ -731,6 +731,8 @@ func (s *FakeWorkspace) WorkspaceGetStatus(requestPath string, returnGitInfo boo info = dirInfo } else if entry, ok := s.files[cleaned]; ok { info = entry.Info + } else if entry, ok := s.dashboardEntry(cleaned); ok { + info = entry.Info } else { // Match the real Workspace API wording, which echoes the requested path. return Response{ diff --git a/libs/testserver/handlers.go b/libs/testserver/handlers.go index 46e762c0522..791b2b5b9b3 100644 --- a/libs/testserver/handlers.go +++ b/libs/testserver/handlers.go @@ -90,6 +90,9 @@ func workspaceImport(w *FakeWorkspace, form ImportForm) Response { if strings.HasSuffix(strings.ToLower(form.Path), ".zip") { return w.WorkspaceImportZipFolder(form.Path, form.Content, form.Overwrite) } + if resp, ok := w.WorkspaceImportOverDashboard(form.Path, form.Content, form.Overwrite); ok { + return resp + } if unsupported, ok := autoImportUnsupported(form.Path); ok { return unsupported }