From bac38284290ac55b7d3ecfcc4337148daf6a66a3 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 15:20:44 +0000 Subject: [PATCH 01/23] docs: record CP-4 teardown checkpoint before WI-7 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) 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..02bc0c836 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. @@ -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, "Connect" (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. @@ -1737,6 +1739,15 @@ 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. - **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. From d9c00de6a3c4c270812483d4cb036ea8cec4362d Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 15:28:36 +0000 Subject: [PATCH 02/23] feat: protect active transfers with task leases (WI-7 A5) Check the connection latch before admitting new work and include import/export leases in the existing task-conflict queries. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 4 + src/commands/dashboardBoundCommands.test.ts | 2 +- .../exportDocuments/exportDocuments.ts | 80 ++++++----- .../importDocuments/importDocuments.test.ts | 131 +++++++++++++++--- .../importDocuments/importDocuments.ts | 128 +++++++++-------- src/services/taskService/taskService.test.ts | 90 +++++++++++- src/services/taskService/taskService.ts | 122 ++++++++++++---- 7 files changed, 421 insertions(+), 136 deletions(-) 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 02bc0c836..370b49a89 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 @@ -1748,6 +1748,10 @@ behave as today. 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). - **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. diff --git a/src/commands/dashboardBoundCommands.test.ts b/src/commands/dashboardBoundCommands.test.ts index d8a2212c8..fd536b557 100644 --- a/src/commands/dashboardBoundCommands.test.ts +++ b/src/commands/dashboardBoundCommands.test.ts @@ -41,7 +41,7 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ }, })); 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() }, })); vi.mock('../documentdb/CredentialCache', () => ({ CredentialCache: { getCredentials: vi.fn(), hasCredentials: vi.fn(() => true) }, 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 4036425f2..072f6f721 100644 --- a/src/commands/importDocuments/importDocuments.test.ts +++ b/src/commands/importDocuments/importDocuments.test.ts @@ -4,16 +4,18 @@ *--------------------------------------------------------------------------------------------*/ import { type IActionContext } from '@microsoft/vscode-azext-utils'; -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 { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { DocumentDBExperience } from '../../DocumentDBExperiences'; +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() }, + ClustersClient: { getClient: vi.fn(), getLatchReason: vi.fn(), resolveBoundClient: vi.fn() }, isBulkWriteError: vi.fn(() => false), })); vi.mock('node:fs/promises', () => ({ @@ -29,14 +31,10 @@ vi.mock('../../extensionVariables', () => ({ }, })); vi.mock('../../utils/workspacUtils', () => ({ getRootPath: vi.fn() })); +vi.mock('../../utils/fs/appendToFile', () => ({ appendToFile: vi.fn() })); -it('does not import using a different identity selected while the file picker was open', async (): Promise => { - const binding: ConnectionBinding = { clusterId: 'cluster', fingerprint: 'original', generation: 1 }; - const insertDocuments = vi.fn(); - const replacement = { insertDocuments, getConnectionString: () => 'mongodb://example.test' }; - vi.mocked(ClustersClient.getClient).mockResolvedValue(replacement as unknown as ClustersClient); - - const source = new CollectionItem( +function createSource(): CollectionItem { + return new CollectionItem( { clusterId: 'cluster', treeId: 'folder/cluster', @@ -47,21 +45,41 @@ it('does not import using a different identity selected while the file picker wa { name: 'database' }, { name: 'collection' }, ); - const showOpenDialog = vi.fn(async () => { - vi.mocked(ClustersClient.resolveBoundClient).mockRejectedValueOnce( - new ConnectionUnavailableError('identityChanged'), - ); - return [vscode.Uri.file('/fixture/documents.json')]; - }); - const context: IActionContext = { +} + +function createContext(showOpenDialog: () => Promise = async () => []): IActionContext { + return { ui: { showOpenDialog }, telemetry: { properties: {}, measurements: {} }, errorHandling: { issueProperties: {} }, valuesToMask: [], } as unknown as IActionContext; - vi.mocked(vscode.window.withProgress).mockImplementationOnce((_options, task) => +} + +beforeEach(() => { + 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 binding: ConnectionBinding = { clusterId: 'cluster', fingerprint: 'original', generation: 1 }; + const insertDocuments = vi.fn(); + const replacement = { insertDocuments, getConnectionString: () => 'mongodb://example.test' }; + vi.mocked(ClustersClient.getClient).mockResolvedValue(replacement as unknown as ClustersClient); + + const source = createSource(); + const showOpenDialog = vi.fn(async () => { + vi.mocked(ClustersClient.resolveBoundClient).mockRejectedValueOnce( + new ConnectionUnavailableError('identityChanged'), + ); + return [vscode.Uri.file('/fixture/documents.json')]; + }); + const context = createContext(showOpenDialog); await expect(importDocuments(context, source, undefined, { binding })).rejects.toMatchObject({ reason: 'credentialsChanged', @@ -71,3 +89,82 @@ it('does not import using a different identity selected while the file picker wa expect(ClustersClient.getClient).not.toHaveBeenCalled(); 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([]); + + 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([]); + + rejectClient(new Error('client resolution failed')); + await expect(exportOperation).rejects.toThrow('client resolution failed'); + expect(TaskService.getConflictingTasks({ clusterId: 'cluster' })).toEqual([]); +}); diff --git a/src/commands/importDocuments/importDocuments.ts b/src/commands/importDocuments/importDocuments.ts index b92f23b90..30ddde0d1 100644 --- a/src/commands/importDocuments/importDocuments.ts +++ b/src/commands/importDocuments/importDocuments.ts @@ -16,6 +16,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'; @@ -156,74 +157,87 @@ 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); + } + + if (isRuResource) { + // For Azure MongoDB RU, we use a buffer with maxDocumentCount = 1 + buffer = createMongoDbBuffer({ + maxDocumentCount: 1, + }); + } else { + buffer = createMongoDbBuffer(); + } } - } - let wasCancelled = false; + let wasCancelled = false; - 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; - } + 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; + } - progress.report({ - increment: incrementDocuments, - message: l10n.t('Importing document {num} of {countDocuments}', { - num: i + 1, - countDocuments, - }), - }); + progress.report({ + increment: incrementDocuments, + message: l10n.t('Importing document {num} of {countDocuments}', { + num: i + 1, + countDocuments, + }), + }); - const result = await insertDocument(selectedItem, documents[i], buffer, boundClient); + const result = await insertDocument(selectedItem, documents[i], buffer, boundClient); - // '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' 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; + } - // Do insertion for the last batch for bulk insertion - if (!wasCancelled && buffer && buffer.getStats().documentCount > 0) { - const lastBatchFlushResult = await insertDocument(selectedItem, undefined, buffer, boundClient); + // Do insertion for the last batch for bulk insertion + if (!wasCancelled && buffer && buffer.getStats().documentCount > 0) { + const lastBatchFlushResult = await insertDocument(selectedItem, undefined, buffer, boundClient); - count += lastBatchFlushResult.count; - hasErrors = hasErrors || lastBatchFlushResult.errorOccurred; - } + count += lastBatchFlushResult.count; + hasErrors = hasErrors || lastBatchFlushResult.errorOccurred; + } - // let's make sure we reach 100% progress, useful in case of errors etc. - progress.report({ increment: 100, message: l10n.t('Finished importing') }); + // 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 }; + return { hasErrors, count, wasCancelled }; + } finally { + lease.dispose(); + } }, ); 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; } From bc791b68c80e08b4fa094991a5ee55df2e1dbf54 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 15:32:28 +0000 Subject: [PATCH 03/23] feat: disconnect clusters with an explicit teardown choice (WI-7) Check task and dirty-view conflicts, fence work before closing resources, and offer Connect without changing tree identity. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 5 + package.json | 30 +++ package.nls.json | 1 + src/commands/disconnect/disconnect.ts | 37 +++ .../openInteractiveShell.ts | 4 +- .../playground/executePlaygroundCode.ts | 24 ++ src/documentdb/ClustersClient.test.ts | 17 ++ src/documentdb/ClustersClient.ts | 19 +- src/documentdb/ClustersExtension.ts | 6 + src/documentdb/connectionTeardown.test.ts | 224 ++++++++++++++++++ src/documentdb/connectionTeardown.ts | 209 ++++++++++++++++ src/documentdb/shell/DocumentDBShellPty.ts | 25 +- .../shell/ShellSessionManager.test.ts | 13 + src/documentdb/shell/ShellSessionManager.ts | 12 + .../shell/ShellTerminalLinkProvider.ts | 21 +- .../discovery-tree/AtlasClusterItem.ts | 2 +- src/settingsKeys.ts | 1 + .../connections-view/DocumentDBClusterItem.ts | 6 +- .../LocalQuickStart/LocalQuickStartItem.ts | 14 +- src/tree/documentdb/ClusterItemBase.test.ts | 50 ++++ src/tree/documentdb/ClusterItemBase.ts | 45 +++- .../documentView/documentView.test.tsx | 13 + .../documentdb/documentView/documentView.tsx | 20 +- .../documentsViewController.test.ts | 16 +- .../documentView/documentsViewController.ts | 5 + .../documentView/documentsViewRouter.test.ts | 12 +- .../documentView/documentsViewRouter.ts | 6 +- 27 files changed, 809 insertions(+), 28 deletions(-) create mode 100644 src/commands/disconnect/disconnect.ts create mode 100644 src/documentdb/connectionTeardown.test.ts create mode 100644 src/documentdb/connectionTeardown.ts 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 370b49a89..dd067cf92 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 @@ -1752,6 +1752,11 @@ behave as today. 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. - **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. diff --git a/package.json b/package.json index 2a21ff0bb..6b5ab0931 100644 --- a/package.json +++ b/package.json @@ -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 =~ /\\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/disconnect/disconnect.ts b/src/commands/disconnect/disconnect.ts new file mode 100644 index 000000000..01332ab8e --- /dev/null +++ b/src/commands/disconnect/disconnect.ts @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * 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'; + +export async function disconnect(context: IActionContext, node?: TreeElement): Promise { + context.telemetry.suppressAll = true; // connection.disconnect owns this operation's telemetry. + if (!(node instanceof ClusterItemBase)) { + throw new UserCancelledError(); + } + + const { clusterId } = node.cluster; + if (!ClustersClient.exists(clusterId) || ClustersClient.getLatchReason(clusterId)) { + throw new UserCancelledError(); + } + + await teardownConnection(clusterId, 'userDisconnected', () => ext.state.notifyChildrenChanged(node.id)); +} + +export function connectDisconnected(_context: IActionContext, node?: TreeElement): void { + if ( + !(node instanceof ClusterItemBase) || + ClustersClient.getLatchReason(node.cluster.clusterId) !== 'userDisconnected' + ) { + return; + } + + ClustersClient.unlatch(node.cluster.clusterId); + ext.state.notifyChildrenChanged(node.id); +} diff --git a/src/commands/openInteractiveShell/openInteractiveShell.ts b/src/commands/openInteractiveShell/openInteractiveShell.ts index 39dd4fcda..87087168f 100644 --- a/src/commands/openInteractiveShell/openInteractiveShell.ts +++ b/src/commands/openInteractiveShell/openInteractiveShell.ts @@ -84,7 +84,7 @@ 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 +133,7 @@ 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.ts b/src/commands/playground/executePlaygroundCode.ts index 807b7dd9f..98119a147 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,6 +247,9 @@ 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; diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index e02da895e..bff9246bb 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -1052,6 +1052,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..7fef0b3c4 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -296,6 +296,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); @@ -1178,13 +1182,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/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts new file mode 100644 index 000000000..c0a54e0f7 --- /dev/null +++ b/src/documentdb/connectionTeardown.test.ts @@ -0,0 +1,224 @@ +/*--------------------------------------------------------------------------------------------- + * 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 } from './connectionTeardown'; + +const mocks = vi.hoisted(() => ({ + getSetting: vi.fn(), + getConflictingTasks: vi.fn(), + getLatchReason: vi.fn(), + latch: 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: {} }); + } 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('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..e78fb4f2c --- /dev/null +++ b/src/documentdb/connectionTeardown.ts @@ -0,0 +1,209 @@ +/*--------------------------------------------------------------------------------------------- + * 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 } 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): 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'; +} + +/** The single-cluster confirm/commit path, with one event covering both phases. */ +export async function teardownConnection( + clusterId: string, + reason: TeardownReason, + refreshTree: () => void, +): Promise { + 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'; + context.telemetry.measurements.surfaceCount = getConnectionSurfaces(clusterId).length; + context.telemetry.measurements.shellCount = getRegisteredShellTerminals().filter( + (shell) => shell.info.clusterId === clusterId, + ).length; + context.telemetry.measurements.playgroundCount = getPlaygroundEvaluators().has(clusterId) ? 1 : 0; + + 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.ts b/src/documentdb/shell/DocumentDBShellPty.ts index a11ab46d3..0e6bc9e4c 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,16 @@ 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.writeLine(this._outputFormatter.formatSystemMessage(l10n.t('Disconnected'))); + this._sessionManager.killWorker(); + this._inputHandler.setEnabled(true); + } + /** * Associate this PTY with its terminal instance. * Called by the command handler after `createTerminal()`. @@ -484,6 +495,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 +514,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 +620,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 +684,10 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // ─── Private: Line handling ────────────────────────────────────────────── private async handleLineInput(line: string): Promise { + if (ClustersClient.getLatchReason(this._connectionInfo.clusterId)) { + this.writeLine(this._outputFormatter.formatSystemMessage(l10n.t('Disconnected'))); + return; + } const trimmed = line.trim(); // Empty line — just show a new prompt @@ -714,6 +736,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { } private async evaluateInput(input: string): Promise { + const disconnectRevision = this._disconnectRevision; this._commandCount++; const commandIndex = this._commandCount; const commandCategory = classifyCommand(input); @@ -754,7 +777,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // 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; } diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index 7e18eb3c4..e252ca7de 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,18 @@ 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..f7fef7bb0 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -19,6 +19,8 @@ import { } from '../auth/documentdbTokenResource'; import { evaluateEntraDestinationFromSettings } from '../auth/entraDestinationSettings'; import { clearEntraTokenFailure, recordEntraTokenFailure } from '../auth/entraErrors/entraTokenFailures'; +import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; import { WorkerSessionManager, @@ -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.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/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..0c749d680 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -11,6 +11,7 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { connectDisconnected } from '../../commands/disconnect/disconnect'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; @@ -83,12 +84,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 +103,7 @@ vi.mock('../../extensionVariables', () => ({ appendLine: vi.fn(), debug: vi.fn(), }, + state: { notifyChildrenChanged: (...args: unknown[]) => notifyChildrenChanged(...args) }, }, })); @@ -451,6 +457,50 @@ 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: 'Connect', 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.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..1fc95de86 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 ({ explainOperationFailure: vi.fn(), displayErrorMessage: vi.fn(), reportEvent: vi.fn(), + reportDirty: vi.fn<(dirty: boolean) => Promise>().mockResolvedValue(undefined), })); vi.mock('@microsoft/vscode-ext-webview/react', () => ({ @@ -31,6 +32,7 @@ vi.mock('../../_integration/useTrpcClient', () => ({ getDocumentById: { query: mocks.getDocumentById }, saveDocument: { mutate: mocks.saveDocument }, recoverUnavailable: { mutate: mocks.recoverUnavailable }, + reportDirty: { mutate: mocks.reportDirty }, }, }, common: { @@ -157,6 +159,17 @@ async function save(): Promise { await act(async () => button?.click()); } +it('reports only dirty transitions, not editor contents', async (): Promise => { + mocks.getDocumentById.mockResolvedValueOnce('{"field":"saved"}'); + mocks.saveDocument.mockResolvedValueOnce({ documentId: 'id', documentStringified: '{"field":"edited"}' }); + await render(config('edit')); + expect(mocks.reportDirty).not.toHaveBeenCalled(); + await edit('{"field":"draft"}'); + await edit('{"field":"edited"}'); + await save(); + expect(mocks.reportDirty.mock.calls).toEqual([[true], [false]]); +}); + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; beforeEach((): void => { diff --git a/src/webviews/documentdb/documentView/documentView.tsx b/src/webviews/documentdb/documentView/documentView.tsx index 8f1171718..6d762fb3d 100644 --- a/src/webviews/documentdb/documentView/documentView.tsx +++ b/src/webviews/documentdb/documentView/documentView.tsx @@ -73,6 +73,7 @@ export const DocumentView = (): JSX.Element => { const [editorContent] = useState(initialContent); const [isLoading, setIsLoading] = useState(configuration.mode !== 'add'); const [isDirty, setIsDirty] = useState(configuration.mode === 'add'); + const dirtyRef = useRef(configuration.mode === 'add'); const [documentLoaded, setDocumentLoaded] = useState(configuration.mode === 'add'); const [unavailable, setUnavailable] = useState(); const [recovering, setRecovering] = useState(false); @@ -92,6 +93,17 @@ export const DocumentView = (): JSX.Element => { const unavailableRef = useRef(undefined); const disposedRef = useRef(false); const pendingDocumentIdRef = useRef(configuration.documentId || undefined); + const updateDirty = (dirty: boolean): void => { + if (dirtyRef.current === dirty) { + return; + } + dirtyRef.current = dirty; + setIsDirty(dirty); + // Only report transitions, without editor contents or connection material. + void trpcClient.mongoClusters.documentView.reportDirty.mutate(dirty).catch(() => { + // The panel may have closed before the host received the report. + }); + }; // Falls back to pending/initial content if called before Monaco has mounted, // so callers (e.g. Save) never operate on an empty string. const getCurrentContent = () => editorRef.current?.getValue() ?? pendingContentRef.current ?? editorContent; @@ -164,7 +176,7 @@ export const DocumentView = (): JSX.Element => { } if (editorRevision === editorRevisionRef.current) { setContent(response); - setIsDirty(false); + updateDirty(false); } setDocumentLoaded(true); // A document deleted since it was listed reads back as `null`. @@ -306,7 +318,7 @@ export const DocumentView = (): JSX.Element => { documentLength = response.length ?? 0; if (editorRevision === editorRevisionRef.current) { setContent(response); - setIsDirty(false); + updateDirty(false); } setDocumentLoaded(true); }) @@ -381,7 +393,7 @@ export const DocumentView = (): JSX.Element => { pendingDocumentIdRef.current = response.documentId; setContent(response.documentStringified); setIsLoading(false); - setIsDirty(false); + updateDirty(false); }) .catch(async (error) => { if (!isCurrentOperation(revision)) { @@ -508,7 +520,7 @@ export const DocumentView = (): JSX.Element => { onChange={() => { if (!settingContentRef.current) { editorRevisionRef.current += 1; - setIsDirty(true); + updateDirty(true); } }} /> diff --git a/src/webviews/documentdb/documentView/documentsViewController.test.ts b/src/webviews/documentdb/documentView/documentsViewController.test.ts index 1527926bb..eeae65f45 100644 --- a/src/webviews/documentdb/documentView/documentsViewController.test.ts +++ b/src/webviews/documentdb/documentView/documentsViewController.test.ts @@ -39,7 +39,7 @@ const originalBinding = { clusterId, fingerprint: 'identity-a', generation: 1 }; const newerBinding = { clusterId, fingerprint: 'identity-b', generation: 2 }; const opened: { readonly dispose: () => void; readonly context: RouterContext }[] = []; -function openPanel(binding = originalBinding): RouterContext { +function openPanel(binding = originalBinding, mode: 'add' | 'edit' = 'edit'): RouterContext { const config: DocumentsViewWebviewConfigurationType = { id: 'document', clusterId, @@ -47,7 +47,7 @@ function openPanel(binding = originalBinding): RouterContext { databaseName: 'database', collectionName: 'collection', documentId: '{"$oid":"000000000000000000000001"}', - mode: 'edit', + mode, }; openDocumentWebview(config, binding); return opened.at(-1)?.context as RouterContext; @@ -90,6 +90,18 @@ beforeEach((): void => { }); }); +it('treats a new document as dirty before reports, and tracks edits per panel', (): void => { + const first = openPanel(originalBinding, 'add'); + const second = openPanel(); + const [draft, existing] = getConnectionSurfaces(clusterId); + expect(draft.isDirty?.()).toBe(true); + expect(existing.isDirty?.()).toBe(false); + first.setDirty(false); + second.setDirty(true); + expect(draft.isDirty?.()).toBe(false); + expect(existing.isDirty?.()).toBe(true); +}); + it('registers the panel, sends typed disable payloads and unregisters on dispose', (): void => { const context = openPanel(); const [surface] = getConnectionSurfaces(clusterId); diff --git a/src/webviews/documentdb/documentView/documentsViewController.ts b/src/webviews/documentdb/documentView/documentsViewController.ts index 2df3256cc..a21f6f96f 100644 --- a/src/webviews/documentdb/documentView/documentsViewController.ts +++ b/src/webviews/documentdb/documentView/documentsViewController.ts @@ -49,6 +49,7 @@ export function openDocumentWebview( // exists after openAppWebview returns. The setter is only invoked at runtime // (in response to a tRPC call), well after the handle is assigned below. const handle: { controller?: AppWebviewController } = {}; + let dirty = initialData.mode === 'add'; const postUnavailable = (reason: ConnectionUnavailableReason): void => { const message: ConnectionUnavailableMessage = { @@ -69,6 +70,9 @@ export function openDocumentWebview( collectionName: initialData.collectionName, documentId: initialData.documentId, binding, + setDirty: (value: boolean): void => { + dirty = value; + }, describeUnavailable: describeUnavailableConnection, recoverUnavailable: (request) => recoverBoundView(binding, 'documentView', () => controller.dispose(), request), viewPanelTitleSetter: (title: string) => { @@ -112,6 +116,7 @@ export function openDocumentWebview( kind: 'documentView', disable: postUnavailable, dispose: () => controller.dispose(), + isDirty: () => dirty, }); controller.onDisposed((): void => { registration.dispose(); diff --git a/src/webviews/documentdb/documentView/documentsViewRouter.test.ts b/src/webviews/documentdb/documentView/documentsViewRouter.test.ts index 70e410996..64db2c42b 100644 --- a/src/webviews/documentdb/documentView/documentsViewRouter.test.ts +++ b/src/webviews/documentdb/documentView/documentsViewRouter.test.ts @@ -28,7 +28,7 @@ vi.mock('../../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsIn vi.mock('../../_integration/trpc', async () => { const { initWebviewTrpc } = await import('@microsoft/vscode-ext-webview'); const { createCallerFactory, publicProcedure, router } = initWebviewTrpc(); - return { createCallerFactory, publicProcedureWithTelemetry: publicProcedure, router }; + return { createCallerFactory, publicProcedure, publicProcedureWithTelemetry: publicProcedure, router }; }); const binding = { clusterId: 'cluster', fingerprint: 'host-only-fingerprint', generation: 1 }; @@ -36,6 +36,7 @@ const newerBinding = { ...binding, generation: 2 }; const upsertDocument = vi.fn(); const pointRead = vi.fn(); const viewPanelTitleSetter = vi.fn(); +const setDirty = vi.fn(); const describeUnavailable = vi.fn((reason: ConnectionUnavailableError['reason']) => ({ unavailable: { reason, title: 'Connection unavailable', detail: 'Close this view.', action: 'close' as const }, })); @@ -57,6 +58,7 @@ function createCaller(signal?: AbortSignal): ReturnType collectionName: 'collection', documentId: 'id', binding, + setDirty, describeUnavailable, recoverUnavailable, signal, @@ -88,6 +90,14 @@ describe('Document View bound operations', () => { expect(info).not.toContain(binding.fingerprint); }); + it('reports dirty state to its owning panel without resolving a connection', async () => { + const view = createCaller(); + await view.reportDirty(true); + await view.reportDirty(false); + expect(setDirty.mock.calls).toEqual([[true], [false]]); + expect(mocks.resolveBoundClient).not.toHaveBeenCalled(); + }); + it('uses the captured identity and preserves the successful save and read shapes', async () => { pointRead.mockResolvedValue(document); upsertDocument.mockResolvedValue({ documentId: id, document }); diff --git a/src/webviews/documentdb/documentView/documentsViewRouter.ts b/src/webviews/documentdb/documentView/documentsViewRouter.ts index 8f743b7c5..1bf867612 100644 --- a/src/webviews/documentdb/documentView/documentsViewRouter.ts +++ b/src/webviews/documentdb/documentView/documentsViewRouter.ts @@ -18,12 +18,13 @@ import { type ConnectionRecoveryResponse, type ConnectionUnavailableResponse, } from '../../_integration/connectionUnavailable'; -import { publicProcedureWithTelemetry, router, type WithTelemetry } from '../../_integration/trpc'; +import { publicProcedure, publicProcedureWithTelemetry, router, type WithTelemetry } from '../../_integration/trpc'; import { guardBoundViewOperation, runBoundViewOperation } from '../boundViewOperations'; export type RouterContext = BaseRouterContext & { clusterId: string; readonly binding: ConnectionBinding; + readonly setDirty: (dirty: boolean) => void; readonly describeUnavailable: (reason: ConnectionUnavailableError['reason']) => ConnectionUnavailableResponse; readonly recoverUnavailable: ( request: ConnectionRecoveryRequest, @@ -61,6 +62,9 @@ async function runDocumentViewOperation( } export const documentsViewRouter = router({ + reportDirty: publicProcedure.input(z.boolean()).mutation(({ input, ctx }) => { + (ctx as RouterContext).setDirty(input); + }), getInfo: publicProcedureWithTelemetry.query(({ ctx }) => { const info = Object.fromEntries( Object.entries(ctx as WithTelemetry).filter(([key]) => key !== 'binding'), From 4bbeb436680e7d5c4ec33322a7abcfdd197ce5d6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 15:37:07 +0000 Subject: [PATCH 04/23] feat: apply shared teardown to connection and folder removal (WI-7) Fence the confirmed targets before deleting, and let a surviving connection reconnect if its storage deletion fails. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 4 + .../deleteFolder/ExecuteStep.ts | 36 +++--- .../deleteFolder/deleteFolder.test.ts | 7 ++ .../removeConnection/removeConnection.ts | 61 +++++----- src/documentdb/connectionTeardown.test.ts | 45 +++++++- src/documentdb/connectionTeardown.ts | 107 ++++++++++++++++-- 6 files changed, 210 insertions(+), 50 deletions(-) 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 dd067cf92..f0ed08b65 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 @@ -1757,6 +1757,10 @@ behave as today. 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. - **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. diff --git a/src/commands/connections-view/deleteFolder/ExecuteStep.ts b/src/commands/connections-view/deleteFolder/ExecuteStep.ts index 3e40393a8..aa15b3f7f 100644 --- a/src/commands/connections-view/deleteFolder/ExecuteStep.ts +++ b/src/commands/connections-view/deleteFolder/ExecuteStep.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { AzureWizardExecuteStep } from '@microsoft/vscode-azext-utils'; +import { withConnectionRemoval } from '../../../documentdb/connectionTeardown'; import { ext } from '../../../extensionVariables'; import { ConnectionStorageService, ItemType } from '../../../services/connectionStorageService'; import { @@ -11,6 +12,7 @@ import { withConnectionsViewProgress, } from '../../../tree/connections-view/connectionsViewHelpers'; import { type DeleteFolderWizardContext } from './DeleteFolderWizardContext'; +import { enumerateConnectionsInFolder } from '../verificationUtils'; /** * Step to execute the folder deletion operation. @@ -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,23 @@ 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..ae2894b07 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 { 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/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/documentdb/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts index c0a54e0f7..571636dff 100644 --- a/src/documentdb/connectionTeardown.test.ts +++ b/src/documentdb/connectionTeardown.test.ts @@ -8,13 +8,15 @@ 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 } from './connectionTeardown'; +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(), @@ -79,6 +81,47 @@ describe('connection teardown', () => { vi.restoreAllMocks(); }); + it('does not close views or delete stored connections when the combined tab choice is cancelled', async () => { + const draft = register('documentView', true); + const deleteStored = vi.fn<() => Promise>(); + + await expect( + withConnectionRemoval([clusterId, otherId], async (remove) => remove(clusterId, deleteStored)), + ).rejects.toBeInstanceOf(UserCancelledError); + + expect(showWarning).toHaveBeenCalledOnce(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(deleteStored).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 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(latches.has(otherId)).toBe(false); + }); + 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', diff --git a/src/documentdb/connectionTeardown.ts b/src/documentdb/connectionTeardown.ts index e78fb4f2c..dbe7cc618 100644 --- a/src/documentdb/connectionTeardown.ts +++ b/src/documentdb/connectionTeardown.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { callWithTelemetryAndErrorHandling, UserCancelledError } from '@microsoft/vscode-azext-utils'; +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'; @@ -160,11 +160,87 @@ export async function commitTeardown( return 'committed'; } -/** The single-cluster confirm/commit path, with one event covering both phases. */ -export async function teardownConnection( - clusterId: string, +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 === 'credentialsChanged' || 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'); + } else if (target.previous) { + ClustersClient.latch(id, target.previous); + } else { + ClustersClient.unlatch(id); + } + } + } +} + +async function reportTeardown( + ids: readonly string[], reason: TeardownReason, - refreshTree: () => void, + operation: (context: IActionContext) => Promise, ): Promise { await callWithTelemetryAndErrorHandling('connection.disconnect', async (context) => { context.errorHandling.suppressDisplay = true; @@ -177,12 +253,27 @@ export async function teardownConnection( }[reason]; context.telemetry.properties.surfacesChoice = 'none'; context.telemetry.properties.blockedByTask = 'false'; - context.telemetry.measurements.surfaceCount = getConnectionSurfaces(clusterId).length; + 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) => shell.info.clusterId === clusterId, + (shell) => targets.has(shell.info.clusterId), ).length; - context.telemetry.measurements.playgroundCount = getPlaygroundEvaluators().has(clusterId) ? 1 : 0; + const playgrounds = getPlaygroundEvaluators(); + context.telemetry.measurements.playgroundCount = [...targets].filter((id) => playgrounds.has(id)).length; + await operation(context); + }); +} +/** 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'; From 6261dc157b0e42374697514a5a8b8985f2d123eb Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 15:45:56 +0000 Subject: [PATCH 05/23] feat: lock existing views after saved connection edits (WI-7) Retire only older view generations after storage changes, including password-only and partial writes. Keep the edit fence retryable until a change is confirmed. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 5 + src/commands/saveConnectionEdit.ts | 141 ++++++++++++++++++ .../updateConnectionString.test.ts | 21 ++- .../updateConnectionString.ts | 38 +++-- .../updateCredentials.test.ts | 79 ++++++++-- .../updateCredentials/updateCredentials.ts | 98 +++++------- src/documentdb/ClusterSession.ts | 6 +- src/documentdb/ClustersClient.test.ts | 17 +++ src/documentdb/ClustersClient.ts | 16 +- src/documentdb/ConnectionUnavailableError.ts | 1 + src/documentdb/connectionBindingRetirement.ts | 17 +++ src/documentdb/connectionTeardown.ts | 4 +- .../_integration/connectionUnavailable.ts | 1 + .../describeUnavailableConnection.ts | 9 ++ .../documentdb/boundViewOperations.ts | 7 +- 15 files changed, 347 insertions(+), 113 deletions(-) create mode 100644 src/commands/saveConnectionEdit.ts create mode 100644 src/documentdb/connectionBindingRetirement.ts 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 f0ed08b65..83fa1958b 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 @@ -1761,6 +1761,11 @@ behave as today. 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. - **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. diff --git a/src/commands/saveConnectionEdit.ts b/src/commands/saveConnectionEdit.ts new file mode 100644 index 000000000..0e5b96c06 --- /dev/null +++ b/src/commands/saveConnectionEdit.ts @@ -0,0 +1,141 @@ +/*--------------------------------------------------------------------------------------------- + * 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 vscode from 'vscode'; +import { isDeepStrictEqual } from 'node:util'; +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; + 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; + } + let saved = 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()) { + if (previous && (!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..2aeb9371a 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,7 @@ 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 +278,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 +308,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..00c82916a 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,25 @@ 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..ed355eee3 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -23,6 +23,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(); @@ -55,10 +56,15 @@ vi.mock('../../documentdb/ClustersClient', () => ({ getLastFailedStartupCorrelationId: (): undefined => undefined, getEpoch: (): number => mockGetEpoch(), getLatchReason: (): undefined => undefined, + 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,7 +72,10 @@ 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(() => false) }, + outputChannel: { error: vi.fn(), warn: vi.fn() }, + }, })); beforeEach(() => { @@ -107,7 +116,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 +228,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 +239,6 @@ describe('updateCredentials post-wizard updates', () => { mockSave.mockImplementationOnce( async (_zone: storageModule.StorageZone, item: storageModule.ConnectionItem): Promise => { storedConnection = structuredClone(item); - mockGetEpoch.mockReturnValue(1); }, ); @@ -239,10 +247,30 @@ 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('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 +294,14 @@ 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,14 +317,14 @@ 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({ + mockGet.mockResolvedValueOnce(originalConnection).mockResolvedValueOnce(originalConnection).mockResolvedValue({ ...originalConnection, secrets: { ...originalConnection.secrets, @@ -308,7 +339,7 @@ describe('updateCredentials post-wizard updates', () => { }); it('deletes cached credentials when the stored authentication method is missing', async () => { - mockGet.mockResolvedValue({ + mockGet.mockResolvedValueOnce(originalConnection).mockResolvedValueOnce(originalConnection).mockResolvedValue({ ...originalConnection, properties: { ...originalConnection.properties, selectedAuthMethod: undefined }, }); @@ -319,18 +350,34 @@ 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..fa01a3649 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,40 @@ 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 (changed && wizardContext.credentialsSaved && node.id && wizardContext.isErrorState) { if (wizardContext.reconnectAfterError) { ext.connectionsBranchDataProvider.resetNodeErrorState(node.id); context.telemetry.properties.reconnected = 'true'; @@ -218,4 +189,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..f2a07cc47 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -15,6 +15,7 @@ import { toSlickGridTree, type TreeData } from '../utils/slickgrid/mongo/toSlick import { type QueryInsightsStage2Response } from '../webviews/documentdb/collectionView/types/queryInsights'; import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; import { ConnectionUnavailableError } from './ConnectionUnavailableError'; +import { isRetiredConnectionBinding } from './connectionBindingRetirement'; import { runWithClient } from './runWithClient'; import { SchemaStore } from './SchemaStore'; import { fixupDocumentDbExplain } from './utils/fixupDocumentDbExplain'; @@ -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 bff9246bb..840a34db6 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -322,6 +322,23 @@ 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)); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 7fef0b3c4..53bd0a4e7 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -53,6 +53,7 @@ import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { readJwtTimes } from './auth/tokenExpiry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; +import { isRetiredConnectionBinding, retireConnectionBindings } from './connectionBindingRetirement'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; import { CredentialCache, type CachedClusterCredentials } from './CredentialCache'; @@ -843,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, @@ -856,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. */ 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.ts b/src/documentdb/connectionTeardown.ts index dbe7cc618..f8b20b53c 100644 --- a/src/documentdb/connectionTeardown.ts +++ b/src/documentdb/connectionTeardown.ts @@ -98,7 +98,7 @@ export async function confirmTeardown( } /** Check the whole batch and fence it synchronously, before any resource is changed. */ -export function latchForTeardown(target: string | readonly string[], reason: TeardownReason): boolean { +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; @@ -184,7 +184,7 @@ async function removeConnections( const targets = new Map( clusterIds(ids).map((id) => [id, { previous: ClustersClient.getLatchReason(id), epoch: 0, started: false }]), ); - if ([...targets.values()].some(({ previous }) => previous === 'credentialsChanged' || previous === 'connectionRemoved')) { + 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')) { diff --git a/src/webviews/_integration/connectionUnavailable.ts b/src/webviews/_integration/connectionUnavailable.ts index bae57d4f9..c2044eccb 100644 --- a/src/webviews/_integration/connectionUnavailable.ts +++ b/src/webviews/_integration/connectionUnavailable.ts @@ -12,6 +12,7 @@ export const connectionUnavailableReasons = [ 'signInRequired', 'credentialsRejected', 'credentialsMissing', + 'credentialsUpdating', 'credentialsChanged', 'identityChanged', 'userDisconnected', diff --git a/src/webviews/_integration/describeUnavailableConnection.ts b/src/webviews/_integration/describeUnavailableConnection.ts index 2ce107c28..c1705ed28 100644 --- a/src/webviews/_integration/describeUnavailableConnection.ts +++ b/src/webviews/_integration/describeUnavailableConnection.ts @@ -37,6 +37,15 @@ export function describeUnavailableConnection(reason: ConnectionUnavailableReaso action: 'retry', }, }; + case 'credentialsUpdating': + return { + unavailable: { + reason, + title: l10n.t('Connection update in progress'), + detail: l10n.t('Wait for the update to finish, then click Retry.'), + action: 'retry', + }, + }; case 'identityChanged': case 'credentialsChanged': return { diff --git a/src/webviews/documentdb/boundViewOperations.ts b/src/webviews/documentdb/boundViewOperations.ts index 28fa2526a..ff5fafc58 100644 --- a/src/webviews/documentdb/boundViewOperations.ts +++ b/src/webviews/documentdb/boundViewOperations.ts @@ -6,6 +6,7 @@ import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { isRetiredConnectionBinding } from '../../documentdb/connectionBindingRetirement'; import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { runWithClient } from '../../documentdb/runWithClient'; import { @@ -26,7 +27,9 @@ export async function recoverBoundView( return { recovered: { text: '' } }; } - const reason = ClustersClient.getLatchReason(binding.clusterId); + const reason = isRetiredConnectionBinding(binding) + ? 'credentialsChanged' + : ClustersClient.getLatchReason(binding.clusterId); if (reason) { return describeUnavailableConnection(reason); } @@ -58,7 +61,7 @@ export function guardBoundViewOperation(binding: ConnectionBinding, signal?: Abo if (signal?.aborted) { throw new UserCancelledError('staleBoundViewOperation'); } - const reason = ClustersClient.getLatchReason(clusterId); + const reason = isRetiredConnectionBinding(binding) ? 'credentialsChanged' : ClustersClient.getLatchReason(clusterId); if (reason) { throw new ConnectionUnavailableError(reason); } From 9bfbe052529ae36237ab06ba2ac2eef7d23e3fce Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 15:50:45 +0000 Subject: [PATCH 06/23] fix: stop Dashboard health polls while the connection is unavailable (WI-8) Treat closed clients and terminal auth as unavailable, keep partial samples for unsupported commands, and resume one poll loop only after Retry. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- build/verification/browser/scenarios.ts | 6 +++ .../iterations/01-dev-plan.md | 12 +++-- .../documentdb/boundViewOperations.ts | 2 + .../clusterDashboard/ClusterDashboard.tsx | 13 ++++-- .../clusterDashboardRouter.test.ts | 44 +++++++++++++++++++ 5 files changed, 71 insertions(+), 6 deletions(-) diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index 794d5463d..d872f8513 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -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,7 @@ const clusterDashboardScenarios = { }, }, { action: 'waitFor', name: 'disconnected overlay', selector: '.disconnectedOverlay' }, + { action: 'releaseReply', name: 'deliver the old health poll', path: 'clusterDashboard.measureRtt' }, ], }, { 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 83fa1958b..9b300447f 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 @@ -1785,9 +1785,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 @@ -1804,6 +1804,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/src/webviews/documentdb/boundViewOperations.ts b/src/webviews/documentdb/boundViewOperations.ts index ff5fafc58..6465d5bfc 100644 --- a/src/webviews/documentdb/boundViewOperations.ts +++ b/src/webviews/documentdb/boundViewOperations.ts @@ -97,6 +97,8 @@ export function throwIfBoundViewUnavailable(binding: ConnectionBinding, error: u case 'credentialsMissing': case 'identityChanged': throw new ConnectionUnavailableError(kind); + case 'clientClosed': + throw new ConnectionUnavailableError('unreachable'); } } diff --git a/src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx b/src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx index 4f7fa9abd..970ce53b1 100644 --- a/src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx +++ b/src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx @@ -116,6 +116,7 @@ export const ClusterDashboard = (): JSX.Element => { createInventoryViewState(configuration.selectedDatabaseName), ); const [unavailable, setUnavailable] = useState(); + const [recoveryDialogDismissed, setRecoveryDialogDismissed] = useState(false); const [recovering, setRecovering] = useState(false); const [recoveryAnnouncement, setRecoveryAnnouncement] = useState(); const unavailableRef = useRef(undefined); @@ -126,6 +127,7 @@ export const ClusterDashboard = (): JSX.Element => { operationRevisionRef.current += 1; unavailableRef.current = failure; setUnavailable(failure); + setRecoveryDialogDismissed(false); setRecovering(false); setRecoveryAnnouncement(undefined); setIsRefreshingStorage(false); @@ -142,7 +144,7 @@ export const ClusterDashboard = (): JSX.Element => { const startOperation = useCallback((revealUnavailable = false): number | undefined => { if (unavailableRef.current !== undefined) { if (revealUnavailable) { - setUnavailable(unavailableRef.current); + setRecoveryDialogDismissed(false); } return undefined; } @@ -348,7 +350,11 @@ export const ClusterDashboard = (): JSX.Element => { // Health polling loop. Failures are absorbed so a transient error does not flip the // header to Disconnected on the first missed sample. + const pollingPaused = unavailable !== undefined; useEffect(() => { + if (pollingPaused) { + return; + } const tick = (): void => { const revision = startOperation(); if (revision === undefined || sampleInFlightRef.current || !isVisibleRef.current) { @@ -386,6 +392,7 @@ export const ClusterDashboard = (): JSX.Element => { }, [ configuration.refreshIntervalMs, isOperationCurrent, + pollingPaused, showUnavailable, startOperation, trpcClient, @@ -783,8 +790,8 @@ export const ClusterDashboard = (): JSX.Element => { return ( setUnavailable(undefined)} + unavailable={recoveryDialogDismissed ? undefined : unavailable} + onDismiss={() => setRecoveryDialogDismissed(true)} onAction={handleUnavailableAction} recovering={recovering} > diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts index d61026cf1..8241deaeb 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts @@ -176,6 +176,50 @@ describe('clusterDashboardRouter create actions', () => { }, }); }); + + it.each([ + ['signInRequired', 'signInRequired'], + ['credentialsRejected', 'credentialsRejected'], + ['clientClosed', 'unreachable'], + ] as const)('maps a %s ping failure to an unavailable poll result', async (kind, reason) => { + const failure = new Error('test ping failure'); + const command = vi.fn(async (input: Document): Promise => { + if (input.ping === 1) { + throw failure; + } + return { uptime: 42 }; + }); + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValueOnce({ + binding, + getMongoClient: () => ({ db: () => ({ admin: () => ({ command }) }) }), + } as unknown as ClustersClient); + vi.mocked(ClustersClient.reportFailure).mockReturnValueOnce(kind); + + await expect(createCallerFactory(clusterDashboardRouter)(createContext()).measureRtt()).resolves.toMatchObject({ + unavailable: { reason }, + }); + expect(ClustersClient.reportFailure).toHaveBeenCalledWith(binding, failure); + }); + + it('returns a partial sample for an unsupported serverStatus command', async () => { + const command = vi.fn(async (input: Document): Promise => { + if (input.serverStatus === 1) { + throw Object.assign(new Error('unsupported serverStatus'), { code: 59 }); + } + return { ok: 1 }; + }); + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValueOnce({ + binding, + getMongoClient: () => ({ db: () => ({ admin: () => ({ command }) }) }), + } as unknown as ClustersClient); + vi.mocked(ClustersClient.reportFailure).mockReturnValueOnce('other'); + + await expect(createCallerFactory(clusterDashboardRouter)(createContext()).measureRtt()).resolves.toMatchObject({ + pingLatencyMs: expect.any(Number), + uptimeSeconds: null, + errors: [expect.stringContaining('serverStatus')], + }); + }); }); it('returns unavailable when a storage collector observes rejected credentials', async () => { From 0933652acf1ad3558800ab888c1bb477435a6d03 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 20:32:19 +0000 Subject: [PATCH 07/23] chore: clean up PR6 verification after syncing PR5 Regenerate localization, apply repository formatting, keep Disconnect type narrowing explicit, and update the Atlas fixture for connected-state detection. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- build/verification/browser/scenarios.ts | 6 +- l10n/bundle.l10n.json | 22 +++++- .../deleteFolder/ExecuteStep.ts | 8 ++- .../deleteFolder/deleteFolder.test.ts | 2 +- src/commands/disconnect/disconnect.ts | 11 +-- .../importDocuments/importDocuments.test.ts | 7 +- .../openInteractiveShell.ts | 12 +++- src/commands/saveConnectionEdit.ts | 20 ++++-- .../updateConnectionString.test.ts | 4 +- .../updateConnectionString.ts | 24 ++++--- .../updateCredentials.test.ts | 72 ++++++++++++------- .../updateCredentials/updateCredentials.ts | 5 +- src/documentdb/ClusterSession.ts | 2 +- src/documentdb/ClustersClient.test.ts | 4 +- src/documentdb/ClustersClient.ts | 2 +- src/documentdb/connectionTeardown.test.ts | 36 +++++++--- src/documentdb/connectionTeardown.ts | 44 ++++++++---- .../shell/ShellSessionManager.test.ts | 6 +- src/documentdb/shell/ShellSessionManager.ts | 4 +- .../discovery-tree/AtlasClusterItem.test.ts | 1 + .../documentdb/boundViewOperations.ts | 4 +- .../clusterDashboardRouter.test.ts | 8 ++- 22 files changed, 216 insertions(+), 88 deletions(-) diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index d872f8513..5956b0b01 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -2580,7 +2580,11 @@ const clusterDashboardScenarios = { }, }, { action: 'waitFor', name: 'disconnected overlay', selector: '.disconnectedOverlay' }, - { action: 'releaseReply', name: 'deliver the old health poll', path: 'clusterDashboard.measureRtt' }, + { + action: 'releaseReply', + name: 'deliver the old health poll', + path: 'clusterDashboard.measureRtt', + }, ], }, { diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 1bc9cabc6..aa4c01dc5 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", @@ -2472,6 +2484,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 +2987,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 +3007,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 +3255,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:", @@ -3419,6 +3436,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 +3543,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 +3595,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/src/commands/connections-view/deleteFolder/ExecuteStep.ts b/src/commands/connections-view/deleteFolder/ExecuteStep.ts index aa15b3f7f..81dd41589 100644 --- a/src/commands/connections-view/deleteFolder/ExecuteStep.ts +++ b/src/commands/connections-view/deleteFolder/ExecuteStep.ts @@ -11,8 +11,8 @@ import { refreshParentInConnectionsView, withConnectionsViewProgress, } from '../../../tree/connections-view/connectionsViewHelpers'; -import { type DeleteFolderWizardContext } from './DeleteFolderWizardContext'; import { enumerateConnectionsInFolder } from '../verificationUtils'; +import { type DeleteFolderWizardContext } from './DeleteFolderWizardContext'; /** * Step to execute the folder deletion operation. @@ -30,7 +30,7 @@ export class ExecuteStep extends AzureWizardExecuteStep { await withConnectionsViewProgress(async () => { @@ -70,7 +70,9 @@ export class ExecuteStep extends AzureWizardExecuteStep ConnectionStorageService.delete(context.connectionType, child.id)); + await removeConnection(child.id, () => + ConnectionStorageService.delete(context.connectionType, child.id), + ); context.deletedConnections++; } } diff --git a/src/commands/connections-view/deleteFolder/deleteFolder.test.ts b/src/commands/connections-view/deleteFolder/deleteFolder.test.ts index ae2894b07..b4d95aa38 100644 --- a/src/commands/connections-view/deleteFolder/deleteFolder.test.ts +++ b/src/commands/connections-view/deleteFolder/deleteFolder.test.ts @@ -59,7 +59,7 @@ vi.mock('../verificationUtils', async () => ({ })); import { UserCancelledError } from '@microsoft/vscode-azext-utils'; -import { withConnectionRemoval } from '../../../documentdb/connectionTeardown'; +import { type withConnectionRemoval } from '../../../documentdb/connectionTeardown'; import { ConnectionType, ItemType, type ConnectionItem } from '../../../services/connectionStorageService'; import { type DeleteFolderWizardContext } from './DeleteFolderWizardContext'; import { ExecuteStep } from './ExecuteStep'; diff --git a/src/commands/disconnect/disconnect.ts b/src/commands/disconnect/disconnect.ts index 01332ab8e..e3def27ee 100644 --- a/src/commands/disconnect/disconnect.ts +++ b/src/commands/disconnect/disconnect.ts @@ -10,9 +10,13 @@ import { ext } from '../../extensionVariables'; import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { type TreeElement } from '../../tree/TreeElement'; +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 (!(node instanceof ClusterItemBase)) { + if (!isClusterNode(node)) { throw new UserCancelledError(); } @@ -25,10 +29,7 @@ export async function disconnect(context: IActionContext, node?: TreeElement): P } export function connectDisconnected(_context: IActionContext, node?: TreeElement): void { - if ( - !(node instanceof ClusterItemBase) || - ClustersClient.getLatchReason(node.cluster.clusterId) !== 'userDisconnected' - ) { + if (!isClusterNode(node) || ClustersClient.getLatchReason(node.cluster.clusterId) !== 'userDisconnected') { return; } diff --git a/src/commands/importDocuments/importDocuments.test.ts b/src/commands/importDocuments/importDocuments.test.ts index 5c76cbcdd..ecf594d6c 100644 --- a/src/commands/importDocuments/importDocuments.test.ts +++ b/src/commands/importDocuments/importDocuments.test.ts @@ -17,7 +17,12 @@ import { exportQueryResults } from '../exportDocuments/exportDocuments'; import { importDocuments } from './importDocuments'; vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), getLatchReason: 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', () => ({ diff --git a/src/commands/openInteractiveShell/openInteractiveShell.ts b/src/commands/openInteractiveShell/openInteractiveShell.ts index 87087168f..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(), () => pty.disconnect()); + 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(), () => pty.disconnect()); + registerShellTerminal( + terminal, + () => pty.getTerminalInfo(), + () => pty.disconnect(), + ); terminal.show(); } diff --git a/src/commands/saveConnectionEdit.ts b/src/commands/saveConnectionEdit.ts index 0e5b96c06..ee68ad7a4 100644 --- a/src/commands/saveConnectionEdit.ts +++ b/src/commands/saveConnectionEdit.ts @@ -4,8 +4,8 @@ *--------------------------------------------------------------------------------------------*/ import { UserCancelledError } from '@microsoft/vscode-azext-utils'; -import * as vscode from 'vscode'; 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'; @@ -93,15 +93,25 @@ export async function saveConnectionEdit( 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) { + 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); + 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.'), + vscode.l10n.t( + 'The connection update may be incomplete. Check the saved settings before reconnecting.', + ), ); } await closing; diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index 2aeb9371a..4b6703005 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -205,7 +205,9 @@ describe('updateConnectionString rejected-destination recovery', () => { await updateConnectionString(makeContext(), item); expect(capturedContexts[0].connectionStringSaved).toBe(true); - expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id', { alreadyInvalidated: true }); + 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); diff --git a/src/commands/updateConnectionString/updateConnectionString.ts b/src/commands/updateConnectionString/updateConnectionString.ts index 00c82916a..27229623a 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -83,17 +83,19 @@ export async function updateConnectionString(context: IActionContext, node: Docu if (isRecoveryCurrent?.() === false) { return; } - 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; + 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; diff --git a/src/commands/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index ed355eee3..f5bb43bd0 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -259,10 +259,12 @@ describe('updateCredentials post-wizard updates', () => { 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'); - }); + mockSave.mockImplementationOnce( + async (_zone: storageModule.StorageZone, item: storageModule.ConnectionItem) => { + stored.secrets = structuredClone(item.secrets); + throw new Error('Metadata write failed'); + }, + ); await updateCredentials(context, node); @@ -294,7 +296,10 @@ describe('updateCredentials post-wizard updates', () => { properties: { ...originalConnection.properties, selectedAuthMethod: authMethod }, secrets: { connectionString: 'mongodb://new.example.com:27017/', ...secrets }, }; - mockGet.mockResolvedValueOnce(originalConnection).mockResolvedValueOnce(originalConnection).mockResolvedValue(savedConnection); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue(savedConnection); mockExecute.mockImplementationOnce(async (wizardContext) => { wizardContext.credentialsSaved = true; }); @@ -318,19 +323,24 @@ describe('updateCredentials post-wizard updates', () => { }); expect(CredentialCache.hasCredentials(node.cluster.treeId)).toBe(false); expect(mockDeleteCredentials).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); - expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, { alreadyInvalidated: true }); + 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.mockResolvedValueOnce(originalConnection).mockResolvedValueOnce(originalConnection).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); @@ -339,10 +349,13 @@ describe('updateCredentials post-wizard updates', () => { }); it('deletes cached credentials when the stored authentication method is missing', async () => { - mockGet.mockResolvedValueOnce(originalConnection).mockResolvedValueOnce(originalConnection).mockResolvedValue({ - ...originalConnection, - properties: { ...originalConnection.properties, selectedAuthMethod: undefined }, - }); + mockGet + .mockResolvedValueOnce(originalConnection) + .mockResolvedValueOnce(originalConnection) + .mockResolvedValue({ + ...originalConnection, + properties: { ...originalConnection.properties, selectedAuthMethod: undefined }, + }); await updateCredentials(context, node); @@ -353,16 +366,27 @@ describe('updateCredentials post-wizard updates', () => { 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' } }, - }); + 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.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' }, disconnect: disconnectOther }, diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index fa01a3649..920684fe8 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -163,7 +163,10 @@ export async function updateCredentials(context: IActionContext, node: DocumentD } const authMethod = authMethodFromString(updated.properties.selectedAuthMethod); const native = updated.secrets.nativeAuthConfig; - if (!authMethod || (authMethod === AuthMethodId.NativeAuth && (!native?.connectionUser || !native.connectionPassword))) { + if ( + !authMethod || + (authMethod === AuthMethodId.NativeAuth && (!native?.connectionUser || !native.connectionPassword)) + ) { return; } CredentialCache.setAuthCredentials( diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index f2a07cc47..6bd272cc7 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -14,8 +14,8 @@ 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 { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { isRetiredConnectionBinding } from './connectionBindingRetirement'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { runWithClient } from './runWithClient'; import { SchemaStore } from './SchemaStore'; import { fixupDocumentDbExplain } from './utils/fixupDocumentDbExplain'; diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 840a34db6..511803848 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -330,7 +330,9 @@ describe('regular connection startup diagnostics', () => { await ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); ClustersClient.unlatch(clusterId); - await expect(ClustersClient.resolveBoundClient(old.binding)).rejects.toMatchObject({ reason: 'credentialsChanged' }); + 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); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 53bd0a4e7..643b43f66 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -52,8 +52,8 @@ import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { readJwtTimes } from './auth/tokenExpiry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; -import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { isRetiredConnectionBinding, retireConnectionBindings } from './connectionBindingRetirement'; +import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; import { CredentialCache, type CachedClusterCredentials } from './CredentialCache'; diff --git a/src/documentdb/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts index 571636dff..94632f365 100644 --- a/src/documentdb/connectionTeardown.test.ts +++ b/src/documentdb/connectionTeardown.test.ts @@ -8,7 +8,13 @@ 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'; +import { + commitTeardown, + confirmTeardown, + latchForTeardown, + teardownConnection, + withConnectionRemoval, +} from './connectionTeardown'; const mocks = vi.hoisted(() => ({ getSetting: vi.fn(), @@ -42,11 +48,15 @@ vi.mock('@microsoft/vscode-azext-utils', () => ({ }, })); vi.mock('../services/SettingsService', () => ({ SettingsService: { getSetting: mocks.getSetting } })); -vi.mock('../services/taskService/taskService', () => ({ TaskService: { getConflictingTasks: mocks.getConflictingTasks } })); +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('./shell/ShellTerminalLinkProvider', () => ({ + getRegisteredShellTerminals: mocks.getRegisteredShellTerminals, +})); vi.mock('../commands/playground/executePlaygroundCode', () => ({ getPlaygroundEvaluators: mocks.getPlaygroundEvaluators, stopPlaygroundEvaluator: mocks.stopPlaygroundEvaluator, @@ -105,18 +115,22 @@ describe('connection teardown', () => { latches.set(id, reason); epochs.set(id, (epochs.get(id) ?? 0) + 1); }); - mocks.unlatch.mockImplementation((id: string) => { latches.delete(id); }); + mocks.unlatch.mockImplementation((id: string) => { + latches.delete(id); + }); mocks.getSetting.mockReturnValue('keepOpenDisabled'); const draft = register('documentView', true); 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); + 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(latches.has(otherId)).toBe(false); diff --git a/src/documentdb/connectionTeardown.ts b/src/documentdb/connectionTeardown.ts index f8b20b53c..ca6ca2cec 100644 --- a/src/documentdb/connectionTeardown.ts +++ b/src/documentdb/connectionTeardown.ts @@ -3,7 +3,11 @@ * 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 { + 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'; @@ -66,12 +70,14 @@ export async function confirmTeardown( 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)) { + 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?'), + 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, @@ -98,7 +104,10 @@ export async function confirmTeardown( } /** Check the whole batch and fence it synchronously, before any resource is changed. */ -export function latchForTeardown(target: string | readonly string[], reason: TeardownReason | 'credentialsUpdating'): boolean { +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; @@ -162,7 +171,9 @@ export async function commitTeardown( export async function withConnectionRemoval( ids: readonly string[], - remove: (removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise) => Promise, + remove: ( + removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise, + ) => Promise, ): Promise { await reportTeardown(ids, 'connectionRemoved', async ({ telemetry }) => { await removeConnections(ids, remove, telemetry.properties); @@ -171,7 +182,9 @@ export async function withConnectionRemoval( async function removeConnections( ids: readonly string[], - remove: (removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise) => Promise, + remove: ( + removeConnection: (clusterId: string, deleteStored: () => Promise) => Promise, + ) => Promise, properties: IActionContext['telemetry']['properties'], ): Promise { const confirmed = await confirmTeardown(ids, 'connectionRemoved'); @@ -184,7 +197,11 @@ async function removeConnections( 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')) { + 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')) { @@ -222,7 +239,10 @@ async function removeConnections( }); } finally { for (const [id, target] of targets) { - if (ClustersClient.getEpoch(id) !== target.epoch || ClustersClient.getLatchReason(id) !== 'connectionRemoved') { + if ( + ClustersClient.getEpoch(id) !== target.epoch || + ClustersClient.getLatchReason(id) !== 'connectionRemoved' + ) { continue; } if (target.started) { @@ -258,8 +278,8 @@ async function reportTeardown( (total, id) => total + getConnectionSurfaces(id).length, 0, ); - context.telemetry.measurements.shellCount = getRegisteredShellTerminals().filter( - (shell) => targets.has(shell.info.clusterId), + 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; diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index e252ca7de..7a5df24cf 100644 --- a/src/documentdb/shell/ShellSessionManager.test.ts +++ b/src/documentdb/shell/ShellSessionManager.test.ts @@ -107,7 +107,11 @@ 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' }); + const manager = new ShellSessionManager({ + clusterId, + clusterDisplayName: 'Test Cluster', + databaseName: 'test', + }); ClustersClient.latch(clusterId, 'userDisconnected'); try { await expect(manager.initialize()).rejects.toMatchObject({ reason: 'userDisconnected' }); diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index f7fef7bb0..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 { @@ -19,8 +21,6 @@ import { } from '../auth/documentdbTokenResource'; import { evaluateEntraDestinationFromSettings } from '../auth/entraDestinationSettings'; import { clearEntraTokenFailure, recordEntraTokenFailure } from '../auth/entraErrors/entraTokenFailures'; -import { ClustersClient } from '../ClustersClient'; -import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; import { WorkerSessionManager, 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/webviews/documentdb/boundViewOperations.ts b/src/webviews/documentdb/boundViewOperations.ts index 6465d5bfc..69cfad9d4 100644 --- a/src/webviews/documentdb/boundViewOperations.ts +++ b/src/webviews/documentdb/boundViewOperations.ts @@ -61,7 +61,9 @@ export function guardBoundViewOperation(binding: ConnectionBinding, signal?: Abo if (signal?.aborted) { throw new UserCancelledError('staleBoundViewOperation'); } - const reason = isRetiredConnectionBinding(binding) ? 'credentialsChanged' : ClustersClient.getLatchReason(clusterId); + const reason = isRetiredConnectionBinding(binding) + ? 'credentialsChanged' + : ClustersClient.getLatchReason(clusterId); if (reason) { throw new ConnectionUnavailableError(reason); } diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts index 8241deaeb..57dda925a 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts @@ -195,7 +195,9 @@ describe('clusterDashboardRouter create actions', () => { } as unknown as ClustersClient); vi.mocked(ClustersClient.reportFailure).mockReturnValueOnce(kind); - await expect(createCallerFactory(clusterDashboardRouter)(createContext()).measureRtt()).resolves.toMatchObject({ + await expect( + createCallerFactory(clusterDashboardRouter)(createContext()).measureRtt(), + ).resolves.toMatchObject({ unavailable: { reason }, }); expect(ClustersClient.reportFailure).toHaveBeenCalledWith(binding, failure); @@ -214,7 +216,9 @@ describe('clusterDashboardRouter create actions', () => { } as unknown as ClustersClient); vi.mocked(ClustersClient.reportFailure).mockReturnValueOnce('other'); - await expect(createCallerFactory(clusterDashboardRouter)(createContext()).measureRtt()).resolves.toMatchObject({ + await expect( + createCallerFactory(clusterDashboardRouter)(createContext()).measureRtt(), + ).resolves.toMatchObject({ pingLatencyMs: expect.any(Number), uptimeSeconds: null, errors: [expect.stringContaining('serverStatus')], From 71c646b678569864d04809fa6d2d9b8202c33877 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 20:32:19 +0000 Subject: [PATCH 08/23] chore: version the PR6 operator VSIX as 1.1.1-alpha.4 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) 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 6b5ab0931..ffcdd79d6 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", From 9744b2467d0aea831782387b84d12a5bc180dabe Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 10:34:37 +0000 Subject: [PATCH 09/23] fix: polish the Disconnect recovery dialog after OP-5 (WI-7) Use Reconnect for an explicit disconnect, keep Fluent layout defaults, and verify teardown rejects active import and export leases. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../importDocuments/importDocuments.test.ts | 5 ++++ src/tree/documentdb/ClusterItemBase.test.ts | 2 +- src/tree/documentdb/ClusterItemBase.ts | 2 +- .../describeUnavailableConnection.ts | 7 +++-- .../components/DisconnectedOverlay.scss | 27 ------------------- .../components/DisconnectedOverlay.test.tsx | 2 +- .../components/DisconnectedOverlay.tsx | 13 +++++---- 7 files changed, 21 insertions(+), 37 deletions(-) diff --git a/src/commands/importDocuments/importDocuments.test.ts b/src/commands/importDocuments/importDocuments.test.ts index ecf594d6c..413fbeb19 100644 --- a/src/commands/importDocuments/importDocuments.test.ts +++ b/src/commands/importDocuments/importDocuments.test.ts @@ -9,6 +9,7 @@ import { beforeEach, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { confirmTeardown } from '../../documentdb/connectionTeardown'; import { DocumentDBExperience } from '../../DocumentDBExperiences'; import { ext } from '../../extensionVariables'; import { TaskService } from '../../services/taskService/taskService'; @@ -127,6 +128,8 @@ it('holds an import lease through client resolution and the final flush', async }), ).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', @@ -167,6 +170,8 @@ it('holds an export lease before client resolution and releases it on failure', }), ).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'); diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 0c749d680..fc4f58b6c 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -469,7 +469,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl try { expect(await node.getChildren()).toEqual([ - expect.objectContaining({ label: 'Connect', id: `${treeId}/connect`, commandArgs: [node] }), + expect.objectContaining({ label: 'Reconnect', id: `${treeId}/connect`, commandArgs: [node] }), ]); expect(node.getTreeItem().contextValue?.split(';')).not.toContain('connected'); expect(mockHasCredentials).not.toHaveBeenCalled(); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index 1fc95de86..bf64996b3 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -662,7 +662,7 @@ 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({ } }} > - +