diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index 794d5463d..5be950f87 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -2435,7 +2435,7 @@ const saveDocumentPath = 'mongoClusters.documentView.saveDocument'; const disconnectedDocument = { reason: 'userDisconnected', title: 'Disconnected', - detail: 'Connect from the connection tree, then click Retry.', + detail: 'Reconnect from the connection tree, then click Retry.', action: 'retry', } as const; const documentEditorName = 'Document Editor: Edit the document in JSON format'; @@ -2544,9 +2544,14 @@ const clusterDashboardScenarios = { default: clusterDashboardBase, disconnected: { ...clusterDashboardBase, + config: { ...fixtures.clusterDashboard.config, refreshIntervalMs: 2000 }, readiness: { ...clusterDashboardBase.readiness, content: ['stage0_inventory'] }, rpc: { ...clusterDashboardBase.rpc, + 'clusterDashboard.measureRtt': { + ...fixtures.clusterDashboard.rpc['clusterDashboard.measureRtt'], + holdReply: true, + }, 'clusterDashboard.recoverUnavailable': { type: 'mutation', results: [{ recovered: { text: 'Reconnected' } }], @@ -2575,6 +2580,11 @@ const clusterDashboardScenarios = { }, }, { action: 'waitFor', name: 'disconnected overlay', selector: '.disconnectedOverlay' }, + { + action: 'releaseReply', + name: 'deliver the old health poll', + path: 'clusterDashboard.measureRtt', + }, ], }, { @@ -2591,6 +2601,26 @@ const clusterDashboardScenarios = { attribute: 'value', expected: 'stage0', }, + { + kind: 'calls', + name: 'tree reconnect resumes the retained Dashboard through Retry', + path: 'clusterDashboard.recoverUnavailable', + count: 1, + checkInput: true, + input: { action: 'retry' }, + steps: [ + { + action: 'post', + name: 'reveal the Dashboard after reconnecting in the tree', + message: { type: 'clusterDashboard.retryAfterReconnect' }, + }, + { + action: 'waitFor', + name: 'Dashboard is enabled again', + selector: '.disconnectedOverlayBackground:not([inert])', + }, + ], + }, ], }, } as const satisfies Readonly>>; diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 593129955..a55a585c0 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -55,6 +55,9 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi the available credentials. Credential repair stays in the tree. Dismissing the dialog with its **X** exposes the existing contents for copying without resuming database operations. Trying another operation shows the dialog again. **Close view** asks for confirmation. +- After an explicit Disconnect, the tree offers **Reconnect**. If reconnecting automatically + opens the existing Dashboard for the same identity, it retries that view without replaying + an operation. Other retained views still require **Retry**. - A pending Dashboard delete confirmation does not survive Disconnect, even when the user reconnects as the same identity. Dashboard **Copy Collection** keeps a tree reference; **Paste Collection** stays in the tree and uses the current connection. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 8e6619d97..f52238187 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1581,8 +1581,9 @@ behave as today. **Outcome:** -- One teardown serves Disconnect, Remove and identity-changing credential updates. -- It is guarded by task conflicts and dirty editors. +- Disconnect and Remove share teardown. Saved edits share the task fence and resource cleanup, + but keep old views locked without asking to close them (decision 0018). +- Task conflicts block teardown or saving an edit. Dirty editors are checked before Close all. - It covers every per-cluster resource. - **What it guarantees** (F-22: closing a client cancels nothing already sent): - no **new** submission under the old binding after the latch is set; @@ -1636,9 +1637,8 @@ behave as today. the teardown. - **`latchForTeardown(clusterId, reason)`**, synchronous: recheck conflicts with `getConflictingTasks`, because a copy, export or import may have started while a prompt was open; on a conflict return - `false` and change nothing. Otherwise set the latch (C-6) and call `ClustersClient.invalidate`, which - increases the epoch, with no `await` in between, and return `true`. From here on no new task, lease or - client can start. + `false` and change nothing. Otherwise set the latch (C-6), which already increases the epoch, + with no `await` in between, and return `true`. From here on no new task, lease or client can start. - **`commitTeardown(clusterId, { reason, choice, dropCredentials })`**, which has no prompts: 1. Call `latchForTeardown` unless the caller already did (step 5). On a conflict, stop and inform the user; nothing has changed. @@ -1648,7 +1648,7 @@ behave as today. worker. **Playground:** stop the worker. The latch keeps both from respawning (F-15). 4. Close the client (`deleteClient`). Clear the Entra failure registry and `SchemaStore.clearCluster`. Clear the `CredentialCache` entry and `lastVerifiedIdentity` **only** when `dropCredentials` is - set (Remove). Disconnect keeps both (A3, decision 0011), so tree Connect and then tab Retry + set (Remove). Disconnect keeps both (A3, decision 0011), so tree Reconnect and then tab Retry can reuse the same identity. 5. Refresh the tree (T-2). - **Never touched:** VS Code auth sessions, the managed identity cache, the ARM cache. @@ -1675,7 +1675,9 @@ behave as today. - The setting never skips the unsaved-edits confirmation: when Close all is chosen and an editor is dirty, that confirmation still appears. - Skip the modal when no surfaces are registered. - - Add a disconnected cluster node child action, "Connect" (T-2). It clears the latch and connects. + - Add a disconnected cluster node child action, "Reconnect" (T-2). Check the `userDisconnected` + latch before reusing cached credentials when building the children. The action clears only + that latch and refreshes the node without changing its ID; normal expansion connects. 4. **Remove Connection and folder deletion.** - Remove Connection: teardown with reason `connectionRemoved` and `dropCredentials: true`, then delete the stored connection and clear the schema, as today. Keep the existing confirmation. @@ -1711,7 +1713,7 @@ behave as today. cluster is not blocked; Disconnect succeeds once the task is done or stopped; - a token response that arrives after Disconnect is ignored; - Reconnect uses the current credentials and cloud settings; -- after Disconnect, tree Connect followed by tab Retry succeeds without the tree reloading +- after Disconnect, tree Reconnect followed by tab Retry succeeds without the tree reloading credentials and without a prompt (native, Entra and discovery with a typed password); after Remove, the `CredentialCache` entry and `lastVerifiedIdentity` are gone; - Remove reuses the same teardown; @@ -1737,6 +1739,42 @@ behave as today. **Progress:** +- **CP-4 verdict:** Opus 5.5 approved the teardown order, T-2 and A5 at about 85% confidence. + Register tasks and acquire export/import leases synchronously against the latch. Take a lease + before client resolution, release it in `finally`, and include it in folder-delete conflict + queries. Recheck conflicts immediately before latching; use the epoch bump already in + `ClustersClient.latch`. For saved edits, keep the fence through persistence and retirement, + then restore only the applicable prior hold. Enforce retirement on the host as well as in the + dialog: a password-only edit does not change the fingerprint. The proposed per-cluster + generation watermark is an implementation candidate to validate in the saved-edit slice, + not a new public contract. No operator decision is needed for the lease slice. +- **WI-7 S1:** Import and export hold a collection lease from client resolution through + completion. Task admission checks the same latch as client startup. Existing conflict queries + see leases, including the folder-delete check. The task, transfer and Dashboard-bound command + test suites passed together (18 tests). +- **WI-7 S2a:** Disconnect now checks task conflicts and dirty views before teardown, with a + synchronous conflict recheck before latching. It stops matching Shell and Playground workers, + keeps credentials and the verified identity, and refreshes the same tree node with one + **Connect** action. The integrated build and 225 focused tests passed. Remove and saved edits + are not wired into teardown yet. +- **WI-7 S2b:** Remove and folder deletion keep their existing deletion confirmation and share + one tab choice for the affected connections. The batch rechecks and fences the entire set + before disposal or deletion. A failed storage delete leaves the surviving connection + disconnected rather than stuck in the removed state. Build and 30 focused tests passed. +- **WI-7 S3:** The save fence reports a retryable update-in-progress state; only a changed + stored value permanently retires the older generations. This also covers password-only and + partial secret writes without adding passwords to the fingerprint. Existing views remain + copyable. Same-settings reconnect can still follow a newer generation. Build and 196 + focused tests passed. +- **OP-5 (`1.1.1-alpha.4`):** The operator reported that Keep open, Close all with a dirty + draft, Remove, and the saved-edit lock passed. Disconnect during import or export was + not tested live; it is checked in the real transfer-lease and teardown preflight paths + by automated tests. Operator feedback: label the tree action **Reconnect**, use the + default Fluent layout with an instant backdrop, and clarify that an old view is bound + to its previous connection settings. +- **PR6 review:** The operator kept the single dirty check at **Close all** confirmation + ([review thread](https://github.com/microsoft/vscode-documentdb/pull/1130#discussion_r4694258852)). + In a batch removal, a view edited after that check still closes; there is no second prompt. - **Carry-forward from WI-4d:** An explicit Update Credentials that changes the tenant must replace or clear the old verified Entra identity so the next connect can use the saved tenant (decision 0011). Automatic reconnect remains pinned until that explicit update. @@ -1756,9 +1794,9 @@ one loop. of a failed command long enough to classify it. A terminal kind (auth, closed client) is rethrown so that `runWithClient` returns `unavailable`. An unsupported command, such as `serverStatus` on some servers, stays an ordinary partial sample with its entry in `errors`. -2. The webview poll effect depends on the overlay state: it stops on `unavailable` or on a `disable` - message, and starts again after Reconnect. React's effect cleanup keeps it to one loop; no extra loop - token. +2. The webview poll effect stops on `unavailable` or a `disable` message, even when the dialog is + dismissed to copy contents. It starts again only after Retry succeeds. React's effect cleanup + keeps it to one loop; no extra loop token. 3. A ping that resolves while the overlay shows is ignored (the WI-6 webview rule), so it cannot clear the overlay. 4. Visibility pause and backoff are the rest of #1091. Do them here only if they are trivial; otherwise @@ -1775,6 +1813,12 @@ one loop. **Progress:** +- The Dashboard polls with a background-only binding. Auth and closed-client errors from + inside the sampler return an unavailable result; unsupported `serverStatus` still returns a + partial sample. Build and 131 focused tests passed. The browser fixture showed no polls + during disconnect, copy mode or reveal; Retry restarted one loop. A held ping released + after disconnect did not clear the dialog. + --- ## WI-9: Token renewal telemetry (PR 7) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md index d96539af2..a9feb8ed4 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md @@ -543,15 +543,15 @@ only), so it is not tested. optional WI-4 test hook may shorten this during development. The release check uses a real wait at least once. -| # | Scenario | Steps | Pass when | -| ---- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| OT-1 | **Entra, long idle, work open** | Connect with Entra. Open a Collection View with filter, sort and projection, on page 2. Open a Document View with an unsaved edit. Open the Cluster Dashboard and a shell. Wait ≥ 2 h. Then refresh the tree, run the query, go to the next page, save the document, and run a command in the shell. | Everything works. No sign-in prompt, and no error that needs a click. Text and edits are kept. (No re-run and no out-of-date notice: decision 0010.) | -| OT-2 | **Entra, silent renewal impossible** | With the OT-1 surfaces open, sign out of the account in the Accounts menu (or revoke sessions in Entra). Run the query. Dismiss the prompt if one appears. Wait 5 min. Then click **Sign in again** and pick the same account. | The action fails once and offers **Sign in again**. The tabs show "sign-in expired" with their content kept. No modal appears on its own, and nothing prompts again after a dismissal. After signing in, the tabs re-enable and the unsaved edit saves. | -| OT-3 | **Changed connection details** | (a) With a Native tab open, save a different user through Update Credentials. (b) Repeat with a password-only change for the same user. (c) Entra: in OT-2, sign in again with a different account. OP-5 checks the pushed lock on saved edits (decision 0018). | (a) and (b): no tab-choice prompt; the old view immediately offers **Close view** only, with contents still copyable. (c): the old tab cannot run under the new account. Open a new view from the tree. | -| OT-4 | **Native, idle and network drop** | Native connection with tabs open. Turn the network off for 2 min, or put the machine to sleep for ≥ 30 min, then restore it. Run a query, refresh the tree, save a document. Also try an insert while offline. | The operations work after restoring, at most after one Retry. The offline insert is reported as failed or unknown and is **not** replayed. | -| OT-5 | **RU (key), idle and key rotation** | Open the RU cluster through Discovery, with tabs open. Wait ≥ 2 h and run a query. Then regenerate the primary key in the portal and run a query again. | After the wait: it works. After rotation: one clear failure with an action. The action reconnects with the new key. No endless retry. | -| OT-6 | **Azure discovery, long idle** | Expand a subscription in vCore and RU Discovery. Wait ≥ 2 h. Expand a cluster, connect, and run **Diagnose connection**. Then sign out of Azure and run Diagnose again. | It works without refreshing the provider root. When signed out, the diagnosis says **"Azure sign-in needed"**, not "Azure details unavailable". | -| OT-7 | **Disconnect** | With a Collection View, a dirty Document View, a shell and a playground open: Disconnect and choose **Keep open (disabled)**. Reconnect in the tree, then click **Retry** in the tab. Repeat with **Close all**. Then use Remove Connection. | Keep open: disabled with the reason and content kept; Retry resumes only after tree reconnect with the same identity. Close all: the dirty editor asks before it closes. The shell prints "Disconnected". The refreshed node offers **Connect**. Remove behaves like Disconnect plus delete. | +| # | Scenario | Steps | Pass when | +| ---- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| OT-1 | **Entra, long idle, work open** | Connect with Entra. Open a Collection View with filter, sort and projection, on page 2. Open a Document View with an unsaved edit. Open the Cluster Dashboard and a shell. Wait ≥ 2 h. Then refresh the tree, run the query, go to the next page, save the document, and run a command in the shell. | Everything works. No sign-in prompt, and no error that needs a click. Text and edits are kept. (No re-run and no out-of-date notice: decision 0010.) | +| OT-2 | **Entra, silent renewal impossible** | With the OT-1 surfaces open, sign out of the account in the Accounts menu (or revoke sessions in Entra). Run the query. Dismiss the prompt if one appears. Wait 5 min. Then click **Sign in again** and pick the same account. | The action fails once and offers **Sign in again**. The tabs show "sign-in expired" with their content kept. No modal appears on its own, and nothing prompts again after a dismissal. After signing in, the tabs re-enable and the unsaved edit saves. | +| OT-3 | **Changed connection details** | (a) With a Native tab open, save a different user through Update Credentials. (b) Repeat with a password-only change for the same user. (c) Entra: in OT-2, sign in again with a different account. OP-5 checks the pushed lock on saved edits (decision 0018). | (a) and (b): no tab-choice prompt; the old view immediately offers **Close view** only, with contents still copyable. (c): the old tab cannot run under the new account. Open a new view from the tree. | +| OT-4 | **Native, idle and network drop** | Native connection with tabs open. Turn the network off for 2 min, or put the machine to sleep for ≥ 30 min, then restore it. Run a query, refresh the tree, save a document. Also try an insert while offline. | The operations work after restoring, at most after one Retry. The offline insert is reported as failed or unknown and is **not** replayed. | +| OT-5 | **RU (key), idle and key rotation** | Open the RU cluster through Discovery, with tabs open. Wait ≥ 2 h and run a query. Then regenerate the primary key in the portal and run a query again. | After the wait: it works. After rotation: one clear failure with an action. The action reconnects with the new key. No endless retry. | +| OT-6 | **Azure discovery, long idle** | Expand a subscription in vCore and RU Discovery. Wait ≥ 2 h. Expand a cluster, connect, and run **Diagnose connection**. Then sign out of Azure and run Diagnose again. | It works without refreshing the provider root. When signed out, the diagnosis says **"Azure sign-in needed"**, not "Azure details unavailable". | +| OT-7 | **Disconnect** | With a Collection View, a dirty Document View, a shell and a playground open: Disconnect and choose **Keep open (disabled)**. Use **Reconnect** in the tree, then **Retry** in the tab. Repeat with **Close all**. Then use Remove Connection. | Keep open: disabled with the reason and content kept. After same-identity reconnect, the auto-opened Dashboard resumes and other views offer **Retry**. Close all: the dirty editor asks before it closes. The shell prints "Disconnected". Remove disconnects and deletes the saved connection. | **After release** (telemetry, operator with Kusto access): run the WI-9 queries on the pre-release cohort. diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 1bc9cabc6..4d4e927f2 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -331,6 +331,7 @@ "A client ID uses only 0-9, a-f, and dashes, like {0}.": "A client ID uses only 0-9, a-f, and dashes, like {0}.", "A collection with the name \"{0}\" already exists": "A collection with the name \"{0}\" already exists", "A configured TLS exception allowed the connection despite a certificate verification problem.": "A configured TLS exception allowed the connection despite a certificate verification problem.", + "A connection is already being updated or removed. Try again when it finishes.": "A connection is already being updated or removed. Try again when it finishes.", "A connection name is required.": "A connection name is required.", "A connection to the same host with the same authentication settings already exists.": "A connection to the same host with the same authentication settings already exists.", "A connection with the same username and host already exists.": "A connection with the same username and host already exists.", @@ -724,9 +725,11 @@ "Clock difference detected": "Clock difference detected", "Clock offset": "Clock offset", "Close": "Close", + "Close all": "Close all", "Close this view and add the credential again.": "Close this view and add the credential again.", "Close this view?": "Close this view?", "Close view": "Close view", + "Closing these tabs will discard their unsaved changes.": "Closing these tabs will discard their unsaved changes.", "Closing this view discards unsaved changes.": "Closing this view discards unsaved changes.", "Closing…": "Closing…", "Cluster": "Cluster", @@ -870,6 +873,7 @@ "Connection successful, but 1 check failed": "Connection successful, but 1 check failed", "Connection successful, but 1 check needs attention": "Connection successful, but 1 check needs attention", "Connection timed out": "Connection timed out", + "Connection update in progress": "Connection update in progress", "Connection updated successfully.": "Connection updated successfully.", "Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.": "Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.", "Connection works, but sign-in is required": "Connection works, but sign-in is required", @@ -952,6 +956,7 @@ "Could not find parent folder.": "Could not find parent folder.", "Could not find the Azure Resource Groups extension": "Could not find the Azure Resource Groups extension", "Could not find unique name for new file.": "Could not find unique name for new file.", + "Could not finish closing the connection.": "Could not finish closing the connection.", "Could not follow the DocumentDB Local container logs: {0}": "Could not follow the DocumentDB Local container logs: {0}", "Could not list the collections of \"{database}\": {reason}": "Could not list the collections of \"{database}\": {reason}", "Could not load indexes.": "Could not load indexes.", @@ -964,6 +969,7 @@ "Could not save the report: {0}": "Could not save the report: {0}", "Could not show the report: {0}": "Could not show the report: {0}", "Could not sign in again.": "Could not sign in again.", + "Could not verify the saved connection settings.": "Could not verify the saved connection settings.", "Counting documents in the source collection...": "Counting documents in the source collection...", "Counting source indexes…": "Counting source indexes…", "Coverage and limits": "Coverage and limits", @@ -1015,7 +1021,6 @@ "Credentials missing": "Credentials missing", "Credentials rejected by the cluster": "Credentials rejected by the cluster", "Credentials updated successfully.": "Credentials updated successfully.", - "Credentials updated. New connections will use them. Open shells for '{cluster}' keep their current connection until you close them.": "Credentials updated. New connections will use them. Open shells for '{cluster}' keep their current connection until you close them.", "Custom cloud": "Custom cloud", "Custom tag": "Custom tag", "Daemon architecture": "Daemon architecture", @@ -1109,8 +1114,13 @@ "Disable TLS/SSL (Not recommended)": "Disable TLS/SSL (Not recommended)", "Disable TLS/SSL checks when connecting.": "Disable TLS/SSL checks when connecting.", "Disabled": "Disabled", + "Discard changes": "Discard changes", "Discard the pasted input.": "Discard the pasted input.", + "Discard unsaved document changes?": "Discard unsaved document changes?", + "Disconnect": "Disconnect", "Disconnect and connect this playground to a different database?": "Disconnect and connect this playground to a different database?", + "disconnect this connection": "disconnect this connection", + "Disconnect?": "Disconnect?", "Disconnected": "Disconnected", "Discovery plugin error: clusterId \"{0}\" must start with provider ID \"{1}\". Plugin \"{2}\" must prefix clusterId with its provider ID.": "Discovery plugin error: clusterId \"{0}\" must start with provider ID \"{1}\". Plugin \"{2}\" must prefix clusterId with its provider ID.", "Discovery Plugins: {0}": "Discovery Plugins: {0}", @@ -1758,6 +1768,7 @@ "JSON results view: Read-only display of query results in JSON format": "JSON results view: Read-only display of query results in JSON format", "JSON View": "JSON View", "Keep one tls option with the value required by your cluster.": "Keep one tls option with the value required by your cluster.", + "Keep open (disabled)": "Keep open (disabled)", "Keep the existing data": "Keep the existing data", "Keep validation on": "Keep validation on", "Keep-alive timeout exceeded": "Keep-alive timeout exceeded", @@ -2198,6 +2209,7 @@ "Open setup": "Open setup", "Open shell": "Open shell", "Open Shell": "Open Shell", + "Open shells are still using the previous connection settings.": "Open shells are still using the previous connection settings.", "Open the VS Code Marketplace to learn more about \"{0}\"": "Open the VS Code Marketplace to learn more about \"{0}\"", "Open this query in Collection View": "Open this query in Collection View", "Open this query in Interactive Shell": "Open this query in Interactive Shell", @@ -2433,6 +2445,8 @@ "Recommendation: Modify Index": "Recommendation: Modify Index", "Recommended": "Recommended", "Recommended Index": "Recommended Index", + "Reconnect": "Reconnect", + "Reconnect from the connection tree, then click Retry.": "Reconnect from the connection tree, then click Retry.", "Reconnect now with the updated credentials": "Reconnect now with the updated credentials", "Reconnected": "Reconnected", "Reconnecting...": "Reconnecting...", @@ -2472,6 +2486,7 @@ "Remove $** from the parent path. It is added automatically.": "Remove $** from the parent path. It is added automatically.", "Remove field": "Remove field", "Remove kubeconfig source \"{0}\"?": "Remove kubeconfig source \"{0}\"?", + "Remove the connection?": "Remove the connection?", "Remove the DOCUMENTDB_DISABLE_SRV_FALLBACK environment variable, restart VS Code, then run the diagnosis again.": "Remove the DOCUMENTDB_DISABLE_SRV_FALLBACK environment variable, restart VS Code, then run the diagnosis again.", "Remove the port. SRV records supply the server ports.": "Remove the port. SRV records supply the server ports.", "Remove the unavailable compressor from the compressors option, or put zlib first.": "Remove the unavailable compressor from the compressors option, or put zlib first.", @@ -2974,6 +2989,7 @@ "The connection changed while it was opening. Try again.": "The connection changed while it was opening. Try again.", "The connection closed during the secure handshake, before a certificate arrived.": "The connection closed during the secure handshake, before a certificate arrived.", "The connection could not be prepared for diagnosis.": "The connection could not be prepared for diagnosis.", + "The connection could not be read from storage.": "The connection could not be read from storage.", "The connection details could not be read because Azure Resource Manager could not be reached from the host running these checks.": "The connection details could not be read because Azure Resource Manager could not be reached from the host running these checks.", "The connection details could not be read from Azure because the Azure sign-in is missing or expired. Connection diagnosis does not open sign-in.": "The connection details could not be read from Azure because the Azure sign-in is missing or expired. Connection diagnosis does not open sign-in.", "The connection details could not be read from Azure.": "The connection details could not be read from Azure.", @@ -2993,8 +3009,10 @@ "The connection string will not include the password": "The connection string will not include the password", "The connection succeeded, but the database-list request returned no databases visible to this user.": "The connection succeeded, but the database-list request returned no databases visible to this user.", "The connection succeeded, but the server denied the database-list request used by the extension.": "The connection succeeded, but the server denied the database-list request used by the extension.", + "The connection update may be incomplete. Check the saved settings before reconnecting.": "The connection update may be incomplete. Check the saved settings before reconnecting.", "The connection was closed while you were signing in.": "The connection was closed while you were signing in.", "The connection works, but these checks need attention:": "The connection works, but these checks need attention:", + "The connections to remove changed. Refresh the tree and try again.": "The connections to remove changed. Refresh the tree and try again.", "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".": "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".", "The container engine": "The container engine", "The container engine became unavailable during setup: {0}": "The container engine became unavailable during setup: {0}", @@ -3239,6 +3257,7 @@ "This Codespaces environment": "This Codespaces environment", "This connection has no connection string.": "This connection has no connection string.", "This connection is no longer in the tree. Close this view.": "This connection is no longer in the tree. Close this view.", + "This connection is unavailable. Reconnect from the tree to run this playground.": "This connection is unavailable. Reconnect from the tree to run this playground.", "This connection no longer exists. It may have been removed.": "This connection no longer exists. It may have been removed.", "This connection string asked for Microsoft Entra ID": "This connection string asked for Microsoft Entra ID", "This connection targets a local or private network host. TLS certificate validation:": "This connection targets a local or private network host. TLS certificate validation:", @@ -3297,7 +3316,7 @@ "This step did not finish within the time limit. This alone does not show that the server is unreachable.": "This step did not finish within the time limit. This alone does not show that the server is unreachable.", "This stops all running WSL distributions so the new group membership applies when WSL starts again.": "This stops all running WSL distributions so the new group membership applies when WSL starts again.", "This table view presents data at the root level by default.": "This table view presents data at the root level by default.", - "This view is tied to the previous connection. Close it and reopen it from the tree.": "This view is tied to the previous connection. Close it and reopen it from the tree.", + "This view is tied to the previous connection settings. Close it and reopen it from the tree.": "This view is tied to the previous connection settings. Close it and reopen it from the tree.", "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround could not read it either.": "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround could not read it either.", "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround is turned off.": "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround is turned off.", "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), so the extension read it another way. Nothing needs to change.": "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), so the extension read it another way. Nothing needs to change.", @@ -3419,6 +3438,7 @@ "Update MongoDB Atlas connection": "Update MongoDB Atlas connection", "Update MongoDB Atlas Credentials": "Update MongoDB Atlas Credentials", "Update saved password": "Update saved password", + "update this connection": "update this connection", "Updated": "Updated", "Updated {0} minutes ago": "Updated {0} minutes ago", "Updated 1 minute ago": "Updated 1 minute ago", @@ -3525,6 +3545,7 @@ "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.": "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.", "VS Code version: {0}": "VS Code version: {0}", "VS Code: v{0}": "VS Code: v{0}", + "Wait for the update to finish, then click Retry.": "Wait for the update to finish, then click Retry.", "Wait longer": "Wait longer", "Wait until the service has an external address, then run the diagnosis again.": "Wait until the service has an external address, then run the diagnosis again.", "Waiting {0}": "Waiting {0}", @@ -3576,6 +3597,7 @@ "We found a container using the DocumentDB Local name, but it very likely was not created by this extension, so we cannot open it.": "We found a container using the DocumentDB Local name, but it very likely was not created by this extension, so we cannot open it.", "We found an existing data volume after the image downloaded. Setup stopped to protect its data. Go back to Configure and try again.": "We found an existing data volume after the image downloaded. Setup stopped to protect its data. Go back to Configure and try again.", "We found an existing DocumentDB Local instance, but its saved credentials are unavailable. Without them, we cannot reopen or reuse the existing data, so you need to start fresh. Nothing has been changed yet. Starting fresh erases the existing instance and its data, then creates a new one.": "We found an existing DocumentDB Local instance, but its saved credentials are unavailable. Without them, we cannot reopen or reuse the existing data, so you need to start fresh. Nothing has been changed yet. Starting fresh erases the existing instance and its data, then creates a new one.", + "What should happen to the open tabs for this connection?": "What should happen to the open tabs for this connection?", "What should setup do with the existing data?": "What should setup do with the existing data?", "What will happen in the Set up step": "What will happen in the Set up step", "What's New": "What's New", diff --git a/package-lock.json b/package-lock.json index bc2a628de..c4d3c6f2b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.3", + "version": "1.1.1-alpha.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vscode-documentdb", - "version": "1.1.1-alpha.3", + "version": "1.1.1-alpha.4", "license": "SEE LICENSE IN LICENSE.md", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 2a21ff0bb..1e5d15472 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.3", + "version": "1.1.1-alpha.4", "releaseNotesUrl": "https://github.com/microsoft/vscode-documentdb/discussions/1089", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "publisher": "ms-azuretools", @@ -602,6 +602,11 @@ "command": "vscode-documentdb.command.diagnoseConnection", "title": "Diagnose Connection…" }, + { + "category": "DocumentDB", + "command": "vscode-documentdb.command.disconnect", + "title": "%connections.disconnect%" + }, { "//": "[DiscoveryView] Rename Kubernetes kubeconfig source", "category": "DocumentDB", @@ -1346,6 +1351,11 @@ "when": "view =~ /connectionsView|discoveryView|azure(ResourceGroups|FocusView)/ && viewItem =~ /\\btreeitem_documentdbcluster\\b/i && !listMultiSelection", "group": "2@2" }, + { + "command": "vscode-documentdb.command.disconnect", + "when": "view =~ /connectionsView|discoveryView|azure(ResourceGroups|FocusView)/ && viewItem =~ /\\btreeitem_documentdbcluster\\b/i && viewItem =~ /\\bconnected\\b/ && !listMultiSelection", + "group": "2@3" + }, { "//": "[Account] Open Interactive Shell", "command": "vscode-documentdb.command.shell.open", @@ -1571,6 +1581,10 @@ ], "explorer/context": [], "commandPalette": [ + { + "command": "vscode-documentdb.command.disconnect", + "when": "false" + }, { "command": "vscode-documentdb.debug.survey.showInvitation", "when": "documentdb-development-mode" @@ -2019,6 +2033,22 @@ } }, "additionalProperties": false + }, + "documentDB.connections.openTabsOnDisconnect": { + "order": 6, + "type": "string", + "default": "ask", + "description": "Choose what happens to open tabs when you disconnect or remove a connection. Closing tabs with unsaved document changes always requires confirmation.", + "enum": [ + "ask", + "closeAll", + "keepOpenDisabled" + ], + "enumDescriptions": [ + "Ask whether to close or keep open tabs.", + "Close all tabs for the connection.", + "Keep tabs open but disable database operations." + ] } } }, diff --git a/package.nls.json b/package.nls.json index b30f91418..0556db980 100644 --- a/package.nls.json +++ b/package.nls.json @@ -1,4 +1,5 @@ { + "connections.disconnect": "Disconnect", "diagnostics.showConnectionStats": "Show Connection Stats", "survey.containerTitle": "DocumentDB Feedback", "survey.viewTitle": "Share Your Experience", diff --git a/src/commands/connections-view/deleteFolder/ExecuteStep.ts b/src/commands/connections-view/deleteFolder/ExecuteStep.ts index 3e40393a8..81dd41589 100644 --- a/src/commands/connections-view/deleteFolder/ExecuteStep.ts +++ b/src/commands/connections-view/deleteFolder/ExecuteStep.ts @@ -4,12 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import { AzureWizardExecuteStep } from '@microsoft/vscode-azext-utils'; +import { withConnectionRemoval } from '../../../documentdb/connectionTeardown'; import { ext } from '../../../extensionVariables'; import { ConnectionStorageService, ItemType } from '../../../services/connectionStorageService'; import { refreshParentInConnectionsView, withConnectionsViewProgress, } from '../../../tree/connections-view/connectionsViewHelpers'; +import { enumerateConnectionsInFolder } from '../verificationUtils'; import { type DeleteFolderWizardContext } from './DeleteFolderWizardContext'; /** @@ -28,18 +30,20 @@ export class ExecuteStep extends AzureWizardExecuteStep { - await ext.state.showDeleting(context.folderItem.id, async () => { - // Recursively delete all descendants - await this.deleteRecursive(context, context.folderItem.storageId); - - // Delete the folder itself (count as 1 more folder) - await ConnectionStorageService.delete(context.connectionType, context.folderItem.storageId); - context.deletedFolders++; + const ids = await enumerateConnectionsInFolder(context.folderItem.storageId, context.connectionType); + try { + await withConnectionRemoval(ids, async (removeConnection) => { + await withConnectionsViewProgress(async () => { + await ext.state.showDeleting(context.folderItem.id, async () => { + await this.deleteRecursive(context, context.folderItem.storageId, removeConnection); + await ConnectionStorageService.delete(context.connectionType, context.folderItem.storageId); + context.deletedFolders++; + }); + }); }); - + } finally { refreshParentInConnectionsView(context.folderItem.id); - }); + } // Record telemetry measurements context.telemetry.measurements.deletedFolders = context.deletedFolders; @@ -52,19 +56,25 @@ export class ExecuteStep extends AzureWizardExecuteStep { + private async deleteRecursive( + context: DeleteFolderWizardContext, + parentId: string, + removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise, + ): Promise { const children = await ConnectionStorageService.getChildren(parentId, context.connectionType); for (const child of children) { // Recursively delete child folders first if (child.properties.type === ItemType.Folder) { - await this.deleteRecursive(context, child.id); + await this.deleteRecursive(context, child.id, removeConnection); + await ConnectionStorageService.delete(context.connectionType, child.id); context.deletedFolders++; } else { + await removeConnection(child.id, () => + ConnectionStorageService.delete(context.connectionType, child.id), + ); context.deletedConnections++; } - // Delete the child item - await ConnectionStorageService.delete(context.connectionType, child.id); } } diff --git a/src/commands/connections-view/deleteFolder/deleteFolder.test.ts b/src/commands/connections-view/deleteFolder/deleteFolder.test.ts index c0db46f67..b4d95aa38 100644 --- a/src/commands/connections-view/deleteFolder/deleteFolder.test.ts +++ b/src/commands/connections-view/deleteFolder/deleteFolder.test.ts @@ -59,11 +59,18 @@ vi.mock('../verificationUtils', async () => ({ })); import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { type withConnectionRemoval } from '../../../documentdb/connectionTeardown'; import { ConnectionType, ItemType, type ConnectionItem } from '../../../services/connectionStorageService'; import { type DeleteFolderWizardContext } from './DeleteFolderWizardContext'; import { ExecuteStep } from './ExecuteStep'; import { VerifyNoConflictsStep } from './VerifyNoConflictsStep'; +vi.mock('../../../documentdb/connectionTeardown', () => ({ + withConnectionRemoval: vi.fn(async (_ids: string[], remove: Parameters[1]) => { + await remove(async (_id, deleteStored) => deleteStored()); + }), +})); + // Mock vscode-azext-utils vi.mock('@microsoft/vscode-azext-utils', () => ({ AzureWizardPromptStep: class { diff --git a/src/commands/dashboardBoundCommands.test.ts b/src/commands/dashboardBoundCommands.test.ts index c9db7f3b3..942277ea6 100644 --- a/src/commands/dashboardBoundCommands.test.ts +++ b/src/commands/dashboardBoundCommands.test.ts @@ -46,6 +46,7 @@ vi.mock('../documentdb/ClustersClient', () => ({ ClustersClient: { getClient: vi.fn(), getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), resolveBoundClient: vi.fn(), reportFailure: vi.fn(), }, diff --git a/src/commands/disconnect/disconnect.ts b/src/commands/disconnect/disconnect.ts new file mode 100644 index 000000000..38673118d --- /dev/null +++ b/src/commands/disconnect/disconnect.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { ext } from '../../extensionVariables'; +import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { type TreeElement } from '../../tree/TreeElement'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; + +function isClusterNode(node: TreeElement | undefined): node is ClusterItemBase { + return node instanceof ClusterItemBase; +} + +export async function disconnect(context: IActionContext, node?: TreeElement): Promise { + context.telemetry.suppressAll = true; // connection.disconnect owns this operation's telemetry. + if (!isClusterNode(node)) { + throw new UserCancelledError(); + } + + const { clusterId } = node.cluster; + if (!ClustersClient.exists(clusterId) || ClustersClient.getLatchReason(clusterId)) { + throw new UserCancelledError(); + } + + await teardownConnection(clusterId, 'userDisconnected', () => refreshAuthenticationNode(node)); +} + +export function connectDisconnected(_context: IActionContext, node?: TreeElement): void { + if (!isClusterNode(node) || ClustersClient.getLatchReason(node.cluster.clusterId) !== 'userDisconnected') { + return; + } + + ClustersClient.unlatch(node.cluster.clusterId); + ext.state.notifyChildrenChanged(node.id); +} diff --git a/src/commands/exportDocuments/exportDocuments.ts b/src/commands/exportDocuments/exportDocuments.ts index 53b48dd6b..8adc17ed7 100644 --- a/src/commands/exportDocuments/exportDocuments.ts +++ b/src/commands/exportDocuments/exportDocuments.ts @@ -10,6 +10,7 @@ import * as vscode from 'vscode'; import { type ConnectionBinding, type FindQueryParams } from '../../documentdb/ClustersClient'; import { resolveTransferClient } from '../../documentdb/resolveTransferClient'; import { ext } from '../../extensionVariables'; +import { TaskService } from '../../services/taskService/taskService'; import { type CollectionItem } from '../../tree/documentdb/CollectionItem'; import { appendToFile } from '../../utils/fs/appendToFile'; import { getRootPath } from '../../utils/workspacUtils'; @@ -53,46 +54,59 @@ export async function exportQueryResults( return; } - const client = await resolveTransferClient(node.cluster.clusterId, props?.binding); - - const docStreamAbortController = new AbortController(); + const lease = TaskService.acquireResourceLease( + { + clusterId: node.cluster.clusterId, + databaseName: node.databaseInfo.name, + collectionName: node.collectionInfo.name, + }, + l10n.t('Export documents'), + ); - // Convert legacy queryText to queryParams if needed - const queryParams: FindQueryParams = props?.queryParams ?? { - filter: props?.queryText ?? '{}', - }; + try { + const client = await resolveTransferClient(node.cluster.clusterId, props?.binding); - const docStream = client.streamDocumentsWithQuery( - node.databaseInfo.name, - node.collectionInfo.name, - docStreamAbortController.signal, - queryParams, - ); + const docStreamAbortController = new AbortController(); - const filePath = targetUri.fsPath; // Convert `vscode.Uri` to a regular file path - ext.outputChannel.info(l10n.t('Starting export to: {filePath}', { filePath })); + // Convert legacy queryText to queryParams if needed + const queryParams: FindQueryParams = props?.queryParams ?? { + filter: props?.queryText ?? '{}', + }; - let documentCount = 0; + const docStream = client.streamDocumentsWithQuery( + node.databaseInfo.name, + node.collectionInfo.name, + docStreamAbortController.signal, + queryParams, + ); - // Wrap the export process inside a progress reporting function - await callWithTelemetryAndErrorHandling('exportDocuments', async (actionContext) => { - await runExportWithProgressAndDescription(node.id, async (progress, cancellationToken) => { - documentCount = await exportDocumentsToFile( - docStream, - filePath, - progress, - cancellationToken, - docStreamAbortController, - ); + const filePath = targetUri.fsPath; // Convert `vscode.Uri` to a regular file path + ext.outputChannel.info(l10n.t('Starting export to: {filePath}', { filePath })); + + let documentCount = 0; + + // Wrap the export process inside a progress reporting function + await callWithTelemetryAndErrorHandling('exportDocuments', async (actionContext) => { + await runExportWithProgressAndDescription(node.id, async (progress, cancellationToken) => { + documentCount = await exportDocumentsToFile( + docStream, + filePath, + progress, + cancellationToken, + docStreamAbortController, + ); + }); + + actionContext.telemetry.properties.source = props?.source; + actionContext.telemetry.measurements.queryLength = + props?.queryParams?.filter?.length ?? props?.queryText?.length; + actionContext.telemetry.measurements.documentCount = documentCount; }); - actionContext.telemetry.properties.source = props?.source; - actionContext.telemetry.measurements.queryLength = - props?.queryParams?.filter?.length ?? props?.queryText?.length; - actionContext.telemetry.measurements.documentCount = documentCount; - }); - - ext.outputChannel.info(l10n.t('Export complete. Exported document count: {documentCount}', { documentCount })); + ext.outputChannel.info(l10n.t('Export complete. Exported document count: {documentCount}', { documentCount })); + } finally { + lease.dispose(); + } } async function runExportWithProgressAndDescription( diff --git a/src/commands/importDocuments/importDocuments.test.ts b/src/commands/importDocuments/importDocuments.test.ts index a8bcf8124..46ca5021c 100644 --- a/src/commands/importDocuments/importDocuments.test.ts +++ b/src/commands/importDocuments/importDocuments.test.ts @@ -5,17 +5,25 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import { readFile } from 'node:fs/promises'; -import { expect, it, vi } from 'vitest'; +import { beforeEach, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { confirmTeardown } from '../../documentdb/connectionTeardown'; import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { DocumentDBExperience } from '../../DocumentDBExperiences'; import { ext } from '../../extensionVariables'; +import { TaskService } from '../../services/taskService/taskService'; import { CollectionItem } from '../../tree/documentdb/CollectionItem'; +import { exportQueryResults } from '../exportDocuments/exportDocuments'; import { importDocuments } from './importDocuments'; vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), resolveBoundClient: vi.fn(), reportFailure: vi.fn() }, + ClustersClient: { + getClient: vi.fn(), + getLatchReason: vi.fn(), + resolveBoundClient: vi.fn(), + reportFailure: vi.fn(), + }, isBulkWriteError: vi.fn(() => false), })); vi.mock('node:fs/promises', () => ({ @@ -31,6 +39,7 @@ vi.mock('../../extensionVariables', () => ({ }, })); vi.mock('../../utils/workspacUtils', () => ({ getRootPath: vi.fn() })); +vi.mock('../../utils/fs/appendToFile', () => ({ appendToFile: vi.fn() })); const binding: ConnectionBinding = { clusterId: 'cluster', fingerprint: 'original', generation: 1 }; @@ -48,10 +57,7 @@ function createSource(): CollectionItem { ); } -function prepareImport(showOpenDialog: () => Promise): IActionContext { - vi.mocked(vscode.window.withProgress).mockImplementationOnce((_options, task) => - task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), - ); +function createContext(showOpenDialog: () => Promise = async () => []): IActionContext { return { ui: { showOpenDialog }, telemetry: { properties: {}, measurements: {} }, @@ -59,6 +65,16 @@ function prepareImport(showOpenDialog: () => Promise): IActionCont valuesToMask: [], } as unknown as IActionContext; } +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(ClustersClient.getClient).mockReset(); + vi.mocked(ClustersClient.resolveBoundClient).mockReset(); + vi.mocked(ClustersClient.getLatchReason).mockReset().mockReturnValue(undefined); + vi.mocked(vscode.window.withProgress).mockImplementation((_options, task) => + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ); + vi.mocked(vscode.window.showSaveDialog).mockReset(); +}); it('does not import using a different identity selected while the file picker was open', async (): Promise => { const insertDocuments = vi.fn(); @@ -71,7 +87,7 @@ it('does not import using a different identity selected while the file picker wa return [vscode.Uri.file('/fixture/documents.json')]; }); await expect( - importDocuments(prepareImport(showOpenDialog), createSource(), undefined, { binding }), + importDocuments(createContext(showOpenDialog), createSource(), undefined, { binding }), ).rejects.toMatchObject({ reason: 'credentialsChanged' }); expect(showOpenDialog).toHaveBeenCalledOnce(); expect(ClustersClient.resolveBoundClient).toHaveBeenCalledExactlyOnceWith(binding, undefined); @@ -79,6 +95,89 @@ it('does not import using a different identity selected while the file picker wa expect(insertDocuments).not.toHaveBeenCalled(); }); +it('holds an import lease through client resolution and the final flush', async (): Promise => { + let resolveClient!: (client: ClustersClient) => void; + const clientResolution = new Promise((resolve) => { + resolveClient = resolve; + }); + let resolveInsert!: (result: { insertedCount: number }) => void; + const insertDocuments = vi.fn( + () => + new Promise<{ insertedCount: number }>((resolve) => { + resolveInsert = resolve; + }), + ); + vi.mocked(ClustersClient.getClient).mockReturnValue(clientResolution); + + const importOperation = importDocuments(createContext(), createSource(), [ + vscode.Uri.file('/fixture/documents.json'), + ]); + + await vi.waitFor(() => { + expect(ClustersClient.getClient).toHaveBeenCalledWith('cluster'); + }); + + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toEqual([ + expect.objectContaining({ taskName: 'Import documents' }), + ]); + expect( + TaskService.getConflictingTasks({ + clusterId: 'cluster', + databaseName: 'database', + collectionName: 'collection', + }), + ).toHaveLength(1); + expect(TaskService.getConflictingTasks({ clusterId: 'unrelated' })).toEqual([]); + await expect(confirmTeardown('cluster', 'userDisconnected')).resolves.toEqual({ outcome: 'blockedByTask' }); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + + resolveClient({ + getConnectionString: () => 'mongodb://example.test', + insertDocuments, + } as unknown as ClustersClient); + await vi.waitFor(() => { + expect(insertDocuments).toHaveBeenCalledOnce(); + }); + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toHaveLength(1); + + resolveInsert({ insertedCount: 1 }); + await importOperation; + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toEqual([]); +}); + +it('holds an export lease before client resolution and releases it on failure', async (): Promise => { + let rejectClient!: (error: Error) => void; + const clientResolution = new Promise((_resolve, reject) => { + rejectClient = reject; + }); + vi.mocked(vscode.window.showSaveDialog).mockResolvedValue(vscode.Uri.file('/fixture/export.json')); + vi.mocked(ClustersClient.getClient).mockReturnValue(clientResolution); + + const exportOperation = exportQueryResults(createContext(), createSource()); + + await vi.waitFor(() => { + expect(ClustersClient.getClient).toHaveBeenCalledWith('cluster'); + }); + + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toEqual([ + expect.objectContaining({ taskName: 'Export documents' }), + ]); + expect( + TaskService.getConflictingTasks({ + clusterId: 'cluster', + databaseName: 'database', + collectionName: 'collection', + }), + ).toHaveLength(1); + expect(TaskService.getConflictingTasks({ clusterId: 'unrelated' })).toEqual([]); + await expect(confirmTeardown('cluster', 'userDisconnected')).resolves.toEqual({ outcome: 'blockedByTask' }); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + + rejectClient(new Error('client resolution failed')); + await expect(exportOperation).rejects.toThrow('client resolution failed'); + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toEqual([]); +}); + it('stops a bound import after rejection and reports only confirmed inserts', async (): Promise => { const failure = new Error('Rejected fixture credentials'); const insertDocuments = vi.fn().mockResolvedValueOnce({ insertedCount: 1 }).mockRejectedValueOnce(failure); @@ -90,7 +189,7 @@ it('stops a bound import after rejection and reports only confirmed inserts', as vi.mocked(readFile).mockResolvedValueOnce('[{"n":1},{"n":2},{"n":3},{"n":4}]'); vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValueOnce(client as unknown as ClustersClient); vi.mocked(ClustersClient.reportFailure).mockReturnValueOnce('credentialsRejected'); - const context = prepareImport(async () => [vscode.Uri.file('/fixture/documents.json')]); + const context = createContext(async () => [vscode.Uri.file('/fixture/documents.json')]); await expect(importDocuments(context, createSource(), undefined, { binding })).rejects.toMatchObject({ reason: 'credentialsRejected', @@ -98,4 +197,5 @@ it('stops a bound import after rejection and reports only confirmed inserts', as expect(insertDocuments).toHaveBeenCalledTimes(2); expect(ClustersClient.reportFailure).toHaveBeenCalledExactlyOnceWith(client.binding, failure); expect(ext.outputChannel.warn).toHaveBeenCalledWith('Inserted 1 document(s).'); + expect(TaskService.getConflictingTasks({ clusterId: binding.clusterId })).toEqual([]); }); diff --git a/src/commands/importDocuments/importDocuments.ts b/src/commands/importDocuments/importDocuments.ts index c389047ed..5ccdce0f2 100644 --- a/src/commands/importDocuments/importDocuments.ts +++ b/src/commands/importDocuments/importDocuments.ts @@ -17,6 +17,7 @@ import { hasDomainSuffix, } from '../../documentdb/utils/connectionStringHelpers'; import { ext } from '../../extensionVariables'; +import { TaskService } from '../../services/taskService/taskService'; import { CollectionItem } from '../../tree/documentdb/CollectionItem'; import { BufferErrorCode, createMongoDbBuffer, type DocumentBuffer } from '../../utils/documentBuffer'; import { getRootPath } from '../../utils/workspacUtils'; @@ -157,84 +158,97 @@ export async function importDocumentsWithProgress( const countDocuments = documents.length; const incrementDocuments = 75 / (countDocuments || 1); let count = 0; - let buffer: DocumentBuffer | undefined; - let boundClient: ClustersClient | undefined; - if (selectedItem instanceof CollectionItem) { - // Get the connection string from the ClustersClient, not from the cluster model. - // For Discovery View items, the cluster model may not have connectionString populated, - // but the ClustersClient will have it after authentication. - const client = await resolveTransferClient(selectedItem.cluster.clusterId, binding); - if (binding) { - // A bound import must not switch clients between batches. - boundClient = client; - } - const connectionString = client.getConnectionString(); - - // Determine if this is an Azure MongoDB RU resource - // Fall back to non-RU buffer if connection string is unavailable - let isRuResource = false; - if (connectionString) { - const hosts = getHostsFromConnectionString(connectionString); - isRuResource = hasDomainSuffix(AzureDomains.RU, ...hosts); - } + const lease = TaskService.acquireResourceLease( + { + clusterId: selectedItem.cluster.clusterId, + databaseName: selectedItem.databaseInfo.name, + collectionName: selectedItem.collectionInfo.name, + }, + l10n.t('Import documents'), + ); - if (isRuResource) { - // For Azure MongoDB RU, we use a buffer with maxDocumentCount = 1 - buffer = createMongoDbBuffer({ - maxDocumentCount: 1, - }); - } else { - buffer = createMongoDbBuffer(); - } - } + try { + let buffer: DocumentBuffer | undefined; + let boundClient: ClustersClient | undefined; + if (selectedItem instanceof CollectionItem) { + // Get the connection string from the ClustersClient, not from the cluster model. + // For Discovery View items, the cluster model may not have connectionString populated, + // but the ClustersClient will have it after authentication. + const client = await resolveTransferClient(selectedItem.cluster.clusterId, binding); + if (binding) { + // A bound import must not switch clients between batches. + boundClient = client; + } + const connectionString = client.getConnectionString(); + + // Determine if this is an Azure MongoDB RU resource + // Fall back to non-RU buffer if connection string is unavailable + let isRuResource = false; + if (connectionString) { + const hosts = getHostsFromConnectionString(connectionString); + isRuResource = hasDomainSuffix(AzureDomains.RU, ...hosts); + } - let wasCancelled = false; - const insertBatch = async (document: unknown): Promise<{ count: number; errorOccurred: boolean }> => { - try { - return await insertDocument(selectedItem, document, buffer, boundClient); - } catch (error) { - if (error instanceof ConnectionUnavailableError) { - ext.outputChannel.warn(l10n.t('Inserted {0} document(s).', count)); + if (isRuResource) { + // For Azure MongoDB RU, we use a buffer with maxDocumentCount = 1 + buffer = createMongoDbBuffer({ + maxDocumentCount: 1, + }); + } else { + buffer = createMongoDbBuffer(); } - throw error; } - }; - for (let i = 0; i < countDocuments; i++) { - if (cancellationToken.isCancellationRequested) { - wasCancelled = true; - ext.outputChannel.warn(l10n.t('Import operation was canceled after {0} document(s).', count)); - break; - } + let wasCancelled = false; + const insertBatch = async (document: unknown): Promise<{ count: number; errorOccurred: boolean }> => { + try { + return await insertDocument(selectedItem, document, buffer, boundClient); + } catch (error) { + if (error instanceof ConnectionUnavailableError) { + ext.outputChannel.warn(l10n.t('Inserted {0} document(s).', count)); + } + throw error; + } + }; - progress.report({ - increment: incrementDocuments, - message: l10n.t('Importing document {num} of {countDocuments}', { - num: i + 1, - countDocuments, - }), - }); + for (let i = 0; i < countDocuments; i++) { + if (cancellationToken.isCancellationRequested) { + wasCancelled = true; + ext.outputChannel.warn(l10n.t('Import operation was canceled after {0} document(s).', count)); + break; + } - const result = await insertBatch(documents[i]); + progress.report({ + increment: incrementDocuments, + message: l10n.t('Importing document {num} of {countDocuments}', { + num: i + 1, + countDocuments, + }), + }); - // 'count' in result means that the result is from the buffer - count += result.count; - // check if error occurred as partial failure would happen in bulk insertion - hasErrors = hasErrors || result.errorOccurred; - } + const result = await insertBatch(documents[i]); - // Do insertion for the last batch for bulk insertion - if (!wasCancelled && buffer && buffer.getStats().documentCount > 0) { - const lastBatchFlushResult = await insertBatch(undefined); + // 'count' in result means that the result is from the buffer + count += result.count; + // check if error occurred as partial failure would happen in bulk insertion + hasErrors = hasErrors || result.errorOccurred; + } - count += lastBatchFlushResult.count; - hasErrors = hasErrors || lastBatchFlushResult.errorOccurred; - } + // Do insertion for the last batch for bulk insertion + if (!wasCancelled && buffer && buffer.getStats().documentCount > 0) { + const lastBatchFlushResult = await insertBatch(undefined); - // let's make sure we reach 100% progress, useful in case of errors etc. - progress.report({ increment: 100, message: l10n.t('Finished importing') }); + count += lastBatchFlushResult.count; + hasErrors = hasErrors || lastBatchFlushResult.errorOccurred; + } - return { hasErrors, count, wasCancelled }; + // let's make sure we reach 100% progress, useful in case of errors etc. + progress.report({ increment: 100, message: l10n.t('Finished importing') }); + + return { hasErrors, count, wasCancelled }; + } finally { + lease.dispose(); + } }, ); diff --git a/src/commands/openClusterDashboard/openClusterDashboard.ts b/src/commands/openClusterDashboard/openClusterDashboard.ts index 983aa07b5..5ccd38002 100644 --- a/src/commands/openClusterDashboard/openClusterDashboard.ts +++ b/src/commands/openClusterDashboard/openClusterDashboard.ts @@ -157,6 +157,7 @@ export async function openClusterDashboard( }, client.binding, options?.deepLink, + options?.activationSource === 'autoOpenOnConnect', ); context.telemetry.properties.viewId = viewId; diff --git a/src/commands/openInteractiveShell/openInteractiveShell.ts b/src/commands/openInteractiveShell/openInteractiveShell.ts index 39dd4fcda..7e367b0bc 100644 --- a/src/commands/openInteractiveShell/openInteractiveShell.ts +++ b/src/commands/openInteractiveShell/openInteractiveShell.ts @@ -84,7 +84,11 @@ export async function openInteractiveShell( }); pty.setTerminal(terminal); - registerShellTerminal(terminal, () => pty.getTerminalInfo()); + registerShellTerminal( + terminal, + () => pty.getTerminalInfo(), + () => pty.disconnect(), + ); terminal.show(); return { opened: true, shellSessionId: pty.shellSessionId }; @@ -133,7 +137,11 @@ export async function openInteractiveShellWithInput( }); pty.setTerminal(terminal); - registerShellTerminal(terminal, () => pty.getTerminalInfo()); + registerShellTerminal( + terminal, + () => pty.getTerminalInfo(), + () => pty.disconnect(), + ); terminal.show(); } diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts new file mode 100644 index 000000000..2498908ab --- /dev/null +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -0,0 +1,86 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { executePlaygroundCode, stopPlaygroundEvaluator } from './executePlaygroundCode'; + +const { evaluate, dispose, setExecuting, showResult } = vi.hoisted(() => ({ + evaluate: vi.fn(), + dispose: vi.fn(), + setExecuting: vi.fn(), + showResult: vi.fn(), +})); + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal<{ UserCancelledError: typeof UserCancelledError }>()), + callWithTelemetryAndErrorHandling: ( + _name: string, + run: (context: IActionContext) => Promise, + ): Promise => run({ errorHandling: {}, telemetry: { measurements: {}, properties: {} } } as IActionContext), +})); + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { getLatchReason: vi.fn(), getExistingClient: vi.fn() }, +})); + +vi.mock('../../documentdb/playground/PlaygroundEvaluator', () => ({ + PlaygroundEvaluator: class { + evaluate = evaluate; + dispose = dispose; + }, +})); + +vi.mock('../../documentdb/playground/PlaygroundService', () => ({ + PlaygroundService: { + getInstance: () => ({ + getConnection: () => ({ clusterId: 'cluster', clusterDisplayName: 'Cluster', databaseName: 'test' }), + isExecuting: () => false, + setExecuting, + }), + }, +})); + +vi.mock('../../extensionVariables', () => ({ + ext: { playgroundResultProvider: { showResult } }, +})); + +describe('executePlaygroundCode', () => { + it('cancels a stopped worker without replacing the retained result or showing an error', async () => { + let stopEvaluation: (error: Error) => void = () => {}; + evaluate.mockImplementation( + () => + new Promise((_resolve, reject) => { + stopEvaluation = reject; + }), + ); + dispose.mockImplementation(() => { + stopEvaluation(new Error('Worker terminated')); + }); + const showError = vi.spyOn(vscode.window, 'showErrorMessage'); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); + + try { + const run = executePlaygroundCode('db.stats()', 'runAll', vscode.Uri.file('test.documentdb.js')); + expect(evaluate).toHaveBeenCalledOnce(); + stopPlaygroundEvaluator('cluster'); + await expect(run).rejects.toBeInstanceOf(UserCancelledError); + expect(showResult).not.toHaveBeenCalled(); + expect(showError).not.toHaveBeenCalled(); + expect(setExecuting).toHaveBeenLastCalledWith('cluster', false); + } finally { + progress.mockRestore(); + showError.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } + }); +}); diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index 807b7dd9f..a95eb661c 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -53,6 +53,13 @@ export function shutdownEvaluator(clusterId: string): void { } } +/** Stop an evaluator immediately without changing the open documents or their bindings. */ +export function stopPlaygroundEvaluator(clusterId: string): void { + const evaluator = evaluators.get(clusterId); + evaluators.delete(clusterId); + evaluator?.dispose(); +} + /** * Shut down all evaluators that have no remaining open playground documents. * Called when playground documents close or state changes. @@ -115,6 +122,14 @@ export async function executePlaygroundCode( } } + const { clusterId } = connection; + if (ClustersClient.getLatchReason(clusterId)) { + void vscode.window.showWarningMessage( + l10n.t('This connection is unavailable. Reconnect from the tree to run this playground.'), + ); + return; + } + // Prevent concurrent runs on the same cluster — no queuing if (service.isExecuting(connection.clusterId)) { void vscode.window.showInformationMessage( @@ -196,10 +211,16 @@ export async function executePlaygroundCode( const sourceUri = documentUri; try { + if (evaluators.get(clusterId) !== evaluator) { + throw new UserCancelledError('playground.execute'); + } const result = await evaluator!.evaluate(connection, code, (message) => { progress.report({ message }); }); + if (evaluators.get(clusterId) !== evaluator) { + return; + } // ── Post-execution telemetry (known after success) ──── context.telemetry.properties.resultType = result.type ?? 'null'; context.telemetry.measurements.initDurationMs = evaluator!.lastInitDurationMs; @@ -226,13 +247,16 @@ export async function executePlaygroundCode( } // result: 'Succeeded' is set automatically by the framework } catch (error: unknown) { + if (error instanceof UserCancelledError) { + throw error; + } // Update session telemetry even on failure (worker may have spawned before failing) context.telemetry.properties.sessionId = evaluator!.sessionId ?? 'none'; context.telemetry.measurements.sessionEvalCount = evaluator!.sessionEvalCount; context.telemetry.properties.authMethod = evaluator!.sessionAuthMethod ?? 'unknown'; context.telemetry.measurements.initDurationMs = evaluator!.lastInitDurationMs; - if (cancelled) { + if (cancelled || evaluators.get(clusterId) !== evaluator) { // Throw UserCancelledError so framework marks result as 'Canceled' throw new UserCancelledError('playground.execute'); } diff --git a/src/commands/removeConnection/removeConnection.ts b/src/commands/removeConnection/removeConnection.ts index c889a2d78..49d211171 100644 --- a/src/commands/removeConnection/removeConnection.ts +++ b/src/commands/removeConnection/removeConnection.ts @@ -6,8 +6,7 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; -import { CredentialCache } from '../../documentdb/CredentialCache'; -import { SchemaStore } from '../../documentdb/SchemaStore'; +import { withConnectionRemoval } from '../../documentdb/connectionTeardown'; import { ext } from '../../extensionVariables'; import { ConnectionStorageService } from '../../services/connectionStorageService'; import { checkCanProceedAndInformUser } from '../../services/taskService/resourceUsageHelper'; @@ -75,33 +74,41 @@ export async function removeConnection( let successCount = 0; let failureCount = 0; - await withConnectionsViewProgress(async () => { - for (const connection of connectionsToDelete) { - try { - await ext.state.showDeleting(connection.id, async () => { - await ConnectionStorageService.delete(resolveStorageZone(connection.cluster), connection.storageId); + try { + await withConnectionRemoval( + connectionsToDelete.map((connection) => connection.cluster.clusterId), + async (remove) => { + await withConnectionsViewProgress(async () => { + for (const connection of connectionsToDelete) { + try { + await remove(connection.cluster.clusterId, async () => { + await ext.state.showDeleting(connection.id, async () => { + await ConnectionStorageService.delete( + resolveStorageZone(connection.cluster), + connection.storageId, + ); + }); + }); + successCount++; + } catch (error) { + failureCount++; + const errorMessage = error instanceof Error ? error.message : String(error); + ext.outputChannel.error( + l10n.t('Failed to remove connection "{connectionName}": {error}', { + connectionName: connection.cluster.name, + error: errorMessage, + }), + ); + } + } }); - - // delete cached credentials from memory using stable clusterId (not treeId) - CredentialCache.deleteCredentials(connection.cluster.clusterId); - - // clear cached schema data for this cluster - SchemaStore.getInstance().clearCluster(connection.cluster.clusterId); - - refreshParentInConnectionsView(connection.id); - successCount++; - } catch (error) { - failureCount++; - const errorMessage = error instanceof Error ? error.message : String(error); - ext.outputChannel.error( - l10n.t('Failed to remove connection "{connectionName}": {error}', { - connectionName: connection.cluster.name, - error: errorMessage, - }), - ); - } + }, + ); + } finally { + for (const connection of connectionsToDelete) { + refreshParentInConnectionsView(connection.id); } - }); + } context.telemetry.measurements.connectionsDeleted = successCount; context.telemetry.measurements.errorCount = failureCount; diff --git a/src/commands/saveConnectionEdit.ts b/src/commands/saveConnectionEdit.ts new file mode 100644 index 000000000..4cd90a3c1 --- /dev/null +++ b/src/commands/saveConnectionEdit.ts @@ -0,0 +1,152 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { isDeepStrictEqual } from 'node:util'; +import * as vscode from 'vscode'; +import { clearEntraTokenFailure } from '../documentdb/auth/entraErrors/entraTokenFailures'; +import { ClustersClient } from '../documentdb/ClustersClient'; +import { getConnectionSurfaces } from '../documentdb/connectionSurfaces'; +import { confirmTeardown, latchForTeardown } from '../documentdb/connectionTeardown'; +import { CredentialCache } from '../documentdb/CredentialCache'; +import { getRegisteredShellTerminals } from '../documentdb/shell/ShellTerminalLinkProvider'; +import { ext } from '../extensionVariables'; +import { ConnectionStorageService, isConnection, type StoredItem } from '../services/connectionStorageService'; +import { checkCanProceedAndInformUser } from '../services/taskService/resourceUsageHelper'; +import { type DocumentDBClusterItem } from '../tree/connections-view/DocumentDBClusterItem'; +import { resolveStorageZone } from '../tree/connections-view/models/ConnectionClusterModel'; +import { stopPlaygroundEvaluator } from './playground/executePlaygroundCode'; + +function storedSettings(item: StoredItem | undefined): object | undefined { + if (!item || !isConnection(item)) { + return undefined; + } + return { + secrets: item.secrets, + authMethod: item.properties.selectedAuthMethod, + emulator: item.properties.emulatorConfiguration, + }; +} + +/** + * Hold the existing latch across storage writes, then use what actually persisted to decide + * whether to retire views. Secret storage and metadata are not written atomically. + */ +export async function saveConnectionEdit( + node: DocumentDBClusterItem, + save: (isCurrent: () => boolean) => Promise, + options?: { + readonly canStart?: () => boolean; + readonly publishCredentials?: (connection: StoredItem | undefined) => void; + }, +): Promise { + const { clusterId } = node.cluster; + const zone = resolveStorageZone(node.cluster); + if ((await confirmTeardown(clusterId, 'credentialsChanged')).outcome !== 'confirmed') { + throw new UserCancelledError(); + } + + if (options?.canStart?.() === false) { + throw new UserCancelledError(); + } + const previous = ClustersClient.getLatchReason(clusterId); + if (previous === 'connectionRemoved' || previous === 'credentialsUpdating') { + throw new Error(vscode.l10n.t('A connection is already being updated or removed. Try again when it finishes.')); + } + if (!latchForTeardown(clusterId, 'credentialsUpdating')) { + await checkCanProceedAndInformUser({ clusterId }, vscode.l10n.t('update this connection')); + throw new UserCancelledError(); + } + + const epoch = ClustersClient.getEpoch(clusterId); + const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; + let changed = false; + let saved = false; + try { + const before = await ConnectionStorageService.get(node.storageId, zone); + const originalSettings = structuredClone(storedSettings(before)); + if (!originalSettings) { + void vscode.window.showErrorMessage(vscode.l10n.t('The connection could not be read from storage.')); + return false; + } + try { + if (!isCurrent()) { + throw new UserCancelledError(); + } + saved = await save(isCurrent); + } finally { + let after: StoredItem | undefined; + try { + after = await ConnectionStorageService.get(node.storageId, zone); + } catch { + ext.outputChannel.warn(vscode.l10n.t('Could not verify the saved connection settings.')); + } + if (isCurrent() && !isDeepStrictEqual(originalSettings, storedSettings(after))) { + changed = true; + ClustersClient.retireBoundViews(clusterId); + for (const surface of getConnectionSurfaces(clusterId)) { + surface.disable('credentialsChanged'); + } + stopPlaygroundEvaluator(clusterId); + const closing = ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); + CredentialCache.deleteCredentials(clusterId); + clearEntraTokenFailure(clusterId); + if ( + !after || + !isConnection(after) || + !before || + !isConnection(before) || + before.properties.selectedAuthMethod !== after.properties.selectedAuthMethod + ) { + ClustersClient.clearLastVerifiedIdentity(clusterId); + } else if (before.secrets.entraIdAuthConfig?.tenantId !== after.secrets.entraIdAuthConfig?.tenantId) { + ClustersClient.discardEntraPinForDifferentTenant( + clusterId, + after.secrets.entraIdAuthConfig?.tenantId, + ); + } + if (!saved || !after) { + void vscode.window.showWarningMessage( + vscode.l10n.t( + 'The connection update may be incomplete. Check the saved settings before reconnecting.', + ), + ); + } + await closing; + if (isCurrent()) { + options?.publishCredentials?.(after); + } + } + } + } finally { + if (isCurrent()) { + const recovered = previous === 'credentialsRejected' && saved; + if (previous && !recovered && (!changed || previous === 'userDisconnected')) { + ClustersClient.latch(clusterId, previous); + } else { + ClustersClient.unlatch(clusterId); + } + } + } + return changed; +} + +export async function offerShellDisconnect(node: DocumentDBClusterItem): Promise { + const shells = getRegisteredShellTerminals().filter(({ info }) => info.clusterId === node.cluster.clusterId); + if (!shells.length) { + return; + } + const disconnect = vscode.l10n.t('Disconnect'); + const selected = await vscode.window.showInformationMessage( + vscode.l10n.t('Open shells are still using the previous connection settings.'), + { modal: true }, + disconnect, + ); + if (selected === disconnect) { + for (const shell of shells) { + shell.disconnect?.(); + } + } +} diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index db65fdedc..4b6703005 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -93,6 +93,11 @@ vi.mock('../../documentdb/ClustersClient', () => ({ getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), getExistingClient: vi.fn(), + latch: vi.fn(), + unlatch: vi.fn(), + retireBoundViews: vi.fn(), + clearLastVerifiedIdentity: vi.fn(), + discardEntraPinForDifferentTenant: vi.fn(), }, })); vi.mock('../../services/connectionReachabilityService', () => ({ @@ -200,7 +205,9 @@ describe('updateConnectionString rejected-destination recovery', () => { await updateConnectionString(makeContext(), item); expect(capturedContexts[0].connectionStringSaved).toBe(true); - expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id', { + alreadyInvalidated: true, + }); expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); expect(resetError).toHaveBeenCalledExactlyOnceWith(item.id); expect(provider.hasNodeErrorState(item.id)).toBe(false); @@ -273,20 +280,20 @@ describe('updateConnectionString rejected-destination recovery', () => { }, ); - it('leaves the existing connected-edit lifecycle unchanged after a successful ordinary edit', async (): Promise => { + it('retires the old client and bindings after an ordinary saved edit', async (): Promise => { const resetError = vi.spyOn(provider, 'resetNodeErrorState'); const refresh = vi.spyOn(provider, 'refresh'); item.lastConnectionOutcome = 'connected'; - const cachedCredentials = CredentialCache.getCredentials('stable-id'); await updateConnectionString(makeContext(), item); expect(capturedContexts[0].connectionStringSaved).toBe(true); expect(storedConnection.secrets.connectionString).toBe(approvedUri); - expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); - expect(deleteCredentials).not.toHaveBeenCalled(); + expect(ClustersClient.retireBoundViews).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id', { alreadyInvalidated: true }); + expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); expect(resetError).not.toHaveBeenCalled(); - expect(CredentialCache.getCredentials('stable-id')).toBe(cachedCredentials); + expect(CredentialCache.getCredentials('stable-id')).toBeUndefined(); expect(item.lastConnectionOutcome).toBe('connected'); expect(refresh).toHaveBeenCalledOnce(); }); @@ -303,8 +310,8 @@ describe('updateConnectionString rejected-destination recovery', () => { expect(storedConnection.secrets.connectionString).toBe(approvedUri); expect(capturedContexts[0].connectionStringSaved).toBe(true); - expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); - expect(deleteCredentials).not.toHaveBeenCalled(); + expect(ClustersClient.retireBoundViews).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); expect(refresh).toHaveBeenCalledOnce(); }); }); diff --git a/src/commands/updateConnectionString/updateConnectionString.ts b/src/commands/updateConnectionString/updateConnectionString.ts index 39e22d8c5..27229623a 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -6,7 +6,6 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { ClustersClient } from '../../documentdb/ClustersClient'; -import { CredentialCache } from '../../documentdb/CredentialCache'; import { maskSensitiveValuesInTelemetry } from '../../documentdb/utils/connectionStringHelpers'; import { DocumentDBConnectionString } from '../../documentdb/utils/DocumentDBConnectionString'; import { Views } from '../../documentdb/Views'; @@ -15,6 +14,7 @@ import { ConnectionStorageService } from '../../services/connectionStorageServic import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../../tree/connections-view/models/ConnectionClusterModel'; import { refreshView } from '../refreshView/refreshView'; +import { offerShellDisconnect, saveConnectionEdit } from '../saveConnectionEdit'; import { ConnectionStringStep } from './ConnectionStringStep'; import { ExecuteStep } from './ExecuteStep'; import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; @@ -29,8 +29,7 @@ import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; * 3. ExecuteStep: Saves updated connection string to storage * 4. Post-wizard: Refreshes the view * - * Only a successful destination-rejection recovery edit clears cached connection and error state. - * Other edits retain the existing connection lifecycle. + * A changed value retires views tied to the previous settings. */ export async function updateConnectionString(context: IActionContext, node: DocumentDBClusterItem): Promise { if (!node) { @@ -38,7 +37,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu } const recoveringRejectedDestination = node.lastConnectionFailureReason === 'entraDestinationRejected'; const clusterId = node.cluster.clusterId; - let epoch = ClustersClient.getEpoch(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); const recoveringRejectedCredentials = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; const recovering = recoveringRejectedDestination || recoveringRejectedCredentials; const isRecoveryCurrent = recovering ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; @@ -84,26 +83,27 @@ export async function updateConnectionString(context: IActionContext, node: Docu if (isRecoveryCurrent?.() === false) { return; } - await wizard.execute(); - if (isRecoveryCurrent?.() === false) { - return; - } - - if (recovering && wizardContext.connectionStringSaved) { - const closing = ClustersClient.deleteClient(clusterId); - epoch = ClustersClient.getEpoch(clusterId); - await closing; - if (isRecoveryCurrent?.() === false) { - return; - } - CredentialCache.deleteCredentials(clusterId); - if (recoveringRejectedCredentials) { - ClustersClient.clearCredentialRejection(clusterId, epoch); - } + const changed = + wizardContext.newConnectionString && + wizardContext.newConnectionString !== wizardContext.originalConnectionString + ? await saveConnectionEdit( + node, + async (isCurrent) => { + wizardContext.isRecoveryCurrent = isCurrent; + await wizard.execute(); + return wizardContext.connectionStringSaved === true; + }, + { canStart: isRecoveryCurrent }, + ) + : false; + if (recovering && changed && wizardContext.connectionStringSaved) { ext.connectionsBranchDataProvider.resetNodeErrorState(node.id); node.lastConnectionFailureReason = undefined; node.lastConnectionOutcome = undefined; } await refreshView(context, Views.ConnectionsView); + if (changed) { + await offerShellDisconnect(node); + } } diff --git a/src/commands/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index b82ec629c..0e9d59238 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -7,9 +7,11 @@ import { type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-u import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { SelectEntraTokenSourceStep } from '../../documentdb/wizards/authenticate/SelectEntraTokenSourceStep'; import { API } from '../../DocumentDBExperiences'; +import { ext } from '../../extensionVariables'; import type * as storageModule from '../../services/connectionStorageService'; import { ItemType } from '../../services/connectionStorageService'; import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; @@ -23,6 +25,7 @@ const mockGet = vi.fn(); const mockSave = vi.fn(); const mockGetEpoch = vi.fn(() => 0); const mockDeleteClient = vi.fn(); +const mockRetireBoundViews = vi.hoisted(() => vi.fn()); const mockDeleteCredentials = vi.spyOn(CredentialCache, 'deleteCredentials'); const mockShutdownEvaluator = vi.fn(); const mockGetRegisteredShellTerminals = vi.fn(); @@ -54,11 +57,16 @@ vi.mock('../../documentdb/ClustersClient', () => ({ deleteClient: (...args: unknown[]): unknown => mockDeleteClient(...args), getLastFailedStartupCorrelationId: (): undefined => undefined, getEpoch: (): number => mockGetEpoch(), - getLatchReason: (): undefined => undefined, + getLatchReason: vi.fn(), + latch: vi.fn(), + unlatch: vi.fn(), + retireBoundViews: mockRetireBoundViews, + clearLastVerifiedIdentity: vi.fn(), + discardEntraPinForDifferentTenant: vi.fn(), }, })); vi.mock('../playground/executePlaygroundCode', () => ({ - shutdownEvaluator: (...args: unknown[]): unknown => mockShutdownEvaluator(...args), + stopPlaygroundEvaluator: (...args: unknown[]): unknown => mockShutdownEvaluator(...args), })); vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals: (): unknown => mockGetRegisteredShellTerminals(), @@ -66,13 +74,18 @@ vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ vi.mock('../refreshView/refreshView', () => ({ refreshView: vi.fn() })); vi.mock('../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); vi.mock('../../extensionVariables', () => ({ - ext: { connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(() => false) } }, + ext: { + connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(), resetNodeErrorState: vi.fn() }, + outputChannel: { error: vi.fn(), warn: vi.fn() }, + }, })); beforeEach(() => { CredentialCache.deleteCredentials('stable-cluster-id'); vi.clearAllMocks(); mockGetEpoch.mockReturnValue(0); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(false); mockGetRegisteredShellTerminals.mockReturnValue([]); capturedContexts.length = 0; }); @@ -107,7 +120,7 @@ async function inferMethods( cluster: { clusterId: 'stable-cluster-id', treeId: 'folder/current-tree-path' }, } as unknown as DocumentDBClusterItem; await updateCredentials(context, node); - expect(mockDeleteClient).toHaveBeenCalledWith('stable-cluster-id'); + expect(mockDeleteClient).not.toHaveBeenCalled(); expect(mockDeleteCredentials).not.toHaveBeenCalled(); const captured = capturedContexts[0]; if (!captured) { @@ -219,7 +232,7 @@ describe('updateCredentials post-wizard updates', () => { ); }); - it('updates runtime credentials when the epoch changes during an ordinary save', async (): Promise => { + it('retires old views after a saved password-only edit', async (): Promise => { let storedConnection: storageModule.ConnectionItem = originalConnection; const newCredentials = { connectionUser: 'old-user', connectionPassword: 'new-password' }; mockGet.mockImplementation(async () => structuredClone(storedConnection)); @@ -230,7 +243,6 @@ describe('updateCredentials post-wizard updates', () => { mockSave.mockImplementationOnce( async (_zone: storageModule.StorageZone, item: storageModule.ConnectionItem): Promise => { storedConnection = structuredClone(item); - mockGetEpoch.mockReturnValue(1); }, ); @@ -239,10 +251,57 @@ describe('updateCredentials post-wizard updates', () => { expect(storedConnection.secrets.nativeAuthConfig).toEqual(newCredentials); expect(CredentialCache.getCredentials(node.cluster.clusterId)?.nativeAuthConfig).toEqual(newCredentials); expect(capturedContexts[0].credentialsSaved).toBe(true); - expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockRetireBoundViews).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, { alreadyInvalidated: true }); expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); }); + it.each([true, false])( + 'only clears rejection and refreshes the recovery node when an unchanged edit saves (%s)', + async (saved) => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); + mockExecute.mockImplementationOnce((wizardContext) => { + wizardContext.reconnectAfterError = true; + wizardContext.credentialsSaved = saved; + return Promise.resolve(); + }); + + await updateCredentials(context, node); + + expect(mockRetireBoundViews).not.toHaveBeenCalled(); + if (saved) { + expect(ClustersClient.unlatch).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).toHaveBeenCalledExactlyOnceWith(node.id); + } else { + expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'credentialsRejected'); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + } + }, + ); + + it('retires old views if the secret write persisted but the edit reported failure', async (): Promise => { + const stored = structuredClone(originalConnection); + mockGet.mockImplementation(async () => structuredClone(stored)); + mockExecute.mockImplementationOnce(async (wizardContext): Promise => { + wizardContext.nativeAuthConfig = { connectionUser: 'old-user', connectionPassword: 'new-password' }; + await new ExecuteStep().execute(wizardContext); + }); + mockSave.mockImplementationOnce( + async (_zone: storageModule.StorageZone, item: storageModule.ConnectionItem) => { + stored.secrets = structuredClone(item.secrets); + throw new Error('Metadata write failed'); + }, + ); + + await updateCredentials(context, node); + + expect(capturedContexts[0].credentialsSaved).not.toBe(true); + expect(mockRetireBoundViews).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(vscode.window.showWarningMessage).toHaveBeenCalledOnce(); + }); + it.each<{ authMethod: AuthMethodId; secrets: Partial }>([ { authMethod: AuthMethodId.NativeAuth, @@ -266,11 +325,17 @@ describe('updateCredentials post-wizard updates', () => { properties: { ...originalConnection.properties, selectedAuthMethod: authMethod }, secrets: { connectionString: 'mongodb://new.example.com:27017/', ...secrets }, }; - mockGet.mockResolvedValueOnce(originalConnection).mockResolvedValueOnce(savedConnection); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue(savedConnection); + mockExecute.mockImplementationOnce(async (wizardContext) => { + wizardContext.credentialsSaved = true; + }); await updateCredentials(context, node); - expect(mockGet).toHaveBeenCalledTimes(2); + expect(mockGet).toHaveBeenCalledTimes(3); expect(mockGet.mock.calls[1]).toEqual(mockGet.mock.calls[0]); expect(CredentialCache.getCredentials(node.cluster.clusterId)).toEqual({ clusterId: node.cluster.clusterId, @@ -286,20 +351,25 @@ describe('updateCredentials post-wizard updates', () => { managedIdentityConfig: secrets.managedIdentityAuthConfig, }); expect(CredentialCache.hasCredentials(node.cluster.treeId)).toBe(false); - expect(mockDeleteCredentials).not.toHaveBeenCalled(); - expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteCredentials).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, { + alreadyInvalidated: true, + }); expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); }, ); it('deletes cached credentials when stored native authentication has no password', async () => { - mockGet.mockResolvedValue({ - ...originalConnection, - secrets: { - ...originalConnection.secrets, - nativeAuthConfig: { connectionUser: 'new-user' }, - }, - }); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue({ + ...originalConnection, + secrets: { + ...originalConnection.secrets, + nativeAuthConfig: { connectionUser: 'new-user' }, + }, + }); await updateCredentials(context, node); @@ -308,10 +378,13 @@ describe('updateCredentials post-wizard updates', () => { }); it('deletes cached credentials when the stored authentication method is missing', async () => { - mockGet.mockResolvedValue({ - ...originalConnection, - properties: { ...originalConnection.properties, selectedAuthMethod: undefined }, - }); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue({ + ...originalConnection, + properties: { ...originalConnection.properties, selectedAuthMethod: undefined }, + }); await updateCredentials(context, node); @@ -319,18 +392,45 @@ describe('updateCredentials post-wizard updates', () => { expect(CredentialCache.getCredentials(node.cluster.clusterId)).toBeUndefined(); }); - it('shows a modal without action items when a shell for the cluster is open', async () => { + it('offers to disconnect only shells using the previous connection settings', async () => { + const disconnect = vi.fn(); + const disconnectOther = vi.fn(); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue({ + ...originalConnection, + secrets: { + ...originalConnection.secrets, + nativeAuthConfig: { connectionUser: 'old-user', connectionPassword: 'new-password' }, + }, + }); + mockExecute.mockImplementationOnce(async (wizardContext) => { + wizardContext.credentialsSaved = true; + }); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); + const showInformation: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] + ) => Thenable = vscode.window.showInformationMessage; + vi.mocked(showInformation).mockResolvedValueOnce('Disconnect'); mockGetRegisteredShellTerminals.mockReturnValue([ - { info: { clusterId: 'another-cluster-id' } }, - { info: { clusterId: node.cluster.clusterId } }, + { info: { clusterId: 'another-cluster-id' }, disconnect: disconnectOther }, + { info: { clusterId: node.cluster.clusterId }, disconnect }, ]); await updateCredentials(context, node); expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( - "Credentials updated. New connections will use them. Open shells for 'cluster' keep their current connection until you close them.", + 'Open shells are still using the previous connection settings.', { modal: true }, + 'Disconnect', ); + expect(disconnect).toHaveBeenCalledOnce(); + expect(disconnectOther).not.toHaveBeenCalled(); const modalCallOrder = vi.mocked(vscode.window.showInformationMessage).mock.invocationCallOrder[0]; expect(mockDeleteClient.mock.invocationCallOrder[0]).toBeLessThan(modalCallOrder); expect(mockShutdownEvaluator.mock.invocationCallOrder[0]).toBeLessThan(modalCallOrder); diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 8e5e6fcfa..72b703ab8 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -5,7 +5,6 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; -import * as vscode from 'vscode'; import { AuthMethodId, authMethodFromString, @@ -15,7 +14,6 @@ import { import { evaluateEntraDestinationFromSettings } from '../../documentdb/auth/entraDestinationSettings'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; -import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; import { DocumentDBConnectionString } from '../../documentdb/utils/DocumentDBConnectionString'; import { Views } from '../../documentdb/Views'; import { SelectEntraTokenSourceStep } from '../../documentdb/wizards/authenticate/SelectEntraTokenSourceStep'; @@ -23,8 +21,8 @@ import { ext } from '../../extensionVariables'; import { ConnectionStorageService, isConnection } from '../../services/connectionStorageService'; import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../../tree/connections-view/models/ConnectionClusterModel'; -import { shutdownEvaluator } from '../playground/executePlaygroundCode'; import { refreshView } from '../refreshView/refreshView'; +import { offerShellDisconnect, saveConnectionEdit } from '../saveConnectionEdit'; import { PromptAuthMethodStep } from '../updateCredentials/PromptAuthMethodStep'; import { ExecuteStep } from './ExecuteStep'; import { PromptPasswordStep } from './PromptPasswordStep'; @@ -58,7 +56,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD throw new Error(l10n.t('No node selected.')); } const clusterId = node.cluster.clusterId; - let epoch = ClustersClient.getEpoch(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; const isRecoveryCurrent = recoveringRejection ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch @@ -150,67 +148,43 @@ export async function updateCredentials(context: IActionContext, node: DocumentD if (isRecoveryCurrent?.() === false) { return; } - await wizard.execute(); - if (isRecoveryCurrent?.() === false || (recoveringRejection && !wizardContext.credentialsSaved)) { - return; - } - - const updatedStoredItem = await ConnectionStorageService.get(node.storageId, resourceType); - if (isRecoveryCurrent?.() === false) { - return; - } - const updatedConnection = updatedStoredItem && isConnection(updatedStoredItem) ? updatedStoredItem : undefined; - const closing = ClustersClient.deleteClient(clusterId); - epoch = ClustersClient.getEpoch(clusterId); - await closing; - // Do not publish cached credentials over a lifecycle change during close. - if (ClustersClient.getEpoch(clusterId) !== epoch) { - return; - } - const authMethod = authMethodFromString(updatedConnection?.properties.selectedAuthMethod); - const username = updatedConnection?.secrets.nativeAuthConfig?.connectionUser; - const password = updatedConnection?.secrets.nativeAuthConfig?.connectionPassword; - if (recoveringRejection && authMethod === AuthMethodId.MicrosoftEntraID) { - ClustersClient.discardEntraPinForDifferentTenant( - clusterId, - updatedConnection?.secrets.entraIdAuthConfig?.tenantId, - ); - } - if (updatedConnection && authMethod && !(authMethod === AuthMethodId.NativeAuth && (!username || !password))) { - const connectionString = new DocumentDBConnectionString(updatedConnection.secrets.connectionString); - - CredentialCache.setAuthCredentials( - node.cluster.clusterId, - authMethod, - connectionString.toString(), - username && password ? { connectionUser: username, connectionPassword: password } : undefined, - node.cluster.emulatorConfiguration, - updatedConnection.secrets.entraIdAuthConfig, - updatedConnection.secrets.managedIdentityAuthConfig, - ); - } else { - // Clear stale credentials so the tree can prompt from storage. - CredentialCache.deleteCredentials(node.cluster.clusterId); - } - if (recoveringRejection && updatedConnection) { - ClustersClient.clearCredentialRejection(clusterId, epoch); - } - - shutdownEvaluator(node.cluster.clusterId); - - if (getRegisteredShellTerminals().some(({ info }) => info.clusterId === node.cluster.clusterId)) { - void vscode.window.showInformationMessage( - l10n.t( - "Credentials updated. New connections will use them. Open shells for '{cluster}' keep their current connection until you close them.", - { cluster: node.cluster.name }, - ), - { modal: true }, - ); - } + const changed = await saveConnectionEdit( + node, + async (isCurrent) => { + wizardContext.isRecoveryCurrent = isCurrent; + await wizard.execute(); + return wizardContext.credentialsSaved === true; + }, + { + canStart: isRecoveryCurrent, + publishCredentials: (updated): void => { + if (!updated || !isConnection(updated)) { + return; + } + const authMethod = authMethodFromString(updated.properties.selectedAuthMethod); + const native = updated.secrets.nativeAuthConfig; + if ( + !authMethod || + (authMethod === AuthMethodId.NativeAuth && (!native?.connectionUser || !native.connectionPassword)) + ) { + return; + } + CredentialCache.setAuthCredentials( + clusterId, + authMethod, + new DocumentDBConnectionString(updated.secrets.connectionString).toString(), + native?.connectionUser && native.connectionPassword ? native : undefined, + node.cluster.emulatorConfiguration, + updated.secrets.entraIdAuthConfig, + updated.secrets.managedIdentityAuthConfig, + ); + }, + }, + ); // When the node is in an error state, only clear it if the user chose to reconnect. // Clearing the error state triggers a fresh connection attempt on refresh. - if (node.id && wizardContext.isErrorState) { + if (wizardContext.credentialsSaved && node.id && wizardContext.isErrorState) { if (wizardContext.reconnectAfterError) { ext.connectionsBranchDataProvider.resetNodeErrorState(node.id); context.telemetry.properties.reconnected = 'true'; @@ -218,4 +192,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD } await refreshView(context, Views.ConnectionsView); + if (changed) { + await offerShellDisconnect(node); + } } diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index 0e1da1664..6bd272cc7 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -14,6 +14,7 @@ import { getDataAtPath } from '../utils/slickgrid/mongo/toSlickGridTable'; import { toSlickGridTree, type TreeData } from '../utils/slickgrid/mongo/toSlickGridTree'; import { type QueryInsightsStage2Response } from '../webviews/documentdb/collectionView/types/queryInsights'; import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; +import { isRetiredConnectionBinding } from './connectionBindingRetirement'; import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { runWithClient } from './runWithClient'; import { SchemaStore } from './SchemaStore'; @@ -91,6 +92,7 @@ export class ClusterSession { const { clusterId, fingerprint } = this.binding; return ( epoch === ClustersClient.getEpoch(clusterId) && + !isRetiredConnectionBinding(this.binding) && ClustersClient.getLatchReason(clusterId) === undefined && ClustersClient.getBinding(clusterId)?.fingerprint === fingerprint ); @@ -106,7 +108,9 @@ export class ClusterSession { if (signal?.aborted) { throw new UserCancelledError('staleCollectionViewOperation'); } - const reason = ClustersClient.getLatchReason(this.binding.clusterId); + const reason = isRetiredConnectionBinding(this.binding) + ? 'credentialsChanged' + : ClustersClient.getLatchReason(this.binding.clusterId); if (reason) { throw new ConnectionUnavailableError(reason); } diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index e02da895e..511803848 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -322,6 +322,25 @@ describe('regular connection startup diagnostics', () => { expect(ClustersClient.getBinding(clusterId)).toBe(current.binding); }); + it('does not let a retired view use a new client with the same fingerprint', async (): Promise => { + const old = await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + ClustersClient.latch(clusterId, 'credentialsUpdating'); + ClustersClient.retireBoundViews(clusterId); + await ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); + ClustersClient.unlatch(clusterId); + + await expect(ClustersClient.resolveBoundClient(old.binding)).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + expect(mockConnect).toHaveBeenCalledOnce(); + const current = await ClustersClient.getClient(clusterId); + expect(current.binding.fingerprint).toBe(old.binding.fingerprint); + expect(current.generation).toBeGreaterThan(old.generation); + expect(() => session.assertAvailable()).toThrow(expect.objectContaining({ reason: 'credentialsChanged' })); + await expect(ClustersClient.resolveBoundClient(current.binding)).resolves.toBe(current); + }); + it('keeps session paging and schema accumulation on a same-identity replacement', async (): Promise => { const original = await ClustersClient.connectInteractive(clusterId); const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); @@ -1052,6 +1071,23 @@ describe('regular connection startup diagnostics', () => { expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); }); + it('closes a fenced client without advancing the epoch again or discarding the identity pin', async () => { + await ClustersClient.connectInteractive(clusterId); + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + expect(identity).toBeDefined(); + const epoch = ClustersClient.getEpoch(clusterId); + + ClustersClient.latch(clusterId, 'userDisconnected'); + await ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); + + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch + 1); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(identity); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + + ClustersClient.unlatch(clusterId); + await expect(ClustersClient.getClient(clusterId)).resolves.toBeDefined(); + }); + it.each([false, true])('a stale replacement waiter has only one retry (latched: %s)', async (latch) => { const cached = await ClustersClient.connectInteractive(clusterId); poolEvents.emit('topologyClosed'); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index dd72e7759..643b43f66 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -52,6 +52,7 @@ import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { readJwtTimes } from './auth/tokenExpiry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; +import { isRetiredConnectionBinding, retireConnectionBindings } from './connectionBindingRetirement'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; @@ -296,6 +297,10 @@ export class ClustersClient { return ClustersClient._lastVerifiedIdentities.get(clusterId); } + public static clearLastVerifiedIdentity(clusterId: string): void { + ClustersClient._lastVerifiedIdentities.delete(clusterId); + } + /** A saved, explicit tenant change must not silently use the previous tenant's pin. */ public static discardEntraPinForDifferentTenant(clusterId: string, tenantId: string | undefined): void { const identity = ClustersClient.getEntraPin(clusterId); @@ -839,11 +844,14 @@ export class ClustersClient { } /** A surface can follow new generations, but never start or use a client for a different identity. */ - public static resolveBoundClient( + public static async resolveBoundClient( binding: ConnectionBinding, options?: { readonly background?: boolean; readonly trigger?: ClientStartupTrigger }, ): Promise { - return ClustersClient.acquireClient( + if (isRetiredConnectionBinding(binding)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + const client = await ClustersClient.acquireClient( binding.clusterId, undefined, undefined, @@ -852,6 +860,14 @@ export class ClustersClient { options?.background === true, binding.fingerprint, ); + if (isRetiredConnectionBinding(binding)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + return client; + } + + public static retireBoundViews(clusterId: string): void { + retireConnectionBindings(clusterId, ClustersClient._generations.get(clusterId) ?? 0); } /** Publish only after explicit sign-in and database startup succeed. The prior pin stays intact until then. */ @@ -1178,13 +1194,22 @@ export class ClustersClient { return ClustersClient._clients.get(clusterId)?._srvResolution; } - public static async deleteClient(clusterId: string): Promise { - ClustersClient.invalidate(clusterId); + public static async deleteClient( + clusterId: string, + options?: { readonly alreadyInvalidated: boolean }, + ): Promise { + if (!options?.alreadyInvalidated) { + ClustersClient.invalidate(clusterId); + } const client = ClustersClient._clients.get(clusterId); if (client) { ClustersClient._clients.delete(clusterId); - SchemaStore.getInstance().clearCluster(clusterId); client._closed = true; + } + if (client || options?.alreadyInvalidated) { + SchemaStore.getInstance().clearCluster(clusterId); + } + if (client) { await client._mongoClient.close(true); } } diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index 23a91d37a..a5b81c0ef 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -37,6 +37,7 @@ import { createMongoDocument } from '../commands/createDocument/createDocument'; import { deleteCollection } from '../commands/deleteCollection/deleteCollection'; import { deleteAzureDatabase } from '../commands/deleteDatabase/deleteDatabase'; import { diagnoseConnection } from '../commands/diagnoseConnection/diagnoseConnection'; +import { connectDisconnected, disconnect } from '../commands/disconnect/disconnect'; import { filterProviderContent } from '../commands/discoveryService.filterProviderContent/filterProviderContent'; import { manageCredentials } from '../commands/discoveryService.manageCredentials/manageCredentials'; import { exportEntireCollection, exportQueryResults } from '../commands/exportDocuments/exportDocuments'; @@ -1014,6 +1015,11 @@ export class ClustersExtension implements vscode.Disposable { 'vscode-documentdb.command.internal.retry', withTreeNodeCommandCorrelation(retryAuthentication), ); + registerCommandWithTreeNodeUnwrapping('vscode-documentdb.command.disconnect', disconnect); + registerCommandWithTreeNodeUnwrapping( + 'vscode-documentdb.command.internal.connectDisconnected', + withTreeNodeCommandCorrelation(connectDisconnected), + ); registerCommandWithTreeNodeUnwrapping( 'vscode-documentdb.command.signInAgain', withTreeNodeCommandCorrelation(signInAgain), diff --git a/src/documentdb/ConnectionUnavailableError.ts b/src/documentdb/ConnectionUnavailableError.ts index 1db3cfff2..dd8404caf 100644 --- a/src/documentdb/ConnectionUnavailableError.ts +++ b/src/documentdb/ConnectionUnavailableError.ts @@ -9,6 +9,7 @@ export type ConnectionUnavailableReason = | 'signInRequired' | 'credentialsRejected' | 'credentialsMissing' + | 'credentialsUpdating' | 'credentialsChanged' | 'identityChanged' | 'userDisconnected' diff --git a/src/documentdb/connectionBindingRetirement.ts b/src/documentdb/connectionBindingRetirement.ts new file mode 100644 index 000000000..cedb5ba99 --- /dev/null +++ b/src/documentdb/connectionBindingRetirement.ts @@ -0,0 +1,17 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type ConnectionBinding } from './ClustersClient'; + +const retiredThroughGeneration = new Map(); + +export function retireConnectionBindings(clusterId: string, generation: number): void { + retiredThroughGeneration.set(clusterId, Math.max(retiredThroughGeneration.get(clusterId) ?? 0, generation)); +} + +export function isRetiredConnectionBinding({ clusterId, generation }: ConnectionBinding): boolean { + const retiredThrough = retiredThroughGeneration.get(clusterId); + return retiredThrough !== undefined && generation <= retiredThrough; +} diff --git a/src/documentdb/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts new file mode 100644 index 000000000..1c1ecab89 --- /dev/null +++ b/src/documentdb/connectionTeardown.test.ts @@ -0,0 +1,295 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import * as l10n from '@vscode/l10n'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; +import { + commitTeardown, + confirmTeardown, + latchForTeardown, + teardownConnection, + withConnectionRemoval, +} from './connectionTeardown'; + +const mocks = vi.hoisted(() => ({ + getSetting: vi.fn(), + getConflictingTasks: vi.fn(), + getLatchReason: vi.fn(), + getEpoch: vi.fn(), + latch: vi.fn(), + unlatch: vi.fn(), + deleteClient: vi.fn(), + clearLastVerifiedIdentity: vi.fn(), + deleteCredentials: vi.fn(), + clearEntraTokenFailure: vi.fn(), + getRegisteredShellTerminals: vi.fn(), + getPlaygroundEvaluators: vi.fn(), + stopPlaygroundEvaluator: vi.fn(), + event: vi.fn(), +})); + +vi.mock('@microsoft/vscode-azext-utils', () => ({ + UserCancelledError: class UserCancelledError extends Error {}, + callWithTelemetryAndErrorHandling: async ( + event: string, + callback: (context: { telemetry: object; errorHandling: object }) => Promise, + ): Promise => { + const telemetry = { properties: {}, measurements: {} }; + try { + await callback({ telemetry, errorHandling: {} }); + } catch (error) { + if (!(error instanceof UserCancelledError)) { + throw error; + } + } finally { + mocks.event(event, telemetry); + } + }, +})); +vi.mock('../services/SettingsService', () => ({ SettingsService: { getSetting: mocks.getSetting } })); +vi.mock('../services/taskService/taskService', () => ({ + TaskService: { getConflictingTasks: mocks.getConflictingTasks }, +})); +vi.mock('./ClustersClient', () => ({ ClustersClient: { ...mocks, exists: () => true } })); +vi.mock('./CredentialCache', () => ({ CredentialCache: { deleteCredentials: mocks.deleteCredentials } })); +vi.mock('./auth/entraErrors/entraTokenFailures', () => ({ clearEntraTokenFailure: mocks.clearEntraTokenFailure })); +vi.mock('./shell/ShellTerminalLinkProvider', () => ({ + getRegisteredShellTerminals: mocks.getRegisteredShellTerminals, +})); +vi.mock('../commands/playground/executePlaygroundCode', () => ({ + getPlaygroundEvaluators: mocks.getPlaygroundEvaluators, + stopPlaygroundEvaluator: mocks.stopPlaygroundEvaluator, +})); + +const clusterId = 'example-cluster'; +const otherId = 'other-cluster'; +const refreshTree = vi.fn(); +const showWarning = vi.mocked(vscode.window.showWarningMessage); +const showError = vi.mocked(vscode.window.showErrorMessage); +const registrations: vscode.Disposable[] = []; + +function register(kind: ConnectionSurface['kind'], dirty = false, target = clusterId): ConnectionSurface { + const surface = { clusterId: target, kind, isDirty: () => dirty, disable: vi.fn(), dispose: vi.fn() }; + registrations.push(registerConnectionSurface(surface)); + return surface; +} + +describe('connection teardown', () => { + beforeEach(() => { + vi.resetAllMocks(); + mocks.getConflictingTasks.mockReturnValue([]); + mocks.getRegisteredShellTerminals.mockReturnValue([]); + mocks.getPlaygroundEvaluators.mockReturnValue(new Map()); + vi.spyOn(vscode.l10n, 't').mockImplementation(l10n.t); + }); + + afterEach(() => { + for (const registration of registrations.splice(0)) { + registration.dispose(); + } + vi.restoreAllMocks(); + }); + + it.each([false, true])( + 'does not remove connections when the user cancels (chose Close all: %s)', + async (choseClose) => { + const draft = register('documentView', true); + const remove = vi.fn(); + if (choseClose) { + showWarning.mockImplementationOnce(async (_title, _options, ...items) => items[0]); + } + + await expect(withConnectionRemoval([clusterId, otherId], remove)).rejects.toBeInstanceOf( + UserCancelledError, + ); + + expect(showWarning).toHaveBeenCalledTimes(choseClose ? 2 : 1); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(remove).not.toHaveBeenCalled(); + }, + ); + + it('fences the whole batch before removal and leaves a surviving connection reconnectable', async () => { + const latches = new Map(); + const epochs = new Map(); + mocks.getLatchReason.mockImplementation((id: string) => latches.get(id)); + mocks.getEpoch.mockImplementation((id: string) => epochs.get(id) ?? 0); + mocks.latch.mockImplementation((id: string, reason: string) => { + latches.set(id, reason); + epochs.set(id, (epochs.get(id) ?? 0) + 1); + }); + mocks.unlatch.mockImplementation((id: string) => { + latches.delete(id); + }); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + const draft = register('documentView', true); + const untouchedView = register('documentView', true, otherId); + const failedDelete = new Error('Storage write failed'); + + await expect( + withConnectionRemoval([clusterId, otherId], async (remove) => { + await remove(clusterId, async () => { + expect(latches.get(otherId)).toBe('connectionRemoved'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + throw failedDelete; + }); + }), + ).rejects.toBe(failedDelete); + + expect(latches.get(clusterId)).toBe('userDisconnected'); + expect(draft.disable).toHaveBeenLastCalledWith('userDisconnected'); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(latches.has(otherId)).toBe(false); + expect(untouchedView.disable).not.toHaveBeenCalled(); + }); + + it('skips the choice modal when there are no surfaces and leaves preflight read-only', async () => { + await expect(confirmTeardown(clusterId, 'userDisconnected')).resolves.toEqual({ + outcome: 'confirmed', + choice: 'close', + }); + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }); + + it.each(['userDisconnected', 'connectionRemoved'] as const)( + 'always asks before discarding dirty editors for %s, even with closeAll configured', + async (reason) => { + const draft = register('documentView', true); + mocks.getSetting.mockReturnValue('closeAll'); + await expect(confirmTeardown(clusterId, reason)).resolves.toEqual({ outcome: 'cancelled' }); + expect(showWarning).toHaveBeenCalledExactlyOnceWith( + 'Discard unsaved document changes?', + expect.objectContaining({ modal: true }), + 'Discard changes', + ); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + }, + ); + + it('honors modal cancellation without changing the connection', async () => { + const draft = register('documentView', true); + await expect(teardownConnection(clusterId, 'userDisconnected', refreshTree)).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(showWarning).toHaveBeenCalledExactlyOnceWith( + 'Disconnect?', + expect.objectContaining({ modal: true }), + 'Close all', + 'Keep open (disabled)', + ); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + }); + + it('names a task before asking what to do with tabs', async () => { + register('collectionView'); + mocks.getConflictingTasks.mockReturnValue([{ taskName: 'Copy orders', taskType: 'copy' }]); + await expect(confirmTeardown(clusterId, 'userDisconnected')).resolves.toEqual({ outcome: 'blockedByTask' }); + expect(showError).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ modal: true, detail: expect.stringContaining('Copy orders') }), + ); + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + }); + + it('blocks a lease started during the modal without mutating surfaces, cache or workers', async () => { + const draft = register('documentView', true); + showWarning.mockImplementationOnce(async (_title, _options, ...items) => { + mocks.getConflictingTasks.mockReturnValue([{ taskName: 'Export documents', taskType: 'export' }]); + return items[1]; + }); + + await expect(teardownConnection(clusterId, 'userDisconnected', refreshTree)).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(showError).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ modal: true, detail: expect.stringContaining('Export documents') }), + ); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(mocks.stopPlaygroundEvaluator).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + expect(refreshTree).not.toHaveBeenCalled(); + expect(mocks.event).toHaveBeenCalledExactlyOnceWith( + 'connection.disconnect', + expect.objectContaining({ properties: expect.objectContaining({ blockedByTask: 'true' }) }), + ); + }); + + it('fences once, disables all matching surfaces, stops only matching workers, and keeps credentials and pin', async () => { + const surfaces = [register('documentView', true), register('collectionView'), register('clusterDashboard')]; + const unrelated = register('documentView', true, otherId); + const disconnect = vi.fn(); + const otherShell = vi.fn(); + mocks.getRegisteredShellTerminals.mockReturnValue([ + { info: { clusterId }, disconnect }, + { info: { clusterId: otherId }, disconnect: otherShell }, + ]); + mocks.getPlaygroundEvaluators.mockReturnValue(new Map([[clusterId, {}]])); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); + for (const surface of surfaces) { + expect(mocks.latch).toHaveBeenCalledBefore(vi.mocked(surface.disable)); + expect(surface.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(surface.dispose).not.toHaveBeenCalled(); + } + expect(unrelated.disable).not.toHaveBeenCalled(); + expect(disconnect).toHaveBeenCalledOnce(); + expect(otherShell).not.toHaveBeenCalled(); + expect(mocks.stopPlaygroundEvaluator).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.deleteClient).toHaveBeenCalledExactlyOnceWith(clusterId, { alreadyInvalidated: true }); + expect(mocks.deleteCredentials).not.toHaveBeenCalled(); + expect(mocks.clearLastVerifiedIdentity).not.toHaveBeenCalled(); + expect(mocks.clearEntraTokenFailure).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(refreshTree).toHaveBeenCalledOnce(); + expect(mocks.event).toHaveBeenCalledExactlyOnceWith('connection.disconnect', { + properties: { source: 'command', surfacesChoice: 'keepOpenDisabled', blockedByTask: 'false' }, + measurements: { surfaceCount: 3, shellCount: 1, playgroundCount: 1 }, + maskEntireErrorMessage: true, + }); + }); + + it('closes surfaces and drops credentials only when requested, without latching a fenced target again', async () => { + const draft = register('documentView', true); + mocks.getLatchReason.mockReturnValue('connectionRemoved'); + await expect( + commitTeardown(clusterId, { + reason: 'connectionRemoved', + choice: 'close', + alreadyLatched: true, + dropCredentials: true, + refreshTree, + }), + ).resolves.toBe('committed'); + expect(showWarning).not.toHaveBeenCalled(); + expect(draft.dispose).toHaveBeenCalledOnce(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteCredentials).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.clearLastVerifiedIdentity).toHaveBeenCalledExactlyOnceWith(clusterId); + }); + + it('does not partially latch a batch when a descendant is blocked', () => { + mocks.getConflictingTasks.mockImplementation(({ clusterId: id }: { clusterId: string }) => + id === otherId ? [{ taskName: 'Import', taskType: 'import' }] : [], + ); + expect(latchForTeardown([clusterId, otherId], 'connectionRemoved')).toBe(false); + expect(mocks.latch).not.toHaveBeenCalled(); + }); +}); diff --git a/src/documentdb/connectionTeardown.ts b/src/documentdb/connectionTeardown.ts new file mode 100644 index 000000000..a0e280eef --- /dev/null +++ b/src/documentdb/connectionTeardown.ts @@ -0,0 +1,337 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { + callWithTelemetryAndErrorHandling, + UserCancelledError, + type IActionContext, +} from '@microsoft/vscode-azext-utils'; +import * as vscode from 'vscode'; +import { getPlaygroundEvaluators, stopPlaygroundEvaluator } from '../commands/playground/executePlaygroundCode'; +import { SettingsService } from '../services/SettingsService'; +import { checkCanProceedAndInformUser } from '../services/taskService/resourceUsageHelper'; +import { TaskService } from '../services/taskService/taskService'; +import { settingsKeys } from '../settingsKeys'; +import { clearEntraTokenFailure } from './auth/entraErrors/entraTokenFailures'; +import { ClustersClient } from './ClustersClient'; +import { getConnectionSurfaces } from './connectionSurfaces'; +import { CredentialCache } from './CredentialCache'; +import { getRegisteredShellTerminals } from './shell/ShellTerminalLinkProvider'; + +export type TeardownReason = 'userDisconnected' | 'connectionRemoved' | 'credentialsChanged'; +export type TeardownChoice = 'close' | 'keepOpenDisabled'; + +type TeardownConfirmation = + | { readonly outcome: 'confirmed'; readonly choice: TeardownChoice } + | { readonly outcome: 'blockedByTask' | 'cancelled' }; + +export interface TeardownOptions { + readonly reason: TeardownReason; + readonly choice: TeardownChoice; + readonly dropCredentials?: boolean; + /** A caller that fenced a batch or a save must still hold the matching latch. */ + readonly alreadyLatched?: boolean; + readonly refreshTree: () => void; +} + +function clusterIds(target: string | readonly string[]): readonly string[] { + return typeof target === 'string' ? [target] : [...new Set(target)]; +} + +function operationName(intent: TeardownReason): string { + switch (intent) { + case 'connectionRemoved': + return vscode.l10n.t('remove this connection'); + case 'credentialsChanged': + return vscode.l10n.t('update this connection'); + case 'userDisconnected': + return vscode.l10n.t('disconnect this connection'); + } +} + +/** Read-only preflight. A folder can ask once for all its descendants. */ +export async function confirmTeardown( + target: string | readonly string[], + intent: TeardownReason, +): Promise { + const ids = clusterIds(target); + for (const clusterId of ids) { + if (!(await checkCanProceedAndInformUser({ clusterId }, operationName(intent)))) { + return { outcome: 'blockedByTask' }; + } + } + + if (intent === 'credentialsChanged') { + return { outcome: 'confirmed', choice: 'keepOpenDisabled' }; + } + + const setting = SettingsService.getSetting(settingsKeys.openTabsOnDisconnect); + let choice: TeardownChoice = setting === 'keepOpenDisabled' ? 'keepOpenDisabled' : 'close'; + const closeAll = vscode.l10n.t('Close all'); + if ( + setting !== 'closeAll' && + setting !== 'keepOpenDisabled' && + ids.some((id) => getConnectionSurfaces(id).length) + ) { + const keepOpen = vscode.l10n.t('Keep open (disabled)'); + const selected = await vscode.window.showWarningMessage( + intent === 'connectionRemoved' ? vscode.l10n.t('Remove the connection?') : vscode.l10n.t('Disconnect?'), + { modal: true, detail: vscode.l10n.t('What should happen to the open tabs for this connection?') }, + closeAll, + keepOpen, + ); + if (selected !== closeAll && selected !== keepOpen) { + return { outcome: 'cancelled' }; + } + choice = selected === closeAll ? 'close' : 'keepOpenDisabled'; + } + + if (choice === 'close' && ids.some((id) => getConnectionSurfaces(id).some((surface) => surface.isDirty?.()))) { + const discard = vscode.l10n.t('Discard changes'); + const selected = await vscode.window.showWarningMessage( + vscode.l10n.t('Discard unsaved document changes?'), + { modal: true, detail: vscode.l10n.t('Closing these tabs will discard their unsaved changes.') }, + discard, + ); + if (selected !== discard) { + return { outcome: 'cancelled' }; + } + } + + return { outcome: 'confirmed', choice }; +} + +/** Check the whole batch and fence it synchronously, before any resource is changed. */ +export function latchForTeardown( + target: string | readonly string[], + reason: TeardownReason | 'credentialsUpdating', +): boolean { + const ids = clusterIds(target); + if (ids.some((clusterId) => TaskService.getConflictingTasks({ clusterId }).length > 0)) { + return false; + } + for (const clusterId of ids) { + ClustersClient.latch(clusterId, reason); + } + return true; +} + +export async function commitTeardown( + clusterId: string, + options: TeardownOptions, +): Promise<'committed' | 'blockedByTask' | 'superseded'> { + const { reason, choice, dropCredentials, alreadyLatched, refreshTree } = options; + if (alreadyLatched) { + if (ClustersClient.getLatchReason(clusterId) !== reason) { + return 'superseded'; + } + } else { + if ( + reason === 'userDisconnected' && + (!ClustersClient.exists(clusterId) || ClustersClient.getLatchReason(clusterId)) + ) { + return 'superseded'; + } + if (!latchForTeardown(clusterId, reason)) { + await checkCanProceedAndInformUser({ clusterId }, operationName(reason)); + return 'blockedByTask'; + } + } + + try { + for (const surface of getConnectionSurfaces(clusterId)) { + if (choice === 'close') { + surface.dispose(); + } else { + surface.disable(reason); + } + } + + for (const shell of getRegisteredShellTerminals()) { + if (shell.info.clusterId === clusterId) { + shell.disconnect?.(); + } + } + stopPlaygroundEvaluator(clusterId); + + const closing = ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); + clearEntraTokenFailure(clusterId); + if (dropCredentials) { + CredentialCache.deleteCredentials(clusterId); + ClustersClient.clearLastVerifiedIdentity(clusterId); + } + await closing; + } finally { + refreshTree(); + } + return 'committed'; +} + +export async function withConnectionRemoval( + ids: readonly string[], + remove: ( + removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise, + ) => Promise, +): Promise { + await reportTeardown(ids, 'connectionRemoved', async ({ telemetry }) => { + await removeConnections(ids, remove, telemetry.properties); + }); +} + +async function removeConnections( + ids: readonly string[], + remove: ( + removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise, + ) => Promise, + properties: IActionContext['telemetry']['properties'], +): Promise { + const confirmed = await confirmTeardown(ids, 'connectionRemoved'); + if (confirmed.outcome !== 'confirmed') { + properties.blockedByTask = confirmed.outcome === 'blockedByTask' ? 'true' : 'false'; + throw new UserCancelledError(); + } + properties.surfacesChoice = confirmed.choice; + + const targets = new Map( + clusterIds(ids).map((id) => [id, { previous: ClustersClient.getLatchReason(id), epoch: 0, started: false }]), + ); + if ( + [...targets.values()].some( + ({ previous }) => previous === 'credentialsUpdating' || previous === 'connectionRemoved', + ) + ) { + throw new Error(vscode.l10n.t('A connection is already being updated or removed. Try again when it finishes.')); + } + if (!latchForTeardown(ids, 'connectionRemoved')) { + properties.blockedByTask = 'true'; + for (const id of targets.keys()) { + if (!(await checkCanProceedAndInformUser({ clusterId: id }, operationName('connectionRemoved')))) { + break; + } + } + throw new UserCancelledError(); + } + for (const [id, target] of targets) { + target.epoch = ClustersClient.getEpoch(id); + } + + try { + await remove(async (id, deleteStored) => { + const target = targets.get(id); + if (!target || target.started || ClustersClient.getEpoch(id) !== target.epoch) { + throw new Error(vscode.l10n.t('The connections to remove changed. Refresh the tree and try again.')); + } + target.started = true; + const result = await commitTeardown(id, { + reason: 'connectionRemoved', + choice: confirmed.choice, + dropCredentials: true, + alreadyLatched: true, + refreshTree: () => {}, + }); + if (result !== 'committed' || ClustersClient.getEpoch(id) !== target.epoch) { + throw new Error(vscode.l10n.t('The connections to remove changed. Refresh the tree and try again.')); + } + await deleteStored(); + targets.delete(id); + }); + } finally { + for (const [id, target] of targets) { + if ( + ClustersClient.getEpoch(id) !== target.epoch || + ClustersClient.getLatchReason(id) !== 'connectionRemoved' + ) { + continue; + } + if (target.started) { + // A failed storage delete must not leave the surviving connection locked as removed. + ClustersClient.latch(id, 'userDisconnected'); + if (confirmed.choice === 'keepOpenDisabled') { + for (const surface of getConnectionSurfaces(id)) { + surface.disable('userDisconnected'); + } + } + } else if (target.previous) { + ClustersClient.latch(id, target.previous); + } else { + ClustersClient.unlatch(id); + } + } + } +} + +async function reportTeardown( + ids: readonly string[], + reason: TeardownReason, + operation: (context: IActionContext) => Promise, +): Promise { + let cancellation: UserCancelledError | undefined; + await callWithTelemetryAndErrorHandling('connection.disconnect', async (context) => { + context.errorHandling.suppressDisplay = true; + context.errorHandling.rethrow = true; + context.telemetry.maskEntireErrorMessage = true; + context.telemetry.properties.source = { + userDisconnected: 'command', + connectionRemoved: 'remove', + credentialsChanged: 'credentialsChanged', + }[reason]; + context.telemetry.properties.surfacesChoice = 'none'; + context.telemetry.properties.blockedByTask = 'false'; + const targets = new Set(ids); + context.telemetry.measurements.surfaceCount = [...targets].reduce( + (total, id) => total + getConnectionSurfaces(id).length, + 0, + ); + context.telemetry.measurements.shellCount = getRegisteredShellTerminals().filter((shell) => + targets.has(shell.info.clusterId), + ).length; + const playgrounds = getPlaygroundEvaluators(); + context.telemetry.measurements.playgroundCount = [...targets].filter((id) => playgrounds.has(id)).length; + try { + await operation(context); + } catch (error) { + if (error instanceof UserCancelledError) { + cancellation = error; + } + throw error; + } + }); + // The telemetry wrapper records cancellation but does not propagate it, even with rethrow set. + if (cancellation) { + throw cancellation; + } +} + +/** The single-cluster confirm/commit path, with one event covering both phases. */ +export async function teardownConnection( + clusterId: string, + reason: TeardownReason, + refreshTree: () => void, +): Promise { + await reportTeardown([clusterId], reason, async (context) => { + const confirmed = await confirmTeardown(clusterId, reason); + if (confirmed.outcome !== 'confirmed') { + context.telemetry.properties.blockedByTask = confirmed.outcome === 'blockedByTask' ? 'true' : 'false'; + throw new UserCancelledError(); + } + context.telemetry.properties.surfacesChoice = confirmed.choice; + try { + const result = await commitTeardown(clusterId, { + reason, + choice: confirmed.choice, + dropCredentials: reason === 'connectionRemoved', + refreshTree, + }); + if (result === 'committed') { + return; + } + context.telemetry.properties.blockedByTask = result === 'blockedByTask' ? 'true' : 'false'; + } catch { + // Driver cleanup failures may contain connection details. Keep both UI and event bounded. + throw new Error(vscode.l10n.t('Could not finish closing the connection.')); + } + throw new UserCancelledError(); + }); +} diff --git a/src/documentdb/shell/DocumentDBShellPty.test.ts b/src/documentdb/shell/DocumentDBShellPty.test.ts index 5911adea3..44dd8b038 100644 --- a/src/documentdb/shell/DocumentDBShellPty.test.ts +++ b/src/documentdb/shell/DocumentDBShellPty.test.ts @@ -426,6 +426,31 @@ describe('DocumentDBShellPty', () => { expect(written).toContain('test result'); }); + it('should reset rejected input before the connection can reconnect', async () => { + const getLatchReason = vi + .spyOn(ClustersClient, 'getLatchReason') + .mockReturnValueOnce('userDisconnected') + .mockReturnValue(undefined); + mockEvaluate.mockResolvedValue({ + type: null, + printable: '"done"', + durationMs: 1, + }); + + pty.handleInput('rejected'); + pty.handleInput('\r'); + expect(written).toContain('Disconnected'); + expect(written).toContain('testdb> '); + + written = ''; + pty.handleInput('accepted'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('accepted', 80); + expect(getLatchReason).toHaveBeenCalled(); + }); + it('should display error message on evaluation failure', async () => { mockEvaluate.mockRejectedValue(new Error('Syntax error')); @@ -436,6 +461,27 @@ describe('DocumentDBShellPty', () => { expect(written).toContain('Syntax error'); }); + it('should suppress the worker termination error when Disconnect cancels evaluation', async () => { + let rejectEvaluation: (error: Error) => void = () => { + throw new Error('Expected evaluation to be pending'); + }; + mockEvaluate.mockImplementation( + () => + new Promise((_resolve, reject) => { + rejectEvaluation = reject; + }), + ); + + pty.handleInput('db.test.find()'); + pty.handleInput('\r'); + pty.disconnect(); + rejectEvaluation(new Error('Worker terminated')); + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(written).toContain('Disconnected'); + expect(written).not.toContain('Worker terminated'); + }); + it('should normalize bare \\n in multi-line error messages to \\r\\n', async () => { // Many driver / server error messages embed bare LFs to delimit // a multi-line explanation. Without normalization the terminal @@ -1528,6 +1574,32 @@ describe('DocumentDBShellPty', () => { expect(mockEvaluate).toHaveBeenNthCalledWith(1, 'show dbs', 80); expect(mockEvaluate).toHaveBeenNthCalledWith(2, 'use newdb', 80); }); + + it('should discard queued pasted commands when Disconnect cancels evaluation', async () => { + let rejectEvaluation: (error: Error) => void = () => { + throw new Error('Expected evaluation to be pending'); + }; + mockEvaluate + .mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectEvaluation = reject; + }), + ) + .mockResolvedValue({ + type: null, + printable: '"done"', + durationMs: 1, + }); + + pty.handleInput('show dbs\nuse newdb\n'); + pty.disconnect(); + rejectEvaluation(new Error('Worker terminated')); + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('show dbs', 80); + expect(written.split('testdb> ')).toHaveLength(2); + }); }); describe('multi-line paste dialog', () => { diff --git a/src/documentdb/shell/DocumentDBShellPty.ts b/src/documentdb/shell/DocumentDBShellPty.ts index a11ab46d3..a62471bed 100644 --- a/src/documentdb/shell/DocumentDBShellPty.ts +++ b/src/documentdb/shell/DocumentDBShellPty.ts @@ -122,6 +122,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { /** Unique session ID for correlating all events within this shell session. */ private readonly _shellSessionId: string = randomUUID(); + private _disconnectRevision = 0; /** Extension client whose metadata describes this cluster, captured once when the shell is created. */ private readonly _connectionCorrelationId?: string; /** Running count of commands evaluated in this session (for commandIndex measurement). */ @@ -263,6 +264,21 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { } } + /** Keep the terminal and its scrollback, but stop the database worker. */ + public disconnect(): void { + this._disconnectRevision += 1; + this._spinner?.stop(); + this._spinner = undefined; + this._evaluating = false; + this._inputHandler.clearPendingInput(); + this.writeLine(this._outputFormatter.formatSystemMessage(l10n.t('Disconnected'))); + this._sessionManager.killWorker(); + this._inputHandler.setEnabled(true); + if (!this._closed) { + this.showPrompt(); + } + } + /** * Associate this PTY with its terminal instance. * Called by the command handler after `createTerminal()`. @@ -484,6 +500,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // ─── Private: Session initialization ───────────────────────────────────── private async initializeSession(): Promise { + const disconnectRevision = this._disconnectRevision; try { const metadata = await callWithTelemetryAndErrorHandling('shell.sessionStart', async (context) => { context.errorHandling.suppressDisplay = true; @@ -502,6 +519,9 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { Object.assign(context.telemetry.properties, domainProps); return metadata; }); + if (disconnectRevision !== this._disconnectRevision) { + return; + } if (!metadata) { throw new UserCancelledError('shell.sessionStart'); } @@ -605,6 +625,9 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { this._initialInput = undefined; } } catch (error: unknown) { + if (disconnectRevision !== this._disconnectRevision) { + return; + } // Stop the connection spinner on failure this._spinner?.stop(); this._spinner = undefined; @@ -666,6 +689,14 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // ─── Private: Line handling ────────────────────────────────────────────── private async handleLineInput(line: string): Promise { + const disconnectRevision = this._disconnectRevision; + if (ClustersClient.getLatchReason(this._connectionInfo.clusterId)) { + this.writeLine(this._outputFormatter.formatSystemMessage(l10n.t('Disconnected'))); + if (!this._closed) { + this.showPrompt(); + } + return; + } const trimmed = line.trim(); // Empty line — just show a new prompt @@ -687,33 +718,37 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { try { await this.evaluateInput(trimmed); } catch (error: unknown) { - await this.handleEvalError(error); + if (disconnectRevision === this._disconnectRevision) { + await this.handleEvalError(error); + } } finally { - // Stop the spinner before writing results or the next prompt. - this._spinner?.stop(); - this._spinner = undefined; + if (disconnectRevision === this._disconnectRevision) { + this._spinner?.stop(); + this._spinner = undefined; - this._evaluating = false; + this._evaluating = false; - // If Ctrl+C was pressed, the interrupt handler already re-enabled - // input and showed a prompt — don't duplicate. - if (!this._interrupted) { - this._inputHandler.setEnabled(true); + // If Ctrl+C was pressed, the interrupt handler already re-enabled + // input and showed a prompt — don't duplicate. + if (!this._interrupted) { + this._inputHandler.setEnabled(true); - if (!this._closed) { - this.showPrompt(); + if (!this._closed) { + this.showPrompt(); - // Process any input that was queued during execution - // (e.g., remaining lines from a multi-line paste). - this._inputHandler.processPendingInput(); + // Process any input that was queued during execution + // (e.g., remaining lines from a multi-line paste). + this._inputHandler.processPendingInput(); + } } - } - this._interrupted = false; + this._interrupted = false; + } } } private async evaluateInput(input: string): Promise { + const disconnectRevision = this._disconnectRevision; this._commandCount++; const commandIndex = this._commandCount; const commandCategory = classifyCommand(input); @@ -739,25 +774,26 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { try { result = await this._sessionManager.evaluate(input, this._columns); } catch (evalError) { - // Ctrl+C kills the worker, producing a "Worker terminated" error. - // Re-classify as user cancellation for accurate telemetry. - if (this._interrupted) { + // Ctrl+C and Disconnect both kill the worker, producing a + // "Worker terminated" error. Re-classify intentional + // cancellation for accurate telemetry and UI behavior. + if (this._interrupted || disconnectRevision !== this._disconnectRevision) { throw new UserCancelledError('shell.eval'); } throw evalError; } - // Stop the spinner before writing any output so the spinner - // character doesn't collide with the result text. - this._spinner?.stop(); - this._spinner = undefined; - // If this eval was cancelled by Ctrl+C, skip output — the interrupt // handler already showed ^C and a new prompt. - if (this._interrupted) { + if (this._interrupted || disconnectRevision !== this._disconnectRevision) { return; } + // Stop the spinner before writing any output so the spinner + // character doesn't collide with the result text. + this._spinner?.stop(); + this._spinner = undefined; + // ── Post-eval telemetry ────────────────────────────────────── context.telemetry.properties.resultType = result.type ?? 'null'; @@ -794,9 +830,9 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { this._spinner?.stop(); this._spinner = undefined; - // Suppress errors from intentional Ctrl+C cancellation — the interrupt - // handler already showed ^C and a new prompt. - if (this._interrupted) { + // Suppress errors from intentional cancellation. Ctrl+C renders its own + // prompt, while Disconnect renders its own terminal status. + if (this._interrupted || error instanceof UserCancelledError) { return; } diff --git a/src/documentdb/shell/ShellInputHandler.ts b/src/documentdb/shell/ShellInputHandler.ts index b848ea808..5e6cd8b31 100644 --- a/src/documentdb/shell/ShellInputHandler.ts +++ b/src/documentdb/shell/ShellInputHandler.ts @@ -213,6 +213,13 @@ export class ShellInputHandler { } } + /** + * Discard input queued behind an evaluation that will no longer resume. + */ + clearPendingInput(): void { + this._pendingInput = ''; + } + /** * Get the current line buffer content. */ diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index 7e18eb3c4..7a5df24cf 100644 --- a/src/documentdb/shell/ShellSessionManager.test.ts +++ b/src/documentdb/shell/ShellSessionManager.test.ts @@ -22,6 +22,7 @@ import { recordEntraTokenFailure, resetEntraTokenFailuresForTests, } from '../auth/entraErrors/entraTokenFailures'; +import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; import { PlaygroundEvaluator } from '../playground/PlaygroundEvaluator'; import { type WorkerSessionCallbacks } from '../playground/WorkerSessionManager'; @@ -105,6 +106,22 @@ vi.mock('../playground/WorkerSessionManager', () => ({ describe('ShellSessionManager', () => { const clusterId = 'test-cluster-id'; + it('does not initialize or evaluate a worker while the cluster is disconnected', async () => { + const manager = new ShellSessionManager({ + clusterId, + clusterDisplayName: 'Test Cluster', + databaseName: 'test', + }); + ClustersClient.latch(clusterId, 'userDisconnected'); + try { + await expect(manager.initialize()).rejects.toMatchObject({ reason: 'userDisconnected' }); + await expect(manager.evaluate('db.stats()')).rejects.toMatchObject({ reason: 'userDisconnected' }); + } finally { + ClustersClient.unlatch(clusterId); + manager.dispose(); + } + }); + beforeEach(() => { vi.clearAllMocks(); resetEntraTokenFailuresForTests(); diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index 12d8b9a31..ac111d75f 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -9,6 +9,8 @@ import type * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; import { traceAuthFlow, traceAuthOperation, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; import { getBatchSizeSetting, getConnectionTimeoutMs } from '../../utils/workspacUtils'; +import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; import { AuthMethodId } from '../auth/AuthMethod'; import { @@ -197,6 +199,7 @@ export class ShellSessionManager implements vscode.Disposable { * @throws Error if initialization exceeds the configured timeout. */ async initialize(): Promise { + this.assertConnectionAvailable(); const initMsg = this.buildInitMessage(); if (!this._initialized || !this._workerManager.isAlive) { this._sessionInitMessage = initMsg; @@ -248,6 +251,7 @@ export class ShellSessionManager implements vscode.Disposable { * @returns The serializable execution result from the worker. */ async evaluate(code: string, terminalColumns?: number): Promise { + this.assertConnectionAvailable(); // Reconnect if the worker is not alive — handles all cases: // timeout kills, Ctrl+C cancellation, unexpected worker crashes. if (!this._initialized || !this._workerManager.isAlive) { @@ -259,6 +263,7 @@ export class ShellSessionManager implements vscode.Disposable { }); } await this._initPromise; + this.assertConnectionAvailable(); this._callbacks?.onReconnected?.(); } @@ -296,6 +301,13 @@ export class ShellSessionManager implements vscode.Disposable { this._initialized = false; } + private assertConnectionAvailable(): void { + const reason = ClustersClient.getLatchReason(this._connectionInfo.clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + } + // ─── Private: Init message ─────────────────────────────────────────────── private buildInitMessage(): MainToWorkerMessage & { type: 'init' } { diff --git a/src/documentdb/shell/ShellTerminalLinkProvider.ts b/src/documentdb/shell/ShellTerminalLinkProvider.ts index b300a6cc6..0a404eca1 100644 --- a/src/documentdb/shell/ShellTerminalLinkProvider.ts +++ b/src/documentdb/shell/ShellTerminalLinkProvider.ts @@ -39,7 +39,10 @@ export interface ShellTerminalInfo { * Populated by the shell command handler when a terminal is created, * queried by the link provider to build navigation actions. */ -const shellTerminalRegistry = new Map(); +const shellTerminalRegistry = new Map< + vscode.Terminal, + { readonly infoProvider: ShellTerminalInfoProvider; readonly disconnect?: () => void } +>(); /** * A function that returns the current {@link ShellTerminalInfo} for a shell terminal. @@ -51,8 +54,12 @@ export type ShellTerminalInfoProvider = () => ShellTerminalInfo; * Register a shell terminal in the link provider registry. * Call this after `vscode.window.createTerminal()` in the command handler. */ -export function registerShellTerminal(terminal: vscode.Terminal, infoProvider: ShellTerminalInfoProvider): void { - shellTerminalRegistry.set(terminal, infoProvider); +export function registerShellTerminal( + terminal: vscode.Terminal, + infoProvider: ShellTerminalInfoProvider, + disconnect?: () => void, +): void { + shellTerminalRegistry.set(terminal, { infoProvider, disconnect }); } /** @@ -70,10 +77,12 @@ export function unregisterShellTerminal(terminal: vscode.Terminal): void { export function getRegisteredShellTerminals(): ReadonlyArray<{ terminal: vscode.Terminal; info: ShellTerminalInfo; + disconnect?: () => void; }> { - return Array.from(shellTerminalRegistry.entries()).map(([terminal, provider]) => ({ + return Array.from(shellTerminalRegistry.entries()).map(([terminal, { infoProvider, disconnect }]) => ({ terminal, - info: provider(), + info: infoProvider(), + disconnect, })); } @@ -213,7 +222,7 @@ type ShellTerminalLink = CollectionViewTerminalLink | PlaygroundTerminalLink | S */ export class ShellTerminalLinkProvider implements vscode.TerminalLinkProvider { provideTerminalLinks(context: vscode.TerminalLinkContext): ShellTerminalLink[] { - const infoProvider = shellTerminalRegistry.get(context.terminal); + const infoProvider = shellTerminalRegistry.get(context.terminal)?.infoProvider; if (!infoProvider) { // Not a shell terminal — no links return []; diff --git a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts index 36abd6522..9bfed4e60 100644 --- a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts +++ b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts @@ -112,6 +112,7 @@ vi.mock('../../../documentdb/ClustersClient', () => ({ ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), + exists: vi.fn(() => false), getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), }, diff --git a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts index 8b6ee7b5d..47ce2ccc0 100644 --- a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts +++ b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts @@ -346,7 +346,7 @@ export class AtlasClusterItem extends ClusterItemBase { getTreeItem(): vscode.TreeItem { return { id: this.id, - contextValue: this.contextValue, + contextValue: this.getClusterTreeItemContextValue(), label: this.cluster.name, description: this.buildDescription(), tooltip: this.buildTooltip(), diff --git a/src/services/taskService/taskService.test.ts b/src/services/taskService/taskService.test.ts index 7bb11e4d0..ce4da3236 100644 --- a/src/services/taskService/taskService.test.ts +++ b/src/services/taskService/taskService.test.ts @@ -6,6 +6,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { Task, TaskService, TaskState, type TaskStatus } from './taskService'; +import { type ResourceDefinition, type ResourceTrackingTask } from './taskServiceResourceTracking'; + +const { latchReasons } = vi.hoisted(() => ({ + latchReasons: new Map(), +})); + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { + getLatchReason: (clusterId: string): string | undefined => latchReasons.get(clusterId), + }, +})); // Mock extensionVariables (ext) module vi.mock('../../extensionVariables', () => ({ @@ -75,13 +86,14 @@ vi.mock('vscode', () => ({ /** * Simple test task implementation */ -class TestTask extends Task { +class TestTask extends Task implements ResourceTrackingTask { public readonly type = 'test'; public readonly name: string; private readonly workSteps: number; private readonly stepDuration: number; private readonly shouldFail: boolean; private readonly failAtStep?: number; + private readonly resources: ResourceDefinition[]; constructor( name: string, @@ -90,6 +102,7 @@ class TestTask extends Task { stepDuration?: number; shouldFail?: boolean; failAtStep?: number; + resources?: ResourceDefinition[]; } = {}, ) { super(); @@ -98,6 +111,11 @@ class TestTask extends Task { this.stepDuration = options.stepDuration ?? 20; this.shouldFail = options.shouldFail ?? false; this.failAtStep = options.failAtStep; + this.resources = options.resources ?? []; + } + + public getUsedResources(): ResourceDefinition[] { + return this.resources; } protected async doWork(signal: AbortSignal): Promise { @@ -160,6 +178,7 @@ describe('TaskService', () => { let taskService: typeof TaskService; beforeEach(() => { + latchReasons.clear(); // Clear the singleton state between tests taskService = TaskService; // Clear any existing tasks @@ -177,6 +196,75 @@ describe('TaskService', () => { expect(taskService.listTasks()).toContain(task); }); + it('exposes active resource leases to collection and folder conflict queries', () => { + const lease = taskService.acquireResourceLease( + { + clusterId: 'lease-cluster', + databaseName: 'database', + collectionName: 'collection', + }, + 'Export documents', + ); + + try { + expect( + taskService.getConflictingTasks({ + clusterId: 'lease-cluster', + databaseName: 'database', + collectionName: 'collection', + }), + ).toEqual([ + expect.objectContaining({ + taskName: 'Export documents', + taskType: 'resource-lease', + }), + ]); + expect(taskService.getConflictingTasks({ clusterId: 'lease-cluster' })).toHaveLength(1); + expect(taskService.findConflictingTasksForConnections(['lease-cluster'])).toHaveLength(1); + expect(taskService.findConflictingTasksForConnections(['other-cluster'])).toEqual([]); + expect( + taskService.getConflictingTasks({ + clusterId: 'lease-cluster', + databaseName: 'database', + collectionName: 'other-collection', + }), + ).toEqual([]); + } finally { + lease.dispose(); + lease.dispose(); + } + + expect(taskService.getConflictingTasks({ clusterId: 'lease-cluster' })).toEqual([]); + expect(taskService.findConflictingTasksForConnections(['lease-cluster'])).toEqual([]); + }); + + it('refuses task and lease admission with the cluster latch reason', async () => { + const resource = { + clusterId: 'latched-cluster', + databaseName: 'database', + collectionName: 'collection', + }; + const task = new TestTask('Blocked Task', { resources: [resource] }); + latchReasons.set(resource.clusterId, 'credentialsChanged'); + + expect(() => taskService.registerTask(task)).toThrowError( + expect.objectContaining({ name: 'ConnectionUnavailableError', reason: 'credentialsChanged' }), + ); + expect(() => taskService.acquireResourceLease(resource, 'Blocked transfer')).toThrowError( + expect.objectContaining({ name: 'ConnectionUnavailableError', reason: 'credentialsChanged' }), + ); + + latchReasons.delete(resource.clusterId); + taskService.registerTask(task); + latchReasons.set(resource.clusterId, 'connectionRemoved'); + + await expect(task.start()).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'connectionRemoved', + }); + expect(task.getStatus().state).toBe(TaskState.Pending); + }); + it('should track task progress and state transitions in correct order', async () => { const task = new TestTask('Progress Task', { workSteps: 5, stepDuration: 10 }); taskService.registerTask(task); diff --git a/src/services/taskService/taskService.ts b/src/services/taskService/taskService.ts index 1a8b2a9f4..16a116586 100644 --- a/src/services/taskService/taskService.ts +++ b/src/services/taskService/taskService.ts @@ -5,6 +5,8 @@ import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { ext } from '../../extensionVariables'; import { recordSurveyActivity } from '../survey/SurveyService'; import { @@ -99,6 +101,25 @@ export function isTerminalState(state: TaskState): boolean { return state === TaskState.Completed || state === TaskState.Failed || state === TaskState.Stopped; } +function getTaskUsedResources(task: Task): ResourceDefinition[] { + if (!('getUsedResources' in task) || typeof (task as ResourceTrackingTask).getUsedResources !== 'function') { + return []; + } + return (task as ResourceTrackingTask).getUsedResources(); +} + +function assertResourcesAdmitted(resources: ResourceDefinition[]): void { + for (const resource of resources) { + if (!resource.clusterId) { + continue; + } + const reason = ClustersClient.getLatchReason(resource.clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + } +} + /** * Abstract base class for long-running tasks managed by the TaskService. * @@ -270,6 +291,8 @@ export abstract class Task { throw new Error(vscode.l10n.t('Cannot start task in state: {0}', this._status.state)); } + assertResourcesAdmitted(getTaskUsedResources(this)); + ext.outputChannel.appendLine(vscode.l10n.t("○ Task '{taskName}' initializing...", { taskName: this.name })); this.updateStatus(TaskState.Initializing, vscode.l10n.t('Initializing task...'), 0); @@ -496,6 +519,15 @@ export interface TaskService { */ registerTask(task: Task): void; + /** + * Synchronously acquires a resource lease for work that is not represented by a Task. + * + * @param resource The resource used by the operation. + * @param label A user-readable operation label used in conflict reporting. + * @returns A disposable that releases the lease. Disposal is idempotent. + */ + acquireResourceLease(resource: ResourceDefinition, label: string): vscode.Disposable; + /** * Retrieves a task by its ID. * @@ -585,6 +617,10 @@ export interface TaskService { class TaskServiceImpl implements TaskService { private readonly tasks = new Map(); private readonly taskSubscriptions = new Map(); + private readonly resourceLeases = new Map< + string, + { readonly task: TaskInfo; readonly resource: ResourceDefinition } + >(); // Event emitters for the service events private readonly _onDidRegisterTask = new vscode.EventEmitter(); @@ -600,7 +636,11 @@ class TaskServiceImpl implements TaskService { public registerTask(task: Task): void { if (this.tasks.has(task.id)) { throw new Error(vscode.l10n.t('Task with ID {0} already exists', task.id)); - } // Subscribe to task events and aggregate them + } + + assertResourcesAdmitted(getTaskUsedResources(task)); + + // Subscribe to task events and aggregate them const subscriptions: vscode.Disposable[] = [ task.onDidChangeStatus((status) => { this._onDidChangeTaskStatus.fire({ taskId: task.id, status }); @@ -615,6 +655,30 @@ class TaskServiceImpl implements TaskService { this._onDidRegisterTask.fire(task); } + public acquireResourceLease(resource: ResourceDefinition, label: string): vscode.Disposable { + assertResourcesAdmitted([resource]); + + const leaseId = `resource-lease-${crypto.randomUUID()}`; + this.resourceLeases.set(leaseId, { + task: { + taskId: leaseId, + taskName: label, + taskType: 'resource-lease', + }, + resource: { ...resource }, + }); + + let disposed = false; + return { + dispose: (): void => { + if (!disposed) { + disposed = true; + this.resourceLeases.delete(leaseId); + } + }, + }; + } + public getTask(id: string): Task | undefined { return this.tasks.get(id); } @@ -654,20 +718,23 @@ class TaskServiceImpl implements TaskService { }); for (const task of activeTasks) { - // Check if task implements resource tracking - if ('getUsedResources' in task && typeof (task as ResourceTrackingTask).getUsedResources === 'function') { - const usedResources = (task as ResourceTrackingTask).getUsedResources(); + const usedResources = getTaskUsedResources(task); - // Check if any of the task's resources conflict with the requested resource - const hasConflict = usedResources.some((usedResource) => hasResourceConflict(resource, usedResource)); + // Check if any of the task's resources conflict with the requested resource + const hasConflict = usedResources.some((usedResource) => hasResourceConflict(resource, usedResource)); - if (hasConflict) { - conflictingTasks.push({ - taskId: task.id, - taskName: task.name, - taskType: task.type, - }); - } + if (hasConflict) { + conflictingTasks.push({ + taskId: task.id, + taskName: task.name, + taskType: task.type, + }); + } + } + + for (const lease of this.resourceLeases.values()) { + if (hasResourceConflict(resource, lease.resource)) { + conflictingTasks.push(lease.task); } } @@ -684,23 +751,24 @@ class TaskServiceImpl implements TaskService { }); for (const task of activeTasks) { - // Check if task implements resource tracking - if ('getUsedResources' in task && typeof (task as ResourceTrackingTask).getUsedResources === 'function') { - const resources = (task as ResourceTrackingTask).getUsedResources(); - - if (resources.length > 0) { - result.push({ - task: { - taskId: task.id, - taskName: task.name, - taskType: task.type, - }, - resources, - }); - } + const resources = getTaskUsedResources(task); + + if (resources.length > 0) { + result.push({ + task: { + taskId: task.id, + taskName: task.name, + taskType: task.type, + }, + resources, + }); } } + for (const lease of this.resourceLeases.values()) { + result.push({ task: lease.task, resources: [lease.resource] }); + } + return result; } diff --git a/src/settingsKeys.ts b/src/settingsKeys.ts index 22fbc0b30..a30b1733e 100644 --- a/src/settingsKeys.ts +++ b/src/settingsKeys.ts @@ -19,6 +19,7 @@ export namespace settingsKeys { // Connections & Discovery export const connectionTimeout = 'documentDB.connectionTimeout'; + export const openTabsOnDisconnect = 'documentDB.connections.openTabsOnDisconnect'; export const localPort = 'documentDB.local.port'; export const kubernetesLocalPortStrategy = 'documentDB.serviceDiscovery.kubernetes.portForward.localPortStrategy'; export const kubernetesLocalPortBase = 'documentDB.serviceDiscovery.kubernetes.portForward.localPortBase'; diff --git a/src/tree/connections-view/DocumentDBClusterItem.ts b/src/tree/connections-view/DocumentDBClusterItem.ts index 639b853f0..df2f60ac1 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.ts @@ -482,6 +482,10 @@ export class DocumentDBClusterItem extends ClusterItemBase { * state label (e.g. "Running"). */ public override getTreeItem(): vscode.TreeItem { - const treeItem = buildClusterTreeItem({ id: this.id, contextValue: this.contextValue, cluster: this.cluster }); + const treeItem = buildClusterTreeItem({ + id: this.id, + contextValue: this.getClusterTreeItemContextValue(), + cluster: this.cluster, + }); return { ...treeItem, description: this.descriptionOverride, @@ -327,7 +331,13 @@ class QuickStartClusterItem extends ClusterItemBase { } public override async getChildren(): Promise { + if (ClustersClient.getLatchReason(this.cluster.clusterId) === 'userDisconnected') { + return super.getChildren(); + } const preflight: QuickStartConnectionPreflightResult = await QuickStartService.prepareForConnection(this.alias); + if (ClustersClient.getLatchReason(this.cluster.clusterId) === 'userDisconnected') { + return super.getChildren(); + } if (preflight !== 'ready') { return buildPreflightChildren(this.id, preflight); } diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 104160095..a2ef48aa5 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -11,14 +11,17 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { connectDisconnected, disconnect } from '../../commands/disconnect/disconnect'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; +import { teardownConnection } from '../../documentdb/connectionTeardown'; import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { ShellCommandIds } from '../../documentdb/shell/constants'; import { Views } from '../../documentdb/Views'; import { type Experience } from '../../DocumentDBExperiences'; +import { ext } from '../../extensionVariables'; import { containsRetryNode, RETRY_NODE_ID_SUFFIX } from '../api/retryNode'; import { BaseExtendedTreeDataProvider } from '../BaseExtendedTreeDataProvider'; import { type BaseClusterModel, type TreeCluster } from '../models/BaseClusterModel'; @@ -83,12 +86,16 @@ vi.mock('../../documentdb/ClustersClient', () => ({ exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn(), getLatchReason: vi.fn(), + unlatch: vi.fn(), getEpoch: vi.fn(() => 0), getLastVerifiedIdentity: vi.fn(), reportFailure: vi.fn(), }, })); +vi.mock('../../documentdb/connectionTeardown', () => ({ teardownConnection: vi.fn() })); + +const notifyChildrenChanged = vi.fn(); vi.mock('../../extensionVariables', () => ({ ext: { settingsKeys: { @@ -98,6 +105,11 @@ vi.mock('../../extensionVariables', () => ({ appendLine: vi.fn(), debug: vi.fn(), }, + state: { notifyChildrenChanged: (...args: unknown[]) => notifyChildrenChanged(...args) }, + connectionsBranchDataProvider: { resetNodeErrorState: vi.fn(), refresh: vi.fn() }, + discoveryBranchDataProvider: { resetNodeErrorState: vi.fn(), refresh: vi.fn() }, + azureResourcesRUBranchDataProvider: { resetNodeErrorState: vi.fn(), refresh: vi.fn() }, + azureResourcesVCoreBranchDataProvider: { resetNodeErrorState: vi.fn(), refresh: vi.fn() }, }, })); @@ -451,6 +463,72 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl ); }); + it('shows only Connect while user-disconnected and uses cached settings on the same node after the click', async () => { + const node = new TestClusterItem({ ...makeCluster(), treeId: 'connectionsView/folder/cluster-1' }, null); + const context = {} as IActionContext; + const stableId = node.cluster.clusterId; + const treeId = node.id; + ClustersClientMock.exists.mockReturnValue(true); + expect(node.getTreeItem().contextValue?.split(';')).toContain('connected'); + ClustersClientMock.exists.mockReturnValue(false); + ClustersClientMock.getLatchReason.mockReturnValue('userDisconnected'); + + try { + expect(await node.getChildren()).toEqual([ + expect.objectContaining({ label: 'Reconnect', id: `${treeId}/connect`, commandArgs: [node] }), + ]); + expect(node.getTreeItem().contextValue?.split(';')).not.toContain('connected'); + expect(mockHasCredentials).not.toHaveBeenCalled(); + expect(ClustersClientMock.connectInteractive).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + + connectDisconnected(context, node); + expect(ClustersClientMock.unlatch).toHaveBeenCalledExactlyOnceWith(stableId); + expect(notifyChildrenChanged).toHaveBeenCalledExactlyOnceWith(treeId); + + ClustersClientMock.getLatchReason.mockReturnValue(undefined); + ClustersClientMock.connectInteractive.mockResolvedValueOnce( + makeClient(vi.fn().mockResolvedValue([{ name: 'database' }])), + ); + expect(await node.getChildren()).toEqual([expect.objectContaining({ id: 'database' })]); + expect(ClustersClientMock.connectInteractive).toHaveBeenCalledExactlyOnceWith( + stableId, + expect.any(AbortSignal), + expect.any(Function), + 'treeConnect', + ); + expect(node.getTreeItem().id).toBe(treeId); + + ClustersClientMock.getLatchReason.mockReturnValue('connectionRemoved'); + connectDisconnected(context, node); + expect(ClustersClientMock.unlatch).toHaveBeenCalledOnce(); + } finally { + ClustersClientMock.getLatchReason.mockReturnValue(undefined); + } + }); + + it('clears and refreshes only the owning discovery provider after Disconnect', async () => { + const node = new TestClusterItem({ ...makeCluster(), treeId: 'discoveryView/custom-source/cluster-1' }, null); + const context = { telemetry: { suppressAll: false } } as IActionContext; + ClustersClientMock.exists.mockReturnValue(true); + ClustersClientMock.getLatchReason.mockReturnValue(undefined); + + await disconnect(context, node); + + expect(teardownConnection).toHaveBeenCalledExactlyOnceWith( + node.cluster.clusterId, + 'userDisconnected', + expect.any(Function), + ); + const refreshTree = vi.mocked(teardownConnection).mock.calls[0][2]; + refreshTree(); + + expect(ext.discoveryBranchDataProvider.resetNodeErrorState).toHaveBeenCalledExactlyOnceWith(node.id); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + }); + it.each(['signInRequired', 'credentialsRejected'] as const)( 'offers Retry sign-in instead of Retry for %s and keeps the failed-expansion marker', async (reason): Promise => { diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index 686511c3f..bf64996b3 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -527,6 +527,11 @@ export abstract class ClusterItemBase { + const clusterId = this.cluster.clusterId; + const disconnected = (): boolean => ClustersClient.getLatchReason(clusterId) === 'userDisconnected'; + if (disconnected()) { + return this.createDisconnectedChildren(); + } ext.outputChannel.appendLine(l10n.t('Loading cluster details for "{cluster}"', { cluster: this.cluster.name })); const wasConnected = ClustersClient.exists(this.cluster.clusterId); @@ -538,7 +543,6 @@ export abstract class ClusterItemBase document.querySelector('.disconnectedOverlay[aria-modal="true"]'); const buttons = (): HTMLButtonElement[] => [ - ...(dialog()?.querySelectorAll('.disconnectedOverlayActions button') ?? []), + ...(dialog()?.querySelectorAll('.fui-DialogActions button') ?? []), ]; expect(host.querySelector('[inert] textarea')).toBe(draft); expect(draft?.value).toBe('unsaved edit'); diff --git a/src/webviews/components/DisconnectedOverlay.tsx b/src/webviews/components/DisconnectedOverlay.tsx index 781c15c76..0bc56d3f1 100644 --- a/src/webviews/components/DisconnectedOverlay.tsx +++ b/src/webviews/components/DisconnectedOverlay.tsx @@ -86,10 +86,13 @@ export function DisconnectedOverlay({ } }} > - +