diff --git a/build/verification/browser/core.test.ts b/build/verification/browser/core.test.ts index 6131dce4c..9ba420b27 100644 --- a/build/verification/browser/core.test.ts +++ b/build/verification/browser/core.test.ts @@ -66,6 +66,24 @@ describe('Shared browser fixture core', (): void => { ]); }); + it('releases a held reply and drops an aborted request', async (): Promise => { + const messages = vi.spyOn(window, 'postMessage').mockImplementation((): void => {}); + const path = 'localQuickStart.checkPort'; + const api = fakeVsCodeApi({ [path]: { ...rpc[path], holdReply: true } }, [])(); + api.postMessage({ id: 'aborted', op: { type: 'query', path } }); + api.postMessage({ id: 'second', op: { type: 'query', path } }); + api.postMessage({ id: 'aborted', op: { type: 'abort', path } }); + await Promise.resolve(); + + expect(messages).not.toHaveBeenCalled(); + expect(window.__harnessReleaseReply(path)).toBe(true); + expect(window.__harnessReleaseReply(path)).toBe(false); + expect(messages.mock.calls.map((call): unknown => call[0])).toEqual([ + { id: 'second', result: port }, + { id: 'second', complete: true }, + ]); + }); + it('records escaping actions and answers only from fixtures without opening or copying anything', async (): Promise => { const errors: string[] = []; const messages = vi.spyOn(window, 'postMessage').mockImplementation((): void => {}); diff --git a/build/verification/browser/core/fakeVsCodeApi.ts b/build/verification/browser/core/fakeVsCodeApi.ts index 8bbde9225..1bfd3d452 100644 --- a/build/verification/browser/core/fakeVsCodeApi.ts +++ b/build/verification/browser/core/fakeVsCodeApi.ts @@ -19,6 +19,7 @@ export interface HarnessCall { declare global { interface Window { __harnessCalls: HarnessCall[]; + __harnessReleaseReply: (path: FixturePaths) => boolean; } } @@ -38,6 +39,18 @@ export function fakeVsCodeApi(rpc: RpcFixtures, errors: string[]): typeof window const calls: HarnessCall[] = []; window.__harnessCalls = calls; const subscriptions = new Set(); + const seenPaths = new Set(); + const heldReplies = new Map void }>(); + window.__harnessReleaseReply = (path): boolean => { + for (const [id, reply] of [...heldReplies].reverse()) { + if (reply.path === path) { + heldReplies.delete(id); + reply.sendReply(); + return true; + } + } + return false; + }; let acquired = false; function send(message: VsCodeLinkResponseMessage): void { @@ -52,6 +65,7 @@ export function fakeVsCodeApi(rpc: RpcFixtures, errors: string[]): typeof window const { id, op } = value; if (op.type === 'subscription.stop' || op.type === 'abort') { subscriptions.delete(id); + heldReplies.delete(id); return; } calls.push({ path: op.path, type: op.type, input: op.input }); @@ -65,11 +79,13 @@ export function fakeVsCodeApi(rpc: RpcFixtures, errors: string[]): typeof window if (response.keepOpen) { subscriptions.add(id); } - queueMicrotask((): void => { + const reply = seenPaths.has(op.path) ? (response.afterFirst ?? response) : response; + seenPaths.add(op.path); + const sendReply = (): void => { if (response.keepOpen && !subscriptions.has(id)) { return; } - for (const result of response.results) { + for (const result of reply.results) { send({ id, result }); } if (response.undefinedResult) { @@ -78,7 +94,12 @@ export function fakeVsCodeApi(rpc: RpcFixtures, errors: string[]): typeof window if (!response.keepOpen) { send({ id, complete: true }); } - }); + }; + if (reply.holdReply) { + heldReplies.set(id, { path: op.path, sendReply }); + } else { + queueMicrotask(sendReply); + } } return (): WebviewApi => { diff --git a/build/verification/browser/core/fixtures.ts b/build/verification/browser/core/fixtures.ts index 26316d7fb..7b23bb5ef 100644 --- a/build/verification/browser/core/fixtures.ts +++ b/build/verification/browser/core/fixtures.ts @@ -24,6 +24,8 @@ export interface RpcFixture { readonly results: readonly unknown[]; readonly keepOpen?: boolean; readonly undefinedResult?: boolean; + readonly holdReply?: boolean; + readonly afterFirst?: { readonly results: readonly unknown[]; readonly holdReply?: boolean }; } export type RpcFixtures = Readonly>>; @@ -37,12 +39,15 @@ export type FixtureAtPath = P extends `${infer Head}.${infe : never; type StreamItem = T extends AsyncIterable ? Item : T; -// tRPC's JSON-serialized output inference represents void procedures as never. The wire protocol -// deliberately supports explicit undefined results, so these fixtures retain the host's void type. -type FixtureResult = [T] extends [never] ? void : StreamItem; +// tRPC infers never for void outputs, but the extension host sends null for those results. +type FixtureResult = [T] extends [never] ? void | null : StreamItem; export type TypedRpcFixtures = { - readonly [P in FixturePaths]?: Omit & { + readonly [P in FixturePaths]?: Omit & { readonly results: readonly FixtureResult>[]; + readonly afterFirst?: { + readonly results: readonly FixtureResult>[]; + readonly holdReply?: boolean; + }; }; }; diff --git a/build/verification/browser/fixtures.ts b/build/verification/browser/fixtures.ts index 4352f2dcf..dff59cf9b 100644 --- a/build/verification/browser/fixtures.ts +++ b/build/verification/browser/fixtures.ts @@ -51,7 +51,7 @@ export interface HarnessFixture extends ViewFixture { function reply( type: RpcFixture['type'], result: T, -): Omit & { readonly results: readonly T[] } { +): Omit & { readonly results: readonly T[] } { if (result === undefined) { return { type, results: [], undefinedResult: true }; } diff --git a/build/verification/browser/scenario-playwright.ts b/build/verification/browser/scenario-playwright.ts index 85fe07a83..c656760aa 100644 --- a/build/verification/browser/scenario-playwright.ts +++ b/build/verification/browser/scenario-playwright.ts @@ -43,9 +43,50 @@ export async function runScenario(page: IntegratedPage, origin: string, route: S if (await page.evaluate((): boolean => document.documentElement.dataset.ready === 'failed')) { throw new Error(`Page failed before step: ${step.name}`); } + if (step.action === 'post') { + await page.evaluate( + (message): void => window.postMessage(message, window.location.origin), + step.message, + ); + continue; + } + if (step.action === 'releaseReply') { + await wait((path) => window.__harnessReleaseReply(path), step.path, step.name); + // The reply is an asynchronous message. Give the app a render before reading the result. + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => resolve()))); + continue; + } + if (step.action === 'waitFor') { + await wait((selector) => document.querySelector(selector) !== null, step.selector, step.name); + continue; + } const locator = page.getByRole(step.role, { name: step.name, exact: true }); - if (step.action === 'click') { + if (step.action === 'press') { + await locator.press(step.key, { timeout: 60000 }); + } else if (step.action === 'click') { await locator.click({ timeout: 60000 }); + } else if (step.action === 'replaceText') { + const modifier = await page.evaluate(() => + /Mac|iPhone|iPad/.test(navigator.platform) ? 'Meta' : 'Control', + ); + const renderedEditor = `.monaco-editor:has([aria-label="${step.name}"]) .view-lines`; + await locator.press(`${modifier}+A`, { timeout: 60000 }); + await locator.press('Backspace', { timeout: 60000 }); + await wait( + (selector) => document.querySelector(selector)?.textContent?.trim() === '', + renderedEditor, + 'cleared editor', + ); + await page.keyboard.insertText(step.value); + await wait( + ({ selector, value }) => + document + .querySelector(selector) + ?.textContent?.replace(/\u00a0/g, ' ') + .includes(value) === true, + { selector: renderedEditor, value: step.value }, + 'editor text to render', + ); } else { await locator.fill(step.value, { timeout: 60000 }); } @@ -92,6 +133,7 @@ export async function runScenario(page: IntegratedPage, origin: string, route: S count: calls.length, matching: calls.filter( (call): boolean => + expected.checkInput === false || JSON.stringify(call.input) === JSON.stringify(expected.input), ).length, }; @@ -102,7 +144,10 @@ export async function runScenario(page: IntegratedPage, origin: string, route: S name: assertion.name, passed: actual.count === assertion.count && actual.matching === assertion.count, actual, - expected: { count: assertion.count, input: assertion.input }, + expected: + assertion.checkInput === false + ? { count: assertion.count } + : { count: assertion.count, input: assertion.input }, }); } else if (assertion.kind === 'order') { const actual = await page.evaluate( diff --git a/build/verification/browser/scenarios.test.ts b/build/verification/browser/scenarios.test.ts index 597b80ec6..0817b91d3 100644 --- a/build/verification/browser/scenarios.test.ts +++ b/build/verification/browser/scenarios.test.ts @@ -32,8 +32,8 @@ describe('L2-dev manifest and routes', (): void => { it('round-trips every scenario and theme, without duplicate routes', (): void => { const routes = scenarioRoutes(); - expect(routes).toHaveLength(171); - expect(new Set(routes.map((route): string => route.path)).size).toBe(171); + expect(routes).toHaveLength(186); + expect(new Set(routes.map((route): string => route.path)).size).toBe(186); for (const route of routes) expect(parseScenarioRoute(route.path)).toEqual(route); }); @@ -71,7 +71,7 @@ describe('L2-dev manifest and routes', (): void => { }); it('provides path-only all/view/theme helpers and rejects unknown subsets', (): void => { - expect(runnerRoutes('/scenarios/run-all.js')).toHaveLength(171); + expect(runnerRoutes('/scenarios/run-all.js')).toHaveLength(186); expect(runnerRoutes('/scenarios/run-all/connectionDiagnostics.js')).toHaveLength(84); expect(runnerRoutes('/scenarios/run-all/localQuickStart.js')).toHaveLength(75); expect(runnerRoutes('/scenarios/run-all/localQuickStart/dark.js')).toHaveLength(25); diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index 8e92ac995..794d5463d 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -50,17 +50,24 @@ export type ScenarioStep = readonly role: 'button' | 'link' | 'switch' | 'menuitem' | 'radio'; readonly name: string; } - | { readonly action: 'fill'; readonly role: 'textbox'; readonly name: string; readonly value: string }; + | { readonly action: 'fill'; readonly role: 'textbox' | 'searchbox'; readonly name: string; readonly value: string } + | { readonly action: 'replaceText'; readonly role: 'textbox'; readonly name: string; readonly value: string } + | { readonly action: 'press'; readonly role: 'button'; readonly name: string; readonly key: string } + | { readonly action: 'waitFor'; readonly name: string; readonly selector: string } + | { readonly action: 'post'; readonly name: string; readonly message: unknown } + | { readonly action: 'releaseReply'; readonly name: string; readonly path: FixturePaths }; type CallAssertion = { [P in FixturePaths]: { readonly kind: 'calls'; readonly name: string; readonly path: P; - readonly input: FixtureAtPath; readonly count: number; readonly steps: readonly ScenarioStep[]; - }; + } & ( + | { readonly input: FixtureAtPath; readonly checkInput?: true } + | { readonly checkInput: false } + ); }[FixturePaths]; /** The elements matching `selector`, in document order, contain `texts` one to one and in order. */ @@ -2422,10 +2429,349 @@ const diagnosticsScenarios = { ), } as const satisfies Readonly>>; +const documentViewBase = defaultScenario('documentView'); +const documentEditReadiness = { ...documentViewBase.readiness, content: ['Save'] }; +const saveDocumentPath = 'mongoClusters.documentView.saveDocument'; +const disconnectedDocument = { + reason: 'userDisconnected', + title: 'Disconnected', + detail: 'Connect from the connection tree, then click Retry.', + action: 'retry', +} as const; +const documentEditorName = 'Document Editor: Edit the document in JSON format'; +const firstDocumentEdit = { + action: 'replaceText', + role: 'textbox', + name: documentEditorName, + value: '{"_id":"stage0-1","name":"First pending edit"}', +} as const; +const saveDocumentStep = { action: 'click', role: 'button', name: 'Save to the database' } as const; + +const documentViewScenarios = { + default: documentViewBase, + 'disconnected-dirty': { + ...documentViewBase, + readiness: documentEditReadiness, + rpc: { + ...documentViewBase.rpc, + [saveDocumentPath]: { type: 'mutation', results: [{ unavailable: disconnectedDocument }] }, + 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, + }, + assertions: [ + { + kind: 'attribute', + name: 'preserves the mounted draft behind an inert overlay', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: '', + steps: [ + firstDocumentEdit, + saveDocumentStep, + { action: 'waitFor', name: 'disconnected overlay', selector: '.disconnectedOverlay' }, + ], + }, + { + kind: 'text', + name: 'the rejected save does not replace the draft', + selector: '.monaco-editor .view-lines', + includes: ['First pending edit'], + excludes: ['Stage 0 document payload'], + }, + ], + }, + 'stale-save-after-reconnect': { + ...documentViewBase, + readiness: documentEditReadiness, + rpc: { + ...documentViewBase.rpc, + [saveDocumentPath]: { + type: 'mutation', + holdReply: true, + results: [{ documentId: '"stage0-1"', documentStringified: '{"name":"Old save reply"}' }], + }, + 'mongoClusters.documentView.recoverUnavailable': { + type: 'mutation', + results: [{ recovered: { text: 'Reconnected' } }], + }, + 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, + }, + assertions: [ + { + kind: 'attribute', + name: 'recovery does not discard the editor', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + steps: [ + firstDocumentEdit, + saveDocumentStep, + { + action: 'post', + name: 'disable Document View', + message: { type: 'documentView.connectionUnavailable', unavailable: disconnectedDocument }, + }, + { action: 'click', role: 'button', name: 'Retry' }, + { + action: 'waitFor', + name: 'the editor to be enabled after reconnect', + selector: '.disconnectedOverlayBackground:not([inert])', + }, + { + ...firstDocumentEdit, + value: '{"_id":"stage0-1","name":"Newer unsaved edit"}', + }, + ], + }, + { + kind: 'stableText', + name: 'the old save reply cannot overwrite the newer edit', + selector: '.monaco-editor .view-lines', + steps: [{ action: 'releaseReply', name: 'deliver the old save reply', path: saveDocumentPath }], + }, + { + kind: 'attribute', + name: 'the newer edit stays dirty and can be saved', + selector: 'button[aria-label="Save to the database"]', + attribute: 'disabled', + expected: null, + }, + ], + }, +} as const satisfies Readonly>>; + +const clusterDashboardBase = defaultScenario('clusterDashboard'); +const clusterDashboardScenarios = { + default: clusterDashboardBase, + disconnected: { + ...clusterDashboardBase, + readiness: { ...clusterDashboardBase.readiness, content: ['stage0_inventory'] }, + rpc: { + ...clusterDashboardBase.rpc, + 'clusterDashboard.recoverUnavailable': { + type: 'mutation', + results: [{ recovered: { text: 'Reconnected' } }], + }, + }, + assertions: [ + { + kind: 'attribute', + name: 'keeps the dashboard mounted behind the unavailable overlay', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: '', + steps: [ + { + action: 'fill', + role: 'searchbox', + name: 'Filter databases by name', + value: 'stage0', + }, + { + action: 'post', + name: 'disable Cluster Dashboard', + message: { + type: 'clusterDashboard.connectionUnavailable', + unavailable: disconnectedDocument, + }, + }, + { action: 'waitFor', name: 'disconnected overlay', selector: '.disconnectedOverlay' }, + ], + }, + { + kind: 'text', + name: 'keeps the last inventory and filter visible', + selector: '.inventoryPanel', + includes: ['stage0_inventory'], + excludes: [], + }, + { + kind: 'attribute', + name: 'keeps the inventory filter', + selector: 'input[aria-label="Filter databases by name"]', + attribute: 'value', + expected: 'stage0', + }, + ], + }, +} as const satisfies Readonly>>; + +const collectionViewBase = defaultScenario('collectionView'); +const collectionQueryPath = 'mongoClusters.collectionView.runFindQuery'; +const collectionTablePath = 'mongoClusters.collectionView.getCurrentPageAsTable'; +const collectionFilterName = 'Filter: Enter the DocumentDB query filter'; +const collectionFilterSelector = `.monaco-editor:has([aria-label="${collectionFilterName}"]) .view-lines`; +const collectionFilter = { + action: 'replaceText', + role: 'textbox', + name: collectionFilterName, + value: '{"name":"Alpha"}', +} as const; +const runCollectionQuery = { + action: 'click', + role: 'button', + name: 'Find Query: execute the current editor values', +} as const; +const collectionSignInRequired = { + reason: 'signInRequired', + title: 'Sign-in required', + detail: 'Sign in from the connection tree, then click Retry.', + action: 'retry', +} as const; +const collectionViewScenarios = { + default: collectionViewBase, + 'disconnected-signInRequired': { + ...collectionViewBase, + rpc: { + ...collectionViewBase.rpc, + [collectionQueryPath]: { + ...fixtures.collectionView.rpc[collectionQueryPath], + afterFirst: { results: [{ unavailable: collectionSignInRequired }] }, + }, + 'mongoClusters.collectionView.recoverUnavailable': { + type: 'mutation', + results: [{ recovered: { text: 'Reconnected' } }], + }, + 'mongoClusters.collectionView.copyQueryToClipboard': { + type: 'mutation', + results: [null], + }, + 'common.confirm': { type: 'mutation', results: [{ confirmed: false }] }, + 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, + }, + assertions: [ + { + kind: 'attribute', + name: 'keeps the query and results mounted but disables their controls', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: '', + steps: [ + collectionFilter, + runCollectionQuery, + { action: 'waitFor', name: 'sign-in overlay', selector: '.disconnectedOverlay' }, + ], + }, + { + kind: 'text', + name: 'retains the filter text', + selector: collectionFilterSelector, + includes: ['"name":"Alpha"'], + excludes: [], + }, + { + kind: 'text', + name: 'offers Retry and Close view while sign-in stays in the tree', + selector: '.disconnectedOverlay', + includes: ['Sign-in required', 'Sign in from the connection tree, then click Retry.', 'Close view'], + excludes: ['Reconnect', 'Retry sign-in'], + }, + { + kind: 'calls', + name: 'the query shortcut while disconnected does not run another query', + path: collectionQueryPath, + count: 2, + checkInput: false, + steps: [{ action: 'press', role: 'button', name: 'Retry', key: 'Control+Enter' }], + }, + { + kind: 'attribute', + name: 'dismissing the dialog makes the existing view accessible', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + steps: [{ action: 'click', role: 'button', name: 'Dismiss dialog to copy view contents' }], + }, + { + kind: 'text', + name: 'the filter can still be copied after dismissal', + selector: collectionFilterSelector, + includes: ['"name":"Alpha"'], + excludes: [], + }, + { + kind: 'calls', + name: 'Copy Query works while the connection is unavailable', + path: 'mongoClusters.collectionView.copyQueryToClipboard', + count: 1, + checkInput: false, + steps: [{ action: 'click', role: 'button', name: 'Copy Query' }], + }, + { + kind: 'calls', + name: 'Find Query after dismissal shows the dialog without submitting another query', + path: collectionQueryPath, + count: 2, + checkInput: false, + steps: [ + runCollectionQuery, + { action: 'waitFor', name: 'sign-in overlay returns', selector: '.disconnectedOverlay' }, + ], + }, + { + kind: 'calls', + name: 'Close view requests confirmation through the host', + path: 'common.confirm', + count: 1, + checkInput: false, + steps: [{ action: 'click', role: 'button', name: 'Close view' }], + }, + ], + }, + 'stale-page-after-disconnect': { + ...collectionViewBase, + rpc: { + ...collectionViewBase.rpc, + [collectionTablePath]: { + ...fixtures.collectionView.rpc[collectionTablePath], + afterFirst: { + results: [{ path: [], headers: ['_id', 'name', 'quantity'], data: [] }], + holdReply: true, + }, + }, + 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, + }, + assertions: [ + { + kind: 'calls', + name: 'the next-page query starts before disconnect', + path: collectionQueryPath, + count: 2, + checkInput: false, + steps: [collectionFilter, { action: 'click', role: 'button', name: 'Go to next page' }], + }, + { + kind: 'stableText', + name: 'applied rows survive a disconnect and a late page reply', + selector: '.slick-viewport', + steps: [ + { + action: 'post', + name: 'disable Collection View', + message: { type: 'collectionView.connectionUnavailable', unavailable: disconnectedDocument }, + }, + { action: 'waitFor', name: 'the disconnect overlay', selector: '.disconnectedOverlay' }, + { + action: 'releaseReply', + name: 'deliver the late collection page reply', + path: collectionTablePath, + }, + ], + }, + { + kind: 'text', + name: 'the late reply does not change the displayed disconnect reason', + selector: '.disconnectedOverlay', + includes: ['Disconnected', 'Retry'], + excludes: ['Retry sign-in'], + }, + ], + }, +} as const satisfies Readonly>>; + export const scenarios = { - collectionView: { default: defaultScenario('collectionView') }, - documentView: { default: defaultScenario('documentView') }, - clusterDashboard: { default: defaultScenario('clusterDashboard') }, + collectionView: collectionViewScenarios, + documentView: documentViewScenarios, + clusterDashboard: clusterDashboardScenarios, atlasCredentials: { default: defaultScenario('atlasCredentials', atlasSteps) }, connectionDiagnostics: diagnosticsScenarios, localQuickStart: { diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 25a97a0d5..593129955 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -49,12 +49,22 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi successful results and records a sanitized diagnostic if an account or tenant cannot be listed. - **Keep one client per cluster.** Surfaces resolve it per operation and check its identity fingerprint and generation. -- **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why - and offers one action. +- **Never change identity under an open surface.** It stays open, keeps its state, and shows a + shaded, disabled view with a dialog that names the problem in a short title and gives the next + step separately. Offer **Close view**, with **Retry** beside it when the view can safely reuse + the available credentials. Credential repair stays in the tree. Dismissing the dialog with + its **X** exposes the existing contents for copying without resuming database operations. + Trying another operation shows the dialog again. **Close view** asks for confirmation. +- A pending Dashboard delete confirmation does not survive Disconnect, even when the + user reconnects as the same identity. Dashboard **Copy Collection** keeps a tree reference; + **Paste Collection** stays in the tree and uses the current connection. - After a database rejects a verified Entra identity, discard the client but keep its in-memory connection settings for explicit sign-in. Do not retain the rejected token or retry silently. When the tree offers **Retry sign-in**, it does not also offer **Retry**. -- **One teardown** serves Disconnect, Remove Connection and identity-changing credential updates. +- **Disconnect and Remove Connection** share a teardown and a tab choice. Saving a change to + connection details (including a password-only change) in this window keeps old tabs open and + copyable, but they cannot recover. Open new tabs from the tree. Unchanged settings still + support Retry and silent token renewal. - Disconnect uses the existing task-conflict guard: if a copy or export is using the cluster, leave the task and connection running. The user can retry after the task finishes or is stopped. @@ -86,6 +96,10 @@ See [decisions.md](./decisions.md): - 0013 corrections to 0012: latch before a credential save, epoch checks on replies, bindings carried through handoffs, an operation wrapper, folder deletion runs teardown. - 0014 retain in-memory settings for explicit sign-in recovery after verified Entra rejection. - 0015 use the existing latch to block startup after authentication rejection until explicit recovery. +- 0016 keep disconnected webviews open under a full-view overlay with explicit actions. +- 0017 limit unavailable webview recovery to Retry and Close view. +- 0018 saved connection edits permanently lock existing views. +- 0019 require a fresh Dashboard delete after Disconnect and retain tree-only Paste. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 9e5712c39..6eeac6991 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -10,23 +10,26 @@ created: 2026-11-19 > Why connections stay usable across token expiry and idle drops, and how open surfaces behave > when credentials or the identity change. Evidence: [research-findings.md](./research-findings.md). -| # | Decision | Status | Changed from the proposal? | Date | PR | -| ---- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ----------------------------------------------------------- | ---------- | ---------------------------------------------------------------- | -| 0001 | Entra tokens are renewed silently in every OIDC callback; the callback never prompts | Accepted | Operator accepted the explanation (2026-11-19) | 2026-11-19 | — | -| 0002 | Keep one cached client per cluster; surfaces resolve it per operation with identity + generation | Accepted (modified by 0010) | Operator position: per-operation clients cost too much | 2026-11-19 | — | -| 0003 | An open surface never moves to a different identity; it becomes disconnected, keeps its state and says why | Accepted | Operator requirement | 2026-11-19 | — | -| 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | -| 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | -| 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | -| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted | Operator: modal cannot pre-select; no remembering | 2026-11-19 | — | -| 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | -| 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | -| 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | -| 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 2026-11-19 | — | -| 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | -| 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | -| 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | -| 0015 | Use the existing latch to block startup after authentication rejection | Accepted | Operator selected A; keep the approach simple and pragmatic | 2026-11-23 | Yes; expands the existing latch rather than adding a second hold | +| # | Decision | Status | Changed from the proposal? | Date | PR | +| ---- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------ | ---------- | ---------------------------------------------------------------- | +| 0001 | Entra tokens are renewed silently in every OIDC callback; the callback never prompts | Accepted | Operator accepted the explanation (2026-11-19) | 2026-11-19 | — | +| 0002 | Keep one cached client per cluster; surfaces resolve it per operation with identity + generation | Accepted (modified by 0010) | Operator position: per-operation clients cost too much | 2026-11-19 | — | +| 0003 | An open surface never moves to a different identity; it becomes disconnected, keeps its state and says why | Accepted | Operator requirement | 2026-11-19 | — | +| 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | +| 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | +| 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | +| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted | Operator: modal cannot pre-select; no remembering | 2026-11-19 | — | +| 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | +| 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | +| 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | +| 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 2026-11-19 | — | +| 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | +| 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | +| 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | +| 0015 | Use the existing latch to block startup after authentication rejection | Accepted | Operator selected A; keep the approach simple and pragmatic | 2026-11-23 | Yes; expands the existing latch rather than adding a second hold | +| 0016 | Keep disconnected webviews open under a full-view overlay | Accepted (modified by 0017) | Operator chose a simple disabled state with explicit actions | 2026-11-24 | Yes; replaces the inline banner and single-action layout | +| 0017 | Limit unavailable webview recovery to Retry and Close view | Accepted (modified by 0018) | Operator wants credential repair in the tree and no extra recovery workflow in a tab | 2026-11-24 | Yes; removes in-view credential repair | +| 0018 | Saved connection edits permanently lock existing views | Accepted | Operator prefers simple reconnect for unchanged settings over recovery after edits | 2026-11-24 | Yes; removes same-identity recovery after a saved edit | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once @@ -424,3 +427,63 @@ the epoch still matches. It cannot clear a latch set by Disconnect, Remove or a The operator chose to reuse the existing latch rather than introduce a separate authentication hold, keeping one place to check for an unavailable connection. The rejection latch uses the existing epoch and does not add a subscription, new persistence, or a retry loop. + +## 0016. Keep disconnected webviews open under a full-view overlay + +The operator chose a simple disabled state instead of the planned warning banner. Keep the +webview and its contents mounted, but make the background unavailable for interaction. Shade +the whole view and show a calm, centered explanation with a row of actions. + +Always offer **Close**. If the connection has a supported recovery action, offer it alongside +Close. If there is no repair the tab can perform, show only **Close** and leave the tab open +until the user chooses it. Do not retry rejected credentials or navigate away automatically. +Keep this component local to the lifecycle webviews for now rather than adding a general +feature to the webview framework. + +## 0017. Limit unavailable webview recovery to Retry and Close view + +The operator decided that editing credentials from an open webview is not needed, including as +a WI-7 follow-up. Users repair credentials or sign in again from the tree. An unavailable view +keeps its contents under the Fluent dialog and offers **Close view** and, where safe, **Retry**. +Retry may attempt a connection with the credentials already available; it must not open a +credential wizard, bypass a credential rejection or removal, silently switch identities, or +resubmit the failed operation. + +Retry keeps the tab bound to its original identity and does not clear a latch. After a +same-identity repair in the tree, Retry can use the repaired connection. After an identity +change, reopen from the tree instead of moving the old view or its draft to the new identity. +A dirty Document View warns that Close view discards unsaved changes, without a second prompt. + +The operator approved testing the identity guard in OP-4 and testing the WI-7 **Keep open +(disabled)** choice and its disable message in OP-5. Neither check is dropped. + +## 0018. Saved connection edits permanently lock existing views + +The operator chose to optimize for the common workflow: reconnect with unchanged settings. +Recovering existing tabs after an explicit credentials or connection-string edit adds complexity +for an uncommon workflow. In WI-7, any such edit saved in this VS Code window that changes stored +connection details, including a password-only change, makes existing views **Close view** only. +Keep their contents and allow dismissal for copying. Do not prompt about tabs or close them when +saving; open new views from the tree after the edit. The Disconnect and Remove tab choices are +unchanged. + +Silent renewal, a network reconnect and signing back in as the same account with unchanged +settings remain supported. A cancelled edit or a save that leaves storage unchanged does not lock +views. If a failed save partially changed storage, retire the old views and tell the user the +change may be incomplete. No cross-window watcher is added. The identity guard still checks +changes from other sources, and commands still check their originating binding after pickers +and confirmations. + +## 0019. Require a new Dashboard delete after Disconnect + +The operator chose to cancel any pending Dashboard delete confirmation when the +connection lifecycle changes, even if the user reconnects as the same identity. +The user must start a fresh delete. This check is limited to Dashboard deletes: +ordinary same-identity replacement remains transparent, and tree commands keep +their existing behavior. + +The operator also kept **Copy Collection** in the Dashboard and **Paste Collection** +in the tree only. Copy stores a tree reference, not a snapshot of the data or +credentials. The later tree Paste uses the current connection; it does not resume +a Dashboard operation. Binding the whole clipboard and index-copy flow was not +part of this change. 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 70658a552..8e6619d97 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 @@ -88,8 +88,8 @@ result may continue, but say so in the message. Record the result in the Progres | OP-1 | WI-1, CP-0 | **Two parts.** (a) Before the handler change: does an expired token on a new socket get code 18 or a socket close? (b) After it: renewal succeeds. | | OP-2 | WI-3, CP-W3 | The azext workflow checks on the packaged VSIX: Azure sign-in, discovery, filters, deep links, wizards, Azure Resources view. | | OP-3 | WI-5 done | OT-2's tree part with a real sign-out: Sign in again, a dismissal, no reprompt. | -| OP-4 | WI-6 done | OT-1 (short form, with the WI-4 hook) and OT-3(a) and (b) on a dev build. | -| OP-5 | WI-7 done | OT-7 on a dev build: Disconnect during a copy, export or import, during an in-flight query or save, and a folder delete with a connected child. | +| OP-4 | WI-6 done | Cleared: short OT-1 and OT-3 identity-guard evidence; the original password-only recovery check was waived by the operator. | +| OP-5 | WI-7 done | OT-7, including **Keep open (disabled)** and its pushed disable message, plus OT-3's immediate lock after a saved edit (decision 0018). | | OP-6 | Before PR F (CP-5) | OT-1 to OT-7 on the packaged VSIX, with at least one real wait of two hours or more (PR F step 3). | ### Per-PR workflow @@ -405,7 +405,7 @@ a checkpoint changes them. new panels run as identity B while panels opened as A stay disabled. - `reason` is one of: `signInRequired`, `credentialsRejected`, `credentialsMissing`, `credentialsChanged`, `identityChanged`, `userDisconnected`, `connectionRemoved`, `unreachable`. - - `action` is one of: `reconnect`, `signInAgain`, `updateCredentials`, `close`. + - `action` is `retry` or `close`. Close view is always available. - Reasons are bounded enums. The webview gets the localized text and the action from the host. - The only push is teardown: Disconnect with Keep open calls each registered surface's `disable(reason)` (WI-6 host step 1). @@ -1375,7 +1375,7 @@ webview as a structured unavailable result, not a generic query error. - Collection View (all tabs), Document View and the Cluster Dashboard resolve their client per operation through a binding. -- They show an unavailable state (C-5) with a banner and one action. +- They show an unavailable state (C-5) with a dimmed view, Close view, and a repair action when supported. - They keep all user state. - They never apply stale results. - They never run under another identity. @@ -1450,17 +1450,19 @@ approved plan allows; the webview half then stacks on the host half without wait ### Webviews 1. **Shared UI.** - - A `DisconnectedBanner` component: a Fluent `MessageBar` with intent `warning`, the host-provided - reason text and **one** action button. It uses `role="status"` and `aria-live="polite"`. + - A feature-local `DisconnectedOverlay` uses a controlled Fluent `Dialog` to dim the webview + and show the host-provided reason in the center. Show **Close view** and at most one supported + repair action (decision 0016). Focus stays in the dialog; Escape and backdrop clicks do not + dismiss it or close the view. - It shows when a procedure returns `unavailable`, or when the host's `disable(reason)` sends its one message to the panel over the existing webview channel. - Put it in the shared webview components folder, and run the detecting-accessibility-issues skill on it. 2. **Disabling.** - - While the banner shows, every action that talks to the server is disabled: run query, paging, + - While the overlay shows, every action that talks to the server is disabled: run query, paging, refresh, save, delete, insert, index actions, Query Insights stages and AI calls. - - Editors stay **editable**. The user can keep typing. - - A response that arrives while the banner shows is ignored. + - The underlying view is inert. Editors stay mounted and retain their contents and dirty state. + - A response that arrives while the overlay shows is ignored. - **A reply never overwrites a newer edit.** The Document View applies a save or load reply to the editor only if the editor content has not changed since the request was sent; otherwise it keeps the edit and stays dirty. Today's save handler (`documentView.tsx`) replaces the content and clears `isDirty` @@ -1471,15 +1473,13 @@ approved plan allows; the webview half then stacks on the host half without wait - **Document View:** the dirty editor content and `isDirty`. - **Dashboard:** the last data (WI-8 stops the polling). 4. **Actions.** - - **Reconnect** (same fingerprint): clear the latch if one is set, and resolve again. On success, - remove the banner and re-enable the actions; the live region announces "Reconnected". The query is - not run automatically, and there is **no** "out of date" notice (decision 0010; see #1106). After a - Disconnect the credentials are still cached (0011), so this is silent. - - **Reconnect after an identity change:** an explicit rebind to the new fingerprint, then show "Now - connected as {label}" (OT-3). - - **Sign in again:** the WI-5 command. - - **Update credentials:** the existing command. - - **Close:** dispose the panel. + - **Retry:** resolve only the original fingerprint, silently and without clearing a latch. + After a same-identity repair in the tree, recovery removes the overlay without replaying the + failed operation. The live region announces "Reconnected"; there is no out-of-date notice + (decision 0010; see #1106). Sign-in and credential changes stay in the tree. + - **Close view:** the only action after an identity change or removal. Reopen from the tree + to use a different identity. A dirty Document View warns that closing discards unsaved + changes; do not open a second prompt (decision 0017). 5. **L2-dev scenarios** (`scenarios.ts` and `fixtures.ts`): - `collectionView/disconnected-signInRequired`: query text kept, Run disabled, no host calls when Run is clicked; @@ -1503,7 +1503,7 @@ behave as today. - `ClusterSession` no longer stores a client (a type-level or structural test); - a stale result is dropped before any host-side mutation, including a reply that started before a Disconnect and arrives after a Reconnect as the same user; -- the webview ignores a response that arrives while the banner shows; +- the webview ignores a response that arrives while the overlay shows; - one submission for a write whose reply is lost; - an import started from Collection View as identity A, with its file picker left open while the cluster moves to B, writes nothing until the user starts it again; @@ -1517,6 +1517,64 @@ behave as today. **Progress:** +- **Host foundation:** Started PR5 from verified PR4 `d422d065b` while the independent + packaged-worker smoke test is pending. Added the disposable, cluster-scoped registry. + The bound resolver permits a new generation of the same identity and refuses to start + or use a client for a changed identity. `runWithClient` uses that resolver and reports + startup credential rejection without submitting the operation (PR4 review N1). Build and + 86 focused tests passed. +- **Collection View host slice:** `ClusterSession` holds a binding instead of a client. + Collection View, Query Insights, and the index advisor resolve the client per operation. + Check the epoch, latch, and identity before applying results to session caches. Build + and 193 focused tests passed. Procedure response shapes are unchanged for now; structured + unavailable results and the remaining panels are subsequent WI-6 slices. +- **Webview design decision:** After the advisor's banner draft, the operator chose the + full-view disabled overlay in [decision 0016](../decisions.md#0016-keep-disconnected-webviews-open-under-a-full-view-overlay). + It keeps the content mounted and inert, uses a polite announcement, and shows only Close + when there is no supported repair. The shared component builds and passed its focused + test; panels are not yet wired. Keep both planned stale-reply browser scenarios. +- **Document View and Dashboard host slice:** Both capture their binding on the host. + Document reads and saves resolve per operation, and a stale save cannot update the tab + title or show confirmation. Dashboard database calls use the binding; forwarded commands + check it before dispatch. Build and 35 focused host and overlay tests passed together. +- **Document View overlay:** The panel receives structured unavailable replies or a typed + disable message. It stays open with the draft intact and offers explicit Close and supported + repairs. Dismissing sign-in does not report recovery; a different account requires an explicit + rebind. A stale Reconnect cannot clear a Remove latch. Build and 26 focused tests passed. + The default, dirty-disconnect, and stale-save-after-reconnect scenarios passed in dark, + light, and high-contrast themes. The two recovery scenarios each sent one save and no + automatic replay. +- **Dashboard overlay:** Added structured unavailable replies, registration, and explicit + recovery. The disabled view keeps its last inventory and filter, and does not submit + automatic requests while the overlay is visible. The build, 118 focused view tests, and + 66 browser harness tests passed. Default and disconnected Dashboard scenarios passed in + dark, light, and high-contrast themes. Next: Collection View recovery and bound handoffs. +- **Transfer command guard:** Import and export can receive the Collection View's host-only + binding. After the file picker, they resolve that identity before opening a stream or writing. + A bound import keeps its original client for every batch; tree-originated transfers keep their + existing behavior. The build and 91 focused tests passed, including an identity change while + the import picker is open. Collection View command forwarding and WI-7 task leases are separate. +- **Collection View overlay:** Documents, Indexes and Query Insights share the view's connection + binding. The view preserves its query and applied results, returns typed unavailable responses, + and forwards the initiating binding to imports and exports. The sign-in and late-page browser + scenarios passed in all three themes before the dialog refinement. After adopting Fluent Dialog, + all eight dark-theme scenarios for Collection View, Document View and Dashboard passed. + The dialog uses **Disconnected** for an explicit disconnect, **Connection lost** for an + unreachable connection, and **Close view** for explicit disposal. +- **Final recovery design:** Decision 0017 supersedes the earlier in-view repair and rebind + experiments. The operator approved a short status title, separate next-step text, and + **Retry** beside **Close view** in an interactive Collection View preview on 2026-11-24. + Credential repair stays in the tree; Retry keeps the original identity and never resubmits an + operation. The dirty Document View warning stays in the dialog, without another prompt. +- **OP-4 partial live evidence (`1.1.1-alpha.2`):** The operator switched between Entra and invalid + username/password credentials rather than testing two valid Native users. They saw Dashboard + move from Retry/Close view to Close view only as the identity change was recognized. Collection + View went directly to Close view only on the next query. +- **OP-4 cleared (`1.1.1-alpha.3`, 2026-11-24):** The operator reported that silent Entra renewal + passed and explicitly lifted the gate without running the same-user password-only rotation test. + The earlier authentication-change result is accepted as the identity-guard evidence. + OP-5 still covers **Keep open (disabled)** and the pushed disable notification. + --- ## WI-7: Teardown, Disconnect, Remove and Update Credentials (PR 6) @@ -1590,8 +1648,8 @@ behave as today. worker. **Playground:** stop the worker. The latch keeps both from respawning (F-15). 4. Close the client (`deleteClient`). Clear the Entra failure registry and `SchemaStore.clearCluster`. Clear the `CredentialCache` entry and `lastVerifiedIdentity` **only** when `dropCredentials` is - set (Remove). Disconnect keeps both (A3, decision 0011), so Connect and a tab's Reconnect are - silent and pinned to the same identity. + set (Remove). Disconnect keeps both (A3, decision 0011), so tree Connect and then tab Retry + can reuse the same identity. 5. Refresh the tree (T-2). - **Never touched:** VS Code auth sessions, the managed identity cache, the ARM cache. - **Keys:** every store keeps its current `clusterId` matching. Provider-specific equality is out of @@ -1612,7 +1670,8 @@ behave as today. - Follow [settings/README.md](../../settings/README.md) for the group, `order` and the ID naming rules. If an existing group fits better than `connections`, use it and record the final ID in Progress. - - The same choice applies to Remove Connection and to identity-changing credential updates. + - The same choice applies to Remove Connection. Saved connection edits keep old views open + and locked without asking for a tab choice (decision 0018). - 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. @@ -1626,27 +1685,19 @@ behave as today. folder, its connections, panels, drafts and shells intact. Descendants without a client or open surface still get their `CredentialCache` entry and schema cleared, as Remove does. 5. **Update Credentials and Update Connection String.** - - Compute the **new** fingerprint from the wizard context before saving. - - **Make save success explicit** (F-19): the execute step must report whether the save succeeded, for - example with a flag on the wizard context. Today it catches failures and returns normally. - - **Same fingerprint:** save. Only after a confirmed success, call `invalidate` and replace the client - with a new generation; surfaces continue. - - **Different fingerprint:** - 1. `confirmTeardown` **before** saving. - 2. `latchForTeardown` **before** saving. On a conflict, stop: nothing is saved. Now no import, task or - connect can start while the save runs. - 3. Save. - 4. **Storage decides, not the success flag** (F-21). Re-read the stored connection and compute its - fingerprint: - - it differs from the live binding (a full save, **or** a partial one where the secrets were - written): `commitTeardown` with reason `credentialsChanged` and `dropCredentials: false`, so what - is stored is what the next connect uses. `lastVerifiedIdentity` is replaced on the next successful - connect. If the save reported a failure, also tell the user the change may be incomplete and offer - Update Credentials; - - it equals the live binding (nothing reached storage): clear the latch. The old binding stays - usable, and the user is told the save failed. - - The latch and the `invalidate` call make sure a concurrent connect cannot publish the old credentials - after the change. + - Follow decision 0018: do not classify edits into same- and different-fingerprint recovery + flows or ask whether to close tabs. Check for task conflicts, fence new operations while + persisting the edit, and make the save result explicit (F-19). + - **Storage decides, not the success flag** (F-21). Compare the relevant before/after stored + connection settings in memory, including credentials; never log or persist the comparison. + If storage is unchanged, release the save fence without retiring the old views. Preserve + existing failure reporting for a failed save. + - If storage changed, retire the old bindings, invalidate the old client and cached settings, + and push `credentialsChanged` to the affected views. They keep their contents but cannot + Retry; new views use the saved settings. If the save reported a failure, warn that the + change may be incomplete. Fence concurrent startup so it cannot publish the old credentials. + - Keep the existing identity checks for other sources of change. Silent token renewal, a + same-account sign-in and reconnect with unchanged settings do not retire old bindings. - Add a **Disconnect** button to the D12 modal for open shells. 6. **Telemetry.** - One `connection.disconnect` event with `source` (`command`, `remove`, `credentialsChanged`), @@ -1660,7 +1711,7 @@ behave as today. cluster is not blocked; Disconnect succeeds once the task is done or stopped; - a token response that arrives after Disconnect is ignored; - Reconnect uses the current credentials and cloud settings; -- after Disconnect, a tab's Reconnect and the tree's Connect succeed without the tree reloading +- after Disconnect, tree Connect followed by tab Retry succeeds without the tree reloading credentials and without a prompt (native, Entra and discovery with a typed password); after Remove, the `CredentialCache` entry and `lastVerifiedIdentity` are gone; - Remove reuses the same teardown; @@ -1673,6 +1724,8 @@ behave as today. - an import attempted while Update Credentials is saving is refused with the latch's reason, and nothing is half-applied; - a save that fails before any write keeps the old binding and clears the latch; +- a cancelled or identical edit keeps old views usable; a saved password-only edit permanently + locks existing views with their contents kept and no tab-choice prompt; - a save whose metadata write fails after the secret write ends in teardown under `credentialsChanged`, never in a split state (old client, new stored secrets); - deleting a folder with a connected child that has a dirty Document View and a live shell: cancelling @@ -1692,7 +1745,7 @@ behave as today. ## WI-8: Cluster Dashboard health polling (PR 6) -**Outcome:** the poll stops when the cluster is unavailable, shows the banner, and resumes with exactly +**Outcome:** the poll stops when the cluster is unavailable, shows the overlay, and resumes with exactly one loop. **Steps:** @@ -1703,18 +1756,18 @@ 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 banner state: it stops on `unavailable` or on a `disable` +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. -3. A ping that resolves while the banner shows is ignored (the WI-6 webview rule), so it cannot clear the - banner. +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 leave them to #1091. **Tests** (fake timers): - no client lookups on ticks or on reveal after Disconnect; -- a late success does not clear the banner; +- a late success does not clear the overlay; - reconnecting starts exactly one loop; - `signInRequired` and `credentialsRejected` stop the loop after one tick, including when they happen **inside** the sampler's ping with the tree untouched; diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md index c83e4ecc2..d96539af2 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md @@ -384,10 +384,11 @@ The largest item. Host side first, then each view. internally; test one application submission when the server accepts a write but its reply is lost. - **Webviews:** - - Push one connection-state channel per view over tRPC: connected, reconnecting, or disconnected - with a reason. Follow the webview-trpc-messaging and react-webview-architecture skills. - - Disconnected disables every action that talks to the server and shows a banner with the reason - and one action: Reconnect, Sign in again, Update credentials, or Close. + - Return unavailable results from operations and use the existing webview message channel for + teardown. Do not add a connection-state subscription (decision 0012). + - Disconnected dims the entire webview, disables the underlying content, and shows the reason + with **Close view** and **Retry** where safe. Credential repair stays in the tree; the tab + never closes automatically (decisions 0016 and 0017). - It **keeps** the editor contents, filter, sort, projection, page position and unsaved document edits. - Views: Collection View (query, documents, indexes and Query Insights tabs), Document View @@ -399,7 +400,7 @@ The largest item. Host side first, then each view. is not permission to restart a transfer under another identity. - **Tests:** - router tests for the three binding outcomes; - - a Collection View scenario: disconnected banner with the query text kept; + - a Collection View scenario: disconnected overlay with the query text kept; - a Document View scenario: dirty edit kept; - inject a disconnect after typing, then deliver a stale page or document read; neither applied results nor drafts may be overwritten, and disabled actions must issue no server calls; @@ -460,12 +461,12 @@ Coordinate with #1091. The minimum for this plan: - the poll uses the WI-6 binding; - after a `signInRequired`, `credentialsRejected` or disconnected outcome, polling **stops** and the - dashboard shows the WI-6 banner instead of starting a connection every 5 s. + dashboard shows the WI-6 overlay instead of starting a connection every 5 s. Visibility pause and backoff are the rest of #1091 and may ship separately. Existing visibility and in-flight guards do not distinguish a missing ping sample from terminal auth failure. With fake timers, verify no client lookups on ticks or reveal after Disconnect, -that a late successful ping cannot clear the banner, and that reconnect starts only one poll loop. +that a late successful ping cannot clear the overlay, and that reconnect starts only one poll loop. ## WI-9: Measure token renewal and recovery after release @@ -542,15 +543,15 @@ only), so it is not tested. optional WI-4 test hook may shorten this during development. The release check uses a real wait at least once. -| # | Scenario | Steps | Pass when | -| ---- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| OT-1 | **Entra, long idle, work open** | Connect with Entra. Open a Collection View with filter, sort and projection, on page 2. Open a Document View with an unsaved edit. Open the Cluster Dashboard and a shell. Wait ≥ 2 h. Then refresh the tree, run the query, go to the next page, save the document, and run a command in the shell. | Everything works. No sign-in prompt, and no error that needs a click. Text and edits are kept. (No re-run and no out-of-date notice: decision 0010.) | -| OT-2 | **Entra, silent renewal impossible** | With the OT-1 surfaces open, sign out of the account in the Accounts menu (or revoke sessions in Entra). Run the query. Dismiss the prompt if one appears. Wait 5 min. Then click **Sign in again** and pick the same account. | The action fails once and offers **Sign in again**. The tabs show "sign-in expired" with their content kept. No modal appears on its own, and nothing prompts again after a dismissal. After signing in, the tabs re-enable and the unsaved edit saves. | -| OT-3 | **Identity change is never silent** | (a) Native: with tabs open, use Update Credentials to switch to a different user. Choose "Keep open (disabled)". (b) Repeat, changing only the password of the same user. (c) Entra: in OT-2, sign in again with a _different_ account. | (a) and (c): tabs are disabled with "credentials changed", no action runs under the new identity, and Reconnect opens a new session and says so. (b): tabs continue. | -| OT-4 | **Native, idle and network drop** | Native connection with tabs open. Turn the network off for 2 min, or put the machine to sleep for ≥ 30 min, then restore it. Run a query, refresh the tree, save a document. Also try an insert while offline. | The operations work after restoring, at most after one Retry. The offline insert is reported as failed or unknown and is **not** replayed. | -| OT-5 | **RU (key), idle and key rotation** | Open the RU cluster through Discovery, with tabs open. Wait ≥ 2 h and run a query. Then regenerate the primary key in the portal and run a query again. | After the wait: it works. After rotation: one clear failure with an action. The action reconnects with the new key. No endless retry. | -| OT-6 | **Azure discovery, long idle** | Expand a subscription in vCore and RU Discovery. Wait ≥ 2 h. Expand a cluster, connect, and run **Diagnose connection**. Then sign out of Azure and run Diagnose again. | It works without refreshing the provider root. When signed out, the diagnosis says **"Azure sign-in needed"**, not "Azure details unavailable". | -| OT-7 | **Disconnect** | With a Collection View, a dirty Document View, a shell and a playground open: Disconnect and choose **Keep open (disabled)**, then use Reconnect from a tab. Repeat with **Close all**. Then use Remove Connection. | Keep open: disabled with the reason, content kept, and Reconnect resumes. Close all: the dirty editor asks before it closes. The shell prints "Disconnected". The node collapses, and the next expand connects again. Remove behaves like Disconnect plus delete. | +| # | Scenario | Steps | Pass when | +| ---- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| OT-1 | **Entra, long idle, work open** | Connect with Entra. Open a Collection View with filter, sort and projection, on page 2. Open a Document View with an unsaved edit. Open the Cluster Dashboard and a shell. Wait ≥ 2 h. Then refresh the tree, run the query, go to the next page, save the document, and run a command in the shell. | Everything works. No sign-in prompt, and no error that needs a click. Text and edits are kept. (No re-run and no out-of-date notice: decision 0010.) | +| OT-2 | **Entra, silent renewal impossible** | With the OT-1 surfaces open, sign out of the account in the Accounts menu (or revoke sessions in Entra). Run the query. Dismiss the prompt if one appears. Wait 5 min. Then click **Sign in again** and pick the same account. | The action fails once and offers **Sign in again**. The tabs show "sign-in expired" with their content kept. No modal appears on its own, and nothing prompts again after a dismissal. After signing in, the tabs re-enable and the unsaved edit saves. | +| OT-3 | **Changed connection details** | (a) With a Native tab open, save a different user through Update Credentials. (b) Repeat with a password-only change for the same user. (c) Entra: in OT-2, sign in again with a different account. OP-5 checks the pushed lock on saved edits (decision 0018). | (a) and (b): no tab-choice prompt; the old view immediately offers **Close view** only, with contents still copyable. (c): the old tab cannot run under the new account. Open a new view from the tree. | +| OT-4 | **Native, idle and network drop** | Native connection with tabs open. Turn the network off for 2 min, or put the machine to sleep for ≥ 30 min, then restore it. Run a query, refresh the tree, save a document. Also try an insert while offline. | The operations work after restoring, at most after one Retry. The offline insert is reported as failed or unknown and is **not** replayed. | +| OT-5 | **RU (key), idle and key rotation** | Open the RU cluster through Discovery, with tabs open. Wait ≥ 2 h and run a query. Then regenerate the primary key in the portal and run a query again. | After the wait: it works. After rotation: one clear failure with an action. The action reconnects with the new key. No endless retry. | +| OT-6 | **Azure discovery, long idle** | Expand a subscription in vCore and RU Discovery. Wait ≥ 2 h. Expand a cluster, connect, and run **Diagnose connection**. Then sign out of Azure and run Diagnose again. | It works without refreshing the provider root. When signed out, the diagnosis says **"Azure sign-in needed"**, not "Azure details unavailable". | +| OT-7 | **Disconnect** | With a Collection View, a dirty Document View, a shell and a playground open: Disconnect and choose **Keep open (disabled)**. Reconnect in the tree, then click **Retry** in the tab. Repeat with **Close all**. Then use Remove Connection. | Keep open: disabled with the reason and content kept; Retry resumes only after tree reconnect with the same identity. Close all: the dirty editor asks before it closes. The shell prints "Disconnected". The refreshed node offers **Connect**. Remove behaves like Disconnect plus delete. | **After release** (telemetry, operator with Kusto access): run the WI-9 queries on the pre-release cohort. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr5-bound-surfaces-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr5-bound-surfaces-review.md new file mode 100644 index 000000000..2006573f4 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr5-bound-surfaces-review.md @@ -0,0 +1,73 @@ +--- +feature: connection-lifecycle +kind: review +status: active +created: 2026-11-24 +--- + +# PR5 pre-review: identity-bound views + +[PR #1121](https://github.com/microsoft/vscode-documentdb/pull/1121), reviewed at +`98530222e` against `feature/connection-lifecycle`. Claude Opus 5.5 performed the initial +review. A second review validated the findings and performed an independent sweep. No +published GitHub review was present. The later lint and formatting cleanup is separate. + +## Validated findings + +| ID | Severity | Finding and recommendation | +| --- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| F1 | High | Dashboard row commands can continue after their initial identity check without the originating binding. Bind Dashboard Import, Export and Delete at the point of database access, while keeping tree commands unchanged. For Paste, either carry the binding through the entire Dashboard destination flow, including index copy, or keep Paste available only from the tree until the Dashboard path can be fully bound. Do not retain a partially guarded Dashboard Paste. [Dashboard dispatch](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L249) | +| F2 | Medium | An interrupted initial collections read can render as an empty database. Distinguish **not loaded** from **loaded and empty**. Preserve existing rows and let an explicit Refresh load missing data after recovery. Block a new drill-in while the copy escape hatch is active. [Collections state](../../../../../src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.ts#L113) | +| F3 | Medium | An interrupted index create can leave a phantom **Creating…** row and keep status polling active. Remove only the affected optimistic entry, preserve the last verified list, and leave an unacknowledged operation's outcome unknown until an explicit refresh. [Index creation](../../../../../src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx#L469) | +| F4 | Medium | Interrupted Query Insights stages 1 and 2 can stay in a loading state. Stop the incomplete stage, retain any completed analysis, and require an explicit Run or Refresh. Resetting to idle could start a background fetch. [Collection View prefetch](../../../../../src/webviews/documentdb/collectionView/CollectionView.tsx#L257) and [Query Insights](../../../../../src/webviews/documentdb/collectionView/queryInsightsTab/QueryInsightsTab.tsx#L329) | +| N1 | Medium | The Dashboard native row menu does not honor the panel's copy-only state. Apply the same availability rule to native dispatch as to the webview: copying existing content stays possible, but database actions stay blocked until Retry succeeds. [Native menu dispatch](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L249) | +| N2 | Medium | Dashboard create wizards perform name-validation reads without the panel's binding. Carry the host-only binding through validation and execution. Report a connection or identity failure as unavailable, not an invalid name. [Database validation](../../../../../src/commands/createDatabase/DatabaseNameStep.ts#L59) and [collection validation](../../../../../src/commands/createCollection/CollectionNameStep.ts#L63) | + +The second review found no separate defect in the native **Close view** confirmation. Index-list +loading and delete/hide busy flags have their own cleanup and do not need the F3 change. + +## Author decisions + +The operator approved fixes for F1–F4 and N1–N2, asking for the simplest changes that preserve +the identity guard and avoid operation replay. In F1, keep Paste Collection available from the +tree only; a Dashboard entry would need to bind the full copy flow, including optional index +copy. No change to ordinary tree commands is intended. + +After consulting Opus, the operator approved permanently locking existing views after saved +connection edits, including password-only changes, in WI-7. See [decision 0018](../decisions.md#0018-saved-connection-edits-permanently-lock-existing-views). +That policy simplifies later recovery; it does not replace the PR5 command guards. +OP-4 remains cleared. + +## Fixes and verification + +- **F1, N1, N2:** `5975620a2` binds Dashboard commands and wizard validation, leaves Paste in + the tree, and reopens the unavailable dialog instead of running blocked native row actions. +- **F2:** `e2fe7afa4` distinguishes interrupted inventory from loaded, empty inventory. +- **F3:** `9cc97ffd1` clears unacknowledged index creation placeholders without replay. +- **F4:** `20df3fe4c` stops interrupted Query Insights stages and preserves completed results. + +Case 2: formatting and localization regeneration completed; localization check, lint, build, +strict workspace test type-check, full Vitest (442 files, 9,863 passed, one skipped), and VSIX +packaging passed. The final native-menu notification adjustment received an additional focused +controller run (18 passed), lint, build, and packaging. OP-4 live evidence and the operator's +password-only test waiver are recorded in the [delivery plan](./01-dev-plan.md). + +## Copilot inline review follow-up + +Claude Opus 5.5 validated the 21 original threads at `c19d0c1d5`. The operator asked +for the smallest safe fixes and to skip low-priority work unless the fix is +straightforward. The operator approved [decision 0019](../decisions.md#0019-require-a-new-dashboard-delete-after-disconnect) +for pending Dashboard deletes and keeping Dashboard Copy with tree-only Paste. + +- **Fixed:** R1 (pending Delete), R4 (acknowledged document ID), R5 (drop errors), + R7–R9 (bound imports, optional stats and transfer startup), R11 (duplicate + notification), and R13–R20 (Dashboard recovery, interrupted reads, and Collection + View and Query Insights guards). Each has a dedicated commit and an inline reply. +- **No code change:** R2 (rare new-tab handoff), R3 (approved tree-reference copy), + R6 (export stream fallback), R10 (unchanged Native rejection policy), + R12 (transparent same-identity replacement), R21 (Stage 1 plan presentation). + These decisions do not change the PR6 saved-edit lock. + +Follow-up verification: Case 1 build passed and 307 focused tests passed across +25 files. The full Case 2 suite above was run for the earlier review handoff, not +repeated for this follow-up. diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 3d79e848e..1bc9cabc6 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -494,6 +494,7 @@ "Authentication data (primary connection string) is missing for \"{cluster}\".": "Authentication data (primary connection string) is missing for \"{cluster}\".", "Authentication data (properties.connectionString) is missing for \"{cluster}\".": "Authentication data (properties.connectionString) is missing for \"{cluster}\".", "Authentication database": "Authentication database", + "Authentication failed": "Authentication failed", "Authentication failed (401 Unauthorized)": "Authentication failed (401 Unauthorized)", "Authentication failed listing services (401)": "Authentication failed listing services (401)", "Authentication failed: {0}": "Authentication failed: {0}", @@ -650,6 +651,7 @@ "Check the kubeconfig source and context, then run the diagnosis again.": "Check the kubeconfig source and context, then run the diagnosis again.", "Check the local database, container or tunnel on this computer, then run the diagnosis again.": "Check the local database, container or tunnel on this computer, then run the diagnosis again.", "Check the network connection and proxy settings, then run the diagnosis again.": "Check the network connection and proxy settings, then run the diagnosis again.", + "Check the network or server, then click Retry.": "Check the network or server, then click Retry.", "Check the option values in the connection string, such as true or false for switches and numbers for timeouts, then connect again.": "Check the option values in the connection string, such as true or false for switches and numbers for timeouts, then connect again.", "Check the output channel for details.": "Check the output channel for details.", "Check the output channel for details. The cluster may be unreachable or your credentials may need updating.": "Check the output channel for details. The cluster may be unreachable or your credentials may need updating.", @@ -723,6 +725,9 @@ "Clock offset": "Clock offset", "Close": "Close", "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 this view discards unsaved changes.": "Closing this view discards unsaved changes.", "Closing…": "Closing…", "Cluster": "Cluster", "Cluster actions": "Cluster actions", @@ -799,6 +804,7 @@ "Connect": "Connect", "Connect another API Key or Service Account to see more organizations and projects.": "Connect another API Key or Service Account to see more organizations and projects.", "Connect database": "Connect database", + "Connect from the connection tree, then click Retry.": "Connect from the connection tree, then click Retry.", "Connect MongoDB Atlas to browse, open, and manage your clusters without leaving VS Code.": "Connect MongoDB Atlas to browse, open, and manage your clusters without leaving VS Code.", "Connect this playground to a database": "Connect this playground to a database", "Connect to a different database…": "Connect to a different database…", @@ -828,6 +834,7 @@ "Connection": "Connection", "connection \"{0}\"": "connection \"{0}\"", "Connection attempt failed": "Connection attempt failed", + "Connection changed": "Connection changed", "Connection checks": "Connection checks", "Connection configuration": "Connection configuration", "Connection details unavailable": "Connection details unavailable", @@ -839,6 +846,7 @@ "Connection failed": "Connection failed", "Connection failed at {0}": "Connection failed at {0}", "Connection failed: {0}": "Connection failed: {0}", + "Connection lost": "Connection lost", "Connection mode": "Connection mode", "Connection not found": "Connection not found", "Connection not tested": "Connection not tested", @@ -846,6 +854,7 @@ "Connection options rejected": "Connection options rejected", "Connection preparation failed": "Connection preparation failed", "Connection refused": "Connection refused", + "Connection removed": "Connection removed", "Connection settings": "Connection settings", "Connection status based on periodic ping commands to this cluster.": "Connection status based on periodic ping commands to this cluster.", "Connection string": "Connection string", @@ -1108,6 +1117,8 @@ "Discovery view": "Discovery view", "DiskANN": "DiskANN", "Dismiss": "Dismiss", + "Dismiss dialog to copy view contents": "Dismiss dialog to copy view contents", + "Dismiss the connection dialog instead if you need to copy anything from the view.": "Dismiss the connection dialog instead if you need to copy anything from the view.", "Dissatisfied": "Dissatisfied", "DNS connection options invalid": "DNS connection options invalid", "DNS lookup temporarily failed": "DNS lookup temporarily failed", @@ -2423,6 +2434,7 @@ "Recommended": "Recommended", "Recommended Index": "Recommended Index", "Reconnect now with the updated credentials": "Reconnect now with the updated credentials", + "Reconnected": "Reconnected", "Reconnecting...": "Reconnecting...", "Recovery command copied.": "Recovery command copied.", "Recreate container": "Recreate container", @@ -2473,6 +2485,7 @@ "Rename kubeconfig source": "Rename kubeconfig source", "Rename Kubernetes context": "Rename Kubernetes context", "Renamed folder from \"{oldName}\" to \"{newName}\"": "Renamed folder from \"{oldName}\" to \"{newName}\"", + "Repair the connection in the tree, then click Retry.": "Repair the connection in the tree, then click Retry.", "Repairing…": "Repairing…", "Replaced, Start fresh": "Replaced, Start fresh", "Replica set": "Replica set", @@ -2724,6 +2737,7 @@ "Sign in": "Sign in", "Sign in again to continue using Microsoft Entra ID.": "Sign in again to continue using Microsoft Entra ID.", "Sign in again to continue using this connection.": "Sign in again to continue using this connection.", + "Sign in from the connection tree, then click Retry.": "Sign in from the connection tree, then click Retry.", "Sign in to": "Sign in to", "Sign in to additional accounts or authenticate with other tenants to see more options.": "Sign in to additional accounts or authenticate with other tenants to see more options.", "Sign in to additional accounts or authenticate with other tenants to see more subscriptions.": "Sign in to additional accounts or authenticate with other tenants to see more subscriptions.", @@ -2750,6 +2764,7 @@ "Sign-in failed in {cloud}. If the sign-in window showed AADSTS65002 (\"must be configured via preauthorization\"), Microsoft Entra ID sign-in for Azure DocumentDB is not enabled yet for VS Code in this cloud. Only Microsoft can change this, not you or your tenant administrator. Use Username and Password authentication or managed identity on an Azure VM as a workaround, and report this on GitHub. See {link}": "Sign-in failed in {cloud}. If the sign-in window showed AADSTS65002 (\"must be configured via preauthorization\"), Microsoft Entra ID sign-in for Azure DocumentDB is not enabled yet for VS Code in this cloud. Only Microsoft can change this, not you or your tenant administrator. Use Username and Password authentication or managed identity on an Azure VM as a workaround, and report this on GitHub. See {link}", "Sign-in needed": "Sign-in needed", "Sign-in not tested": "Sign-in not tested", + "Sign-in required": "Sign-in required", "Sign-in required to use this connection": "Sign-in required to use this connection", "Sign-in resource unavailable": "Sign-in resource unavailable", "Sign-in set to {0}": "Sign-in set to {0}", @@ -3223,6 +3238,7 @@ "This ClusterIP service requires port-forwarding. Confirm or change the local port to forward to {0}/{1}:{2}.": "This ClusterIP service requires port-forwarding. Confirm or change the local port to forward to {0}/{1}:{2}.", "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 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:", @@ -3281,6 +3297,7 @@ "This step did not finish within the time limit. This alone does not show that the server is unreachable.": "This step did not finish within the time limit. This alone does not show that the server is unreachable.", "This stops all running WSL distributions so the new group membership applies when WSL starts again.": "This stops all running WSL distributions so the new group membership applies when WSL starts again.", "This table view presents data at the root level by default.": "This table view presents data at the root level by default.", + "This view is tied to the previous connection. Close it and reopen it from the tree.": "This view is tied to the previous connection. Close it and reopen it from the tree.", "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround could not read it either.": "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround could not read it either.", "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround is turned off.": "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround is turned off.", "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), so the extension read it another way. Nothing needs to change.": "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), so the extension read it another way. Nothing needs to change.", @@ -3339,10 +3356,12 @@ "Type \"it\" for more": "Type \"it\" for more", "Type a username that is not in this list": "Type a username that is not in this list", "TypeScript-powered completions are unavailable on this read-only extension install. Click to retry.": "TypeScript-powered completions are unavailable on this read-only extension install. Click to retry.", + "Unable to confirm closing the view. Try again.": "Unable to confirm closing the view. Try again.", "Unable to connect to the local database instance. Make sure it is started correctly. See {link} for tips.": "Unable to connect to the local database instance. Make sure it is started correctly. See {link} for tips.", "Unable to connect to the local instance. Make sure it is started correctly. See {link} for tips.": "Unable to connect to the local instance. Make sure it is started correctly. See {link} for tips.", "Unable to load tenants. See the DocumentDB output for details.": "Unable to load tenants. See the DocumentDB output for details.", "Unable to parse the document _id. See the output channel for details.": "Unable to parse the document _id. See the output channel for details.", + "Unable to recover the connection": "Unable to recover the connection", "Unable to retrieve credentials for cluster \"{cluster}\".": "Unable to retrieve credentials for cluster \"{cluster}\".", "Unable to retrieve credentials for the selected cluster.": "Unable to retrieve credentials for the selected cluster.", "Uncertainty": "Uncertainty", diff --git a/package-lock.json b/package-lock.json index a2ea6de7a..bc2a628de 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.1", + "version": "1.1.1-alpha.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vscode-documentdb", - "version": "1.1.1-alpha.1", + "version": "1.1.1-alpha.3", "license": "SEE LICENSE IN LICENSE.md", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index eec16dff8..2a21ff0bb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.1", + "version": "1.1.1-alpha.3", "releaseNotesUrl": "https://github.com/microsoft/vscode-documentdb/discussions/1089", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "publisher": "ms-azuretools", @@ -797,10 +797,6 @@ "command": "vscode-documentdb.command.clusterDashboard.context.copyCollection", "title": "Copy Collection" }, - { - "command": "vscode-documentdb.command.clusterDashboard.context.pasteCollection", - "title": "Paste Collection" - }, { "command": "vscode-documentdb.command.clusterDashboard.context.exportDocuments", "title": "Export Documents" @@ -999,11 +995,6 @@ "when": "webviewId == 'vscode-documentdb-cluster-dashboard' && clusterDashboardNamespace == database", "group": "3_open@2" }, - { - "command": "vscode-documentdb.command.clusterDashboard.context.pasteCollection", - "when": "webviewId == 'vscode-documentdb-cluster-dashboard' && clusterDashboardNamespace == database", - "group": "4_transfer@1" - }, { "command": "vscode-documentdb.command.clusterDashboard.context.deleteDatabase", "when": "webviewId == 'vscode-documentdb-cluster-dashboard' && clusterDashboardNamespace == database", @@ -1039,11 +1030,6 @@ "when": "webviewId == 'vscode-documentdb-cluster-dashboard' && clusterDashboardNamespace == collection", "group": "3_transfer@1" }, - { - "command": "vscode-documentdb.command.clusterDashboard.context.pasteCollection", - "when": "webviewId == 'vscode-documentdb-cluster-dashboard' && clusterDashboardNamespace == collection", - "group": "3_transfer@2" - }, { "command": "vscode-documentdb.command.clusterDashboard.context.exportDocuments", "when": "webviewId == 'vscode-documentdb-cluster-dashboard' && clusterDashboardNamespace == collection", @@ -1633,10 +1619,6 @@ "command": "vscode-documentdb.command.clusterDashboard.context.copyCollection", "when": "never" }, - { - "command": "vscode-documentdb.command.clusterDashboard.context.pasteCollection", - "when": "never" - }, { "command": "vscode-documentdb.command.clusterDashboard.context.exportDocuments", "when": "never" diff --git a/src/commands/copyReference/copyReference.ts b/src/commands/copyReference/copyReference.ts index 39b7e74d6..2292902c7 100644 --- a/src/commands/copyReference/copyReference.ts +++ b/src/commands/copyReference/copyReference.ts @@ -57,10 +57,7 @@ function opt(label: string, value: string): CopyReferenceOption { return { id: value, label, detail: value, alwaysShow: true }; } -function getDatabaseOptions(node: DatabaseItem): CopyReferenceOption[] { - const dbName = node.databaseInfo.name; - const host = getClusterHost(node.cluster.connectionString); - +function getDatabaseOptions(dbName: string, host?: string): CopyReferenceOption[] { const options: CopyReferenceOption[] = [opt(l10n.t('Name'), dbName), opt(l10n.t('Shell Command'), `use ${dbName}`)]; if (host) { @@ -70,9 +67,7 @@ function getDatabaseOptions(node: DatabaseItem): CopyReferenceOption[] { return options; } -function getCollectionOptions(node: CollectionItem): CopyReferenceOption[] { - const dbName = node.databaseInfo.name; - const collName = node.collectionInfo.name; +function getCollectionOptions(dbName: string, collName: string): CopyReferenceOption[] { const quoted = needsQuoting(collName) || needsQuoting(dbName); const escapedCollName = escapeDoubleQuotes(collName); @@ -108,28 +103,25 @@ function getIndexOptions(node: IndexItem): CopyReferenceOption[] { return options; } -function getOptionsForNode(node: DatabaseItem | CollectionItem | IndexItem): { - title: string; - options: CopyReferenceOption[]; -} { - if (node instanceof IndexItem) { - return { - title: l10n.t('Copy Reference: {0}', node.indexInfo.name), - options: getIndexOptions(node), - }; - } - - if (node instanceof CollectionItem) { - return { - title: l10n.t('Copy Reference: {0}.{1}', node.databaseInfo.name, node.collectionInfo.name), - options: getCollectionOptions(node), - }; +export async function copyNamespaceReference( + context: IActionContext, + databaseName: string, + collectionName?: string, + host?: string, +): Promise { + if (collectionName === undefined) { + await copyReferenceOptions( + context, + l10n.t('Copy Reference: {0}', databaseName), + getDatabaseOptions(databaseName, host), + ); + } else { + await copyReferenceOptions( + context, + l10n.t('Copy Reference: {0}.{1}', databaseName, collectionName), + getCollectionOptions(databaseName, collectionName), + ); } - - return { - title: l10n.t('Copy Reference: {0}', node.databaseInfo.name), - options: getDatabaseOptions(node), - }; } export async function copyReference( @@ -140,8 +132,25 @@ export async function copyReference( throw new Error(l10n.t('No node selected.')); } - const { title, options } = getOptionsForNode(node); + if (node instanceof IndexItem) { + await copyReferenceOptions(context, l10n.t('Copy Reference: {0}', node.indexInfo.name), getIndexOptions(node)); + } else if (node instanceof CollectionItem) { + await copyNamespaceReference(context, node.databaseInfo.name, node.collectionInfo.name); + } else { + await copyNamespaceReference( + context, + node.databaseInfo.name, + undefined, + getClusterHost(node.cluster.connectionString), + ); + } +} +async function copyReferenceOptions( + context: IActionContext, + title: string, + options: CopyReferenceOption[], +): Promise { const picked = await context.ui.showQuickPick(options, { placeHolder: title, stepName: 'copyReference', diff --git a/src/commands/createCollection/CollectionNameStep.ts b/src/commands/createCollection/CollectionNameStep.ts index 1ed0210db..0406a1f91 100644 --- a/src/commands/createCollection/CollectionNameStep.ts +++ b/src/commands/createCollection/CollectionNameStep.ts @@ -6,7 +6,9 @@ import { AzureWizardPromptStep } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { ext } from '../../extensionVariables'; +import { runBoundNamespaceCommand } from '../runBoundNamespaceCommand'; import { type CreateCollectionWizardContext } from './CreateCollectionWizardContext'; export class CollectionNameStep extends AzureWizardPromptStep { @@ -71,13 +73,19 @@ export class CollectionNameStep extends AzureWizardPromptStep + client.listCollections(context.databaseId), + ) + : await (await ClustersClient.getClient(context.credentialsId)).listCollections(context.databaseId); if (collections.filter((c) => c.name === name).length > 0) { return l10n.t('The collection "{0}" already exists in the database "{1}".', name, context.databaseId); } } catch (error) { + if (context.binding && error instanceof ConnectionUnavailableError) { + throw error; + } const errorMessage = error instanceof Error ? error.message : String(error); ext.outputChannel.error(l10n.t('Error validating collection name availability: {0}', errorMessage)); return undefined; // we don't want to block the user from continuing if we can't validate the name diff --git a/src/commands/createCollection/CreateCollectionWizardContext.ts b/src/commands/createCollection/CreateCollectionWizardContext.ts index 2a3c0ab8d..6ddfc9424 100644 --- a/src/commands/createCollection/CreateCollectionWizardContext.ts +++ b/src/commands/createCollection/CreateCollectionWizardContext.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { type ConnectionBinding } from '../../documentdb/ClustersClient'; export interface CreateCollectionWizardContext extends IActionContext { /** @@ -11,6 +12,7 @@ export interface CreateCollectionWizardContext extends IActionContext { * This should be `cluster.clusterId` (NOT treeId). */ credentialsId: string; + readonly binding?: ConnectionBinding; databaseId: string; nodeId: string; diff --git a/src/commands/createCollection/ExecuteStep.ts b/src/commands/createCollection/ExecuteStep.ts index a2fb43966..315fb48cc 100644 --- a/src/commands/createCollection/ExecuteStep.ts +++ b/src/commands/createCollection/ExecuteStep.ts @@ -7,6 +7,7 @@ import { AzureWizardExecuteStep } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; +import { runBoundNamespaceCommand } from '../runBoundNamespaceCommand'; import { type CreateCollectionWizardContext } from './CreateCollectionWizardContext'; export class ExecuteStep extends AzureWizardExecuteStep { @@ -15,14 +16,20 @@ export class ExecuteStep extends AzureWizardExecuteStep { const collectionName = context.newCollectionName!; const databaseName = context.databaseId; - const client = await ClustersClient.getClient(context.credentialsId); + const client = context.binding ? undefined : await ClustersClient.getClient(context.credentialsId); return ext.state.showCreatingChild( context.nodeId, l10n.t('Creating "{nodeName}"…', { nodeName: collectionName }), async () => { await new Promise((resolve) => setTimeout(resolve, 250)); - await client.createCollection(databaseName, collectionName); + if (context.binding) { + await runBoundNamespaceCommand(context.credentialsId, context.binding, (boundClient) => + boundClient.createCollection(databaseName, collectionName), + ); + } else { + await client?.createCollection(databaseName, collectionName); + } }, ); } diff --git a/src/commands/createCollection/createCollection.ts b/src/commands/createCollection/createCollection.ts index 438167b50..62daa5ab7 100644 --- a/src/commands/createCollection/createCollection.ts +++ b/src/commands/createCollection/createCollection.ts @@ -5,9 +5,11 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; +import { type ConnectionBinding } from '../../documentdb/ClustersClient'; import { type DatabaseItem } from '../../tree/documentdb/DatabaseItem'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { nonNullValue } from '../../utils/nonNull'; +import { rethrowBoundCommandUnavailable } from '../rethrowBoundCommandUnavailable'; import { CollectionNameStep } from './CollectionNameStep'; import { type CreateCollectionWizardContext } from './CreateCollectionWizardContext'; import { ExecuteStep } from './ExecuteStep'; @@ -18,6 +20,7 @@ interface CreateCollectionCommandOptions { * `treeEmptyPlaceholder`, `clusterDashboard:emptyState`. */ readonly activationSource?: string; + readonly binding?: ConnectionBinding; readonly onNameResolved?: (collectionName: string) => Promise; } @@ -38,6 +41,7 @@ export async function createCollection( const wizardContext: CreateCollectionWizardContext = { ...context, credentialsId: node.cluster.clusterId, + binding: options?.binding, databaseId: node.databaseInfo.name, nodeId: node.id, }; @@ -49,16 +53,23 @@ export async function createCollection( showLoadingPrompt: true, }); - await wizard.prompt(); - const newCollectionName = nonNullValue( - wizardContext.newCollectionName, - 'wizardContext.newCollectionName', - 'createCollection.ts', - ); - await options?.onNameResolved?.(newCollectionName); - await wizard.execute(); + try { + await wizard.prompt(); + const newCollectionName = nonNullValue( + wizardContext.newCollectionName, + 'wizardContext.newCollectionName', + 'createCollection.ts', + ); + await options?.onNameResolved?.(newCollectionName); + await wizard.execute(); - showConfirmationAsInSettings( - l10n.t('The "{newCollectionName}" collection has been created.', { newCollectionName }), - ); + showConfirmationAsInSettings( + l10n.t('The "{newCollectionName}" collection has been created.', { newCollectionName }), + ); + } catch (error) { + if (options?.binding) { + rethrowBoundCommandUnavailable(context, error); + } + throw error; + } } diff --git a/src/commands/createDatabase/CreateDatabaseWizardContext.ts b/src/commands/createDatabase/CreateDatabaseWizardContext.ts index e531b280b..f512e0e5c 100644 --- a/src/commands/createDatabase/CreateDatabaseWizardContext.ts +++ b/src/commands/createDatabase/CreateDatabaseWizardContext.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { type ConnectionBinding } from '../../documentdb/ClustersClient'; export interface CreateDatabaseWizardContext extends IActionContext { /** @@ -11,6 +12,7 @@ export interface CreateDatabaseWizardContext extends IActionContext { * This should be `cluster.clusterId` (NOT treeId). */ credentialsId: string; + readonly binding?: ConnectionBinding; clusterName: string; nodeId: string; diff --git a/src/commands/createDatabase/DatabaseNameStep.ts b/src/commands/createDatabase/DatabaseNameStep.ts index a68d27ce9..005eb7127 100644 --- a/src/commands/createDatabase/DatabaseNameStep.ts +++ b/src/commands/createDatabase/DatabaseNameStep.ts @@ -6,6 +6,8 @@ import { AzureWizardPromptStep } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { runBoundNamespaceCommand } from '../runBoundNamespaceCommand'; import { type CreateDatabaseWizardContext } from './CreateDatabaseWizardContext'; export class DatabaseNameStep extends AzureWizardPromptStep { @@ -67,8 +69,11 @@ export class DatabaseNameStep extends AzureWizardPromptStep + client.listDatabases(), + ) + : await (await ClustersClient.getClient(context.credentialsId)).listDatabases(); if ( databases.filter((c) => 0 === c.name.localeCompare(name, undefined, { sensitivity: 'accent' })).length > @@ -87,6 +92,9 @@ export class DatabaseNameStep extends AzureWizardPromptStep { @@ -17,7 +18,7 @@ export class ExecuteStep extends AzureWizardExecuteStep setTimeout(resolve, 250)); - await client.createDatabase(databaseName, collectionName); + if (context.binding) { + await runBoundNamespaceCommand(credentialsId, context.binding, (boundClient) => + boundClient.createDatabase(databaseName, collectionName), + ); + } else { + await client?.createDatabase(databaseName, collectionName); + } }, ); } diff --git a/src/commands/createDatabase/createDatabase.ts b/src/commands/createDatabase/createDatabase.ts index b89666487..fae540161 100644 --- a/src/commands/createDatabase/createDatabase.ts +++ b/src/commands/createDatabase/createDatabase.ts @@ -6,11 +6,13 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { AtlasExperience } from '../../DocumentDBExperiences'; +import { type ConnectionBinding } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { nonNullValue } from '../../utils/nonNull'; import { InitialCollectionNameStep } from '../createCollection/InitialCollectionNameStep'; +import { rethrowBoundCommandUnavailable } from '../rethrowBoundCommandUnavailable'; import { type CreateDatabaseWizardContext } from './CreateDatabaseWizardContext'; import { DatabaseNameStep } from './DatabaseNameStep'; import { ExecuteStep } from './ExecuteStep'; @@ -22,6 +24,7 @@ interface CreateDatabaseCommandOptions { * cannot say is a menu entry. */ readonly activationSource?: string; + readonly binding?: ConnectionBinding; readonly onNameResolved?: (databaseName: string) => Promise; } @@ -56,7 +59,7 @@ async function createMongoDatabase( context.telemetry.properties.activationSource = options?.activationSource ?? 'treeContextMenu'; context.telemetry.properties.viewId = node.cluster.viewId ?? 'unknown'; - if (!CredentialCache.hasCredentials(node.cluster.clusterId)) { + if (!options?.binding && !CredentialCache.hasCredentials(node.cluster.clusterId)) { context.telemetry.properties.failureReason = 'notSignedIn'; throw new Error( l10n.t( @@ -69,6 +72,7 @@ async function createMongoDatabase( const wizardContext: CreateDatabaseWizardContext = { ...context, credentialsId: node.cluster.clusterId, + binding: options?.binding, clusterName: node.cluster.name, nodeId: node.id, requiresInitialCollection: node.experience.api === AtlasExperience.api, @@ -81,10 +85,21 @@ async function createMongoDatabase( showLoadingPrompt: true, }); - await wizard.prompt(); - const newDatabaseName = nonNullValue(wizardContext.databaseName, 'wizardContext.databaseName', 'createDatabase.ts'); - await options?.onNameResolved?.(newDatabaseName); - await wizard.execute(); + try { + await wizard.prompt(); + const newDatabaseName = nonNullValue( + wizardContext.databaseName, + 'wizardContext.databaseName', + 'createDatabase.ts', + ); + await options?.onNameResolved?.(newDatabaseName); + await wizard.execute(); - showConfirmationAsInSettings(l10n.t('The "{name}" database has been created.', { name: newDatabaseName })); + showConfirmationAsInSettings(l10n.t('The "{name}" database has been created.', { name: newDatabaseName })); + } catch (error) { + if (options?.binding) { + rethrowBoundCommandUnavailable(context, error); + } + throw error; + } } diff --git a/src/commands/dashboardBoundCommands.test.ts b/src/commands/dashboardBoundCommands.test.ts new file mode 100644 index 000000000..c9db7f3b3 --- /dev/null +++ b/src/commands/dashboardBoundCommands.test.ts @@ -0,0 +1,251 @@ +/*--------------------------------------------------------------------------------------------- + * 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 AzExtInputBoxOptions, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { MongoNetworkError, MongoServerError } from 'mongodb'; +import { beforeEach, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { AuthMethodId } from '../documentdb/auth/AuthMethodId'; +import { ClustersClient, type ConnectionBinding } from '../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../documentdb/ConnectionUnavailableError'; +import { CredentialCache } from '../documentdb/CredentialCache'; +import { DocumentDBExperience } from '../DocumentDBExperiences'; +import { type ClusterItemBase } from '../tree/documentdb/ClusterItemBase'; +import { type CollectionItem } from '../tree/documentdb/CollectionItem'; +import { type DatabaseItem } from '../tree/documentdb/DatabaseItem'; +import { getConfirmationAsInSettings } from '../utils/dialogs/getConfirmation'; +import { createCollection } from './createCollection/createCollection'; +import { createDatabase } from './createDatabase/createDatabase'; +import { deleteCollection } from './deleteCollection/deleteCollection'; +import { deleteAzureDatabase } from './deleteDatabase/deleteDatabase'; +import { exportEntireCollection } from './exportDocuments/exportDocuments'; + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal()), + AzureWizard: class { + constructor( + private readonly context: IActionContext, + private readonly options: { + promptSteps: { prompt: (context: IActionContext) => Promise }[]; + executeSteps: { execute: (context: IActionContext) => Promise }[]; + }, + ) {} + + async prompt(): Promise { + await this.options.promptSteps[0].prompt(this.context); + } + + async execute(): Promise { + await this.options.executeSteps[0].execute(this.context); + } + }, +})); +vi.mock('../documentdb/ClustersClient', () => ({ + ClustersClient: { + getClient: vi.fn(), + getEpoch: vi.fn(() => 0), + resolveBoundClient: vi.fn(), + reportFailure: vi.fn(), + }, +})); +vi.mock('../documentdb/CredentialCache', () => ({ + CredentialCache: { getCredentials: vi.fn(), hasCredentials: vi.fn(() => true) }, +})); +vi.mock('../extensionVariables', () => ({ + ext: { + outputChannel: { error: vi.fn() }, + state: { + showDeleting: async (_id: string, callback: () => Promise) => callback(), + showCreatingChild: async (_id: string, _message: string, callback: () => Promise) => callback(), + notifyChildrenChanged: vi.fn(), + }, + }, +})); +vi.mock('../services/taskService/resourceUsageHelper', () => ({ checkCanProceedAndInformUser: vi.fn(() => true) })); +vi.mock('../utils/dialogs/getConfirmation', () => ({ getConfirmationAsInSettings: vi.fn() })); +vi.mock('../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../utils/workspacUtils', () => ({ getRootPath: vi.fn() })); + +const binding: ConnectionBinding = { clusterId: 'cluster', fingerprint: 'original', generation: 1 }; +const cluster = { clusterId: 'cluster', name: 'Cluster', viewId: 'connectionsView' }; +const clusterNode = { id: 'cluster', experience: DocumentDBExperience, cluster } as ClusterItemBase; +const database = { + id: 'cluster/database', + experience: DocumentDBExperience, + cluster, + databaseInfo: { name: 'database' }, +} as DatabaseItem; +const collection = { + ...database, + id: 'cluster/database/collection', + collectionInfo: { name: 'collection' }, +} as CollectionItem; +const replacement = { + dropDatabase: vi.fn(), + dropCollection: vi.fn(), + streamDocumentsWithQuery: vi.fn(), + listDatabases: vi.fn(), + listCollections: vi.fn(), + createDatabase: vi.fn(), + createCollection: vi.fn(), +}; + +function createContext(showInputBox = vi.fn()): IActionContext { + return { + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + valuesToMask: [], + ui: { showInputBox }, + } as unknown as IActionContext; +} + +function changeIdentity(): void { + vi.mocked(ClustersClient.resolveBoundClient).mockRejectedValue(new ConnectionUnavailableError('identityChanged')); +} + +beforeEach(() => { + vi.resetAllMocks(); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(0); + vi.mocked(ClustersClient.getClient).mockResolvedValue(replacement as unknown as ClustersClient); +}); + +it.each([ + ['database', (context: IActionContext) => deleteAzureDatabase(context, database, undefined, { binding })], + ['collection', (context: IActionContext) => deleteCollection(context, collection, undefined, { binding })], +] as const)('does not drop a %s after the connection identity changes during confirmation', async (_name, drop) => { + vi.mocked(getConfirmationAsInSettings).mockImplementationOnce(async () => { + changeIdentity(); + return true; + }); + const context = createContext(); + + await expect(drop(context)).rejects.toMatchObject({ reason: 'identityChanged' }); + + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledExactlyOnceWith(binding, { trigger: 'clusterDashboard' }); + expect(context.errorHandling).toMatchObject({ rethrow: true, suppressDisplay: true }); + expect(ClustersClient.getClient).not.toHaveBeenCalled(); + expect(replacement.dropDatabase).not.toHaveBeenCalled(); + expect(replacement.dropCollection).not.toHaveBeenCalled(); +}); + +it('reports a rejected Dashboard drop on the client that ran it without retrying', async (): Promise => { + const failure = new MongoServerError({ code: 18, errmsg: 'Authentication failed' }); + const client = { binding: { ...binding, generation: 2 }, dropCollection: vi.fn().mockRejectedValue(failure) }; + vi.mocked(getConfirmationAsInSettings).mockResolvedValueOnce(true); + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValueOnce(client as unknown as ClustersClient); + vi.mocked(ClustersClient.reportFailure).mockReturnValueOnce('credentialsRejected'); + + await expect(deleteCollection(createContext(), collection, undefined, { binding })).rejects.toMatchObject({ + reason: 'credentialsRejected', + }); + expect(ClustersClient.reportFailure).toHaveBeenCalledExactlyOnceWith(client.binding, failure); + expect(client.dropCollection).toHaveBeenCalledOnce(); +}); + +it.each([ + ['database', (context: IActionContext) => deleteAzureDatabase(context, database, undefined, { binding })], + ['collection', (context: IActionContext) => deleteCollection(context, collection, undefined, { binding })], +] as const)('cancels a confirmed %s deletion after same-identity reconnect', async (_name, drop) => { + vi.mocked(getConfirmationAsInSettings).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + return true; + }); + + await expect(drop(createContext())).rejects.toBeInstanceOf(UserCancelledError); + expect(ClustersClient.resolveBoundClient).not.toHaveBeenCalled(); +}); + +it('does not export with a different connection after the save dialog', async () => { + vi.mocked(vscode.window.showSaveDialog).mockImplementationOnce(async () => { + changeIdentity(); + return vscode.Uri.file('/fixture/export.json'); + }); + const context = createContext(); + + await expect(exportEntireCollection(context, collection, undefined, { binding })).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledExactlyOnceWith(binding, undefined); + expect(context.errorHandling).toMatchObject({ rethrow: true, suppressDisplay: true }); + expect(ClustersClient.getClient).not.toHaveBeenCalled(); + expect(replacement.streamDocumentsWithQuery).not.toHaveBeenCalled(); +}); + +it('reports a rejected export startup as unavailable', async () => { + vi.mocked(CredentialCache.getCredentials).mockReturnValueOnce({ + clusterId: binding.clusterId, + authMechanism: AuthMethodId.NativeAuth, + connectionString: 'mongodb://localhost/', + connectionStringWithPassword: 'mongodb://localhost/', + }); + vi.mocked(vscode.window.showSaveDialog).mockResolvedValue(vscode.Uri.file('/fixture/export.json')); + vi.mocked(ClustersClient.resolveBoundClient).mockRejectedValue( + new MongoServerError({ code: 18, errmsg: 'Authentication failed' }), + ); + + await expect(exportEntireCollection(createContext(), collection, undefined, { binding })).rejects.toMatchObject({ + reason: 'credentialsRejected', + }); + expect(replacement.streamDocumentsWithQuery).not.toHaveBeenCalled(); +}); + +it.each([ + ['database', (context: IActionContext) => createDatabase(context, clusterNode, undefined, { binding })], + ['collection', (context: IActionContext) => createCollection(context, database, undefined, { binding })], +] as const)( + 'surfaces unavailable, not a %s name error, when the bound validation read fails', + async (_name, create) => { + const listNames = vi.fn(async () => { + throw new MongoNetworkError('fixture connection lost'); + }); + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValue({ + binding, + listDatabases: listNames, + listCollections: listNames, + } as unknown as ClustersClient); + const context = createContext( + vi.fn(async ({ asyncValidationTask }: AzExtInputBoxOptions) => { + try { + await asyncValidationTask?.('newName'); + } catch (error) { + // The Azure input box wraps the error and closes instead of showing a validation message. + throw new Error('fixture validation failure', { cause: error }); + } + return 'newName'; + }), + ); + + await expect(create(context)).rejects.toMatchObject({ reason: 'unreachable' }); + + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledExactlyOnceWith(binding, { + trigger: 'clusterDashboard', + }); + expect(listNames).toHaveBeenCalledOnce(); + expect(context.errorHandling).toMatchObject({ rethrow: true, suppressDisplay: true }); + expect(ClustersClient.getClient).not.toHaveBeenCalled(); + }, +); + +it('resolves the original binding again immediately before creating a collection', async () => { + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValueOnce({ + binding, + listCollections: vi.fn(async () => []), + } as unknown as ClustersClient); + const context = createContext( + vi.fn(async ({ asyncValidationTask }: AzExtInputBoxOptions) => { + expect(await asyncValidationTask?.('newName')).toBeUndefined(); + return 'newName'; + }), + ); + + await expect( + createCollection(context, database, undefined, { binding, onNameResolved: async () => changeIdentity() }), + ).rejects.toMatchObject({ reason: 'identityChanged' }); + + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledTimes(2); + expect(ClustersClient.getClient).not.toHaveBeenCalled(); + expect(replacement.createCollection).not.toHaveBeenCalled(); +}); diff --git a/src/commands/deleteCollection/deleteCollection.ts b/src/commands/deleteCollection/deleteCollection.ts index 8fa4c90f4..2f08fe634 100644 --- a/src/commands/deleteCollection/deleteCollection.ts +++ b/src/commands/deleteCollection/deleteCollection.ts @@ -5,20 +5,28 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; -import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; import { SchemaStore } from '../../documentdb/SchemaStore'; import { ext } from '../../extensionVariables'; import { checkCanProceedAndInformUser } from '../../services/taskService/resourceUsageHelper'; import { type CollectionItem } from '../../tree/documentdb/CollectionItem'; import { getConfirmationAsInSettings } from '../../utils/dialogs/getConfirmation'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; +import { rethrowBoundCommandUnavailable } from '../rethrowBoundCommandUnavailable'; +import { runBoundNamespaceCommand } from '../runBoundNamespaceCommand'; -export async function deleteCollection(context: IActionContext, node: CollectionItem): Promise { +export async function deleteCollection( + context: IActionContext, + node: CollectionItem, + _nodes?: CollectionItem[], + options?: { readonly binding?: ConnectionBinding }, +): Promise { if (!node) { throw new Error(l10n.t('No node selected.')); } context.telemetry.properties.experience = node.experience.api; + const confirmationEpoch = options?.binding ? ClustersClient.getEpoch(node.cluster.clusterId) : undefined; // Check if any running tasks are using this collection const canProceed = await checkCanProceedAndInformUser( @@ -53,11 +61,21 @@ export async function deleteCollection(context: IActionContext, node: Collection } try { - const client = await ClustersClient.getClient(node.cluster.clusterId); + const { clusterId } = node.cluster; + const drop = (client: ClustersClient): Promise => + client.dropCollection(node.databaseInfo.name, node.collectionInfo.name); + const binding = options?.binding; + let runDrop: () => Promise; + if (binding) { + runDrop = () => runBoundNamespaceCommand(clusterId, binding, drop, confirmationEpoch); + } else { + const client = await ClustersClient.getClient(clusterId); + runDrop = () => drop(client); + } let success = false; await ext.state.showDeleting(node.id, async () => { - success = await client.dropCollection(node.databaseInfo.name, node.collectionInfo.name); + success = await runDrop(); }); if (success) { @@ -68,6 +86,11 @@ export async function deleteCollection(context: IActionContext, node: Collection ); showConfirmationAsInSettings(successMessage); } + } catch (error) { + if (options?.binding) { + rethrowBoundCommandUnavailable(context, error); + } + throw error; } finally { const lastSlashIndex = node.id.lastIndexOf('/'); let parentId = node.id; diff --git a/src/commands/deleteDatabase/deleteDatabase.ts b/src/commands/deleteDatabase/deleteDatabase.ts index be392733a..8de2da144 100644 --- a/src/commands/deleteDatabase/deleteDatabase.ts +++ b/src/commands/deleteDatabase/deleteDatabase.ts @@ -5,24 +5,40 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; -import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; import { SchemaStore } from '../../documentdb/SchemaStore'; import { ext } from '../../extensionVariables'; import { checkCanProceedAndInformUser } from '../../services/taskService/resourceUsageHelper'; import { type DatabaseItem } from '../../tree/documentdb/DatabaseItem'; import { getConfirmationAsInSettings } from '../../utils/dialogs/getConfirmation'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; +import { rethrowBoundCommandUnavailable } from '../rethrowBoundCommandUnavailable'; +import { runBoundNamespaceCommand } from '../runBoundNamespaceCommand'; -export async function deleteAzureDatabase(context: IActionContext, node: DatabaseItem): Promise { +interface DeleteDatabaseCommandOptions { + readonly binding?: ConnectionBinding; +} + +export async function deleteAzureDatabase( + context: IActionContext, + node: DatabaseItem, + _nodes?: DatabaseItem[], + options?: DeleteDatabaseCommandOptions, +): Promise { if (!node) { throw new Error(l10n.t('No node selected.')); } - return deleteDatabase(context, node); + return deleteDatabase(context, node, options); } -export async function deleteDatabase(context: IActionContext, node: DatabaseItem): Promise { +export async function deleteDatabase( + context: IActionContext, + node: DatabaseItem, + options?: DeleteDatabaseCommandOptions, +): Promise { context.telemetry.properties.experience = node.experience.api; + const confirmationEpoch = options?.binding ? ClustersClient.getEpoch(node.cluster.clusterId) : undefined; // Check if any running tasks are using this database const canProceed = await checkCanProceedAndInformUser( @@ -52,17 +68,31 @@ export async function deleteDatabase(context: IActionContext, node: DatabaseItem } try { - const client = await ClustersClient.getClient(node.cluster.clusterId); + const { clusterId } = node.cluster; + const drop = (client: ClustersClient): Promise => client.dropDatabase(databaseId); + const binding = options?.binding; + let runDrop: () => Promise; + if (binding) { + runDrop = () => runBoundNamespaceCommand(clusterId, binding, drop, confirmationEpoch); + } else { + const client = await ClustersClient.getClient(clusterId); + runDrop = () => drop(client); + } let success = false; await ext.state.showDeleting(node.id, async () => { - success = await client.dropDatabase(node.databaseInfo.name); + success = await runDrop(); }); if (success) { SchemaStore.getInstance().clearDatabase(node.cluster.clusterId, node.databaseInfo.name); showConfirmationAsInSettings(l10n.t('The "{databaseId}" database has been deleted.', { databaseId })); } + } catch (error) { + if (options?.binding) { + rethrowBoundCommandUnavailable(context, error); + } + throw error; } finally { const lastSlashIndex = node.id.lastIndexOf('/'); let parentId = node.id; diff --git a/src/commands/exportDocuments/exportDocuments.ts b/src/commands/exportDocuments/exportDocuments.ts index 0f2fd7bb2..53b48dd6b 100644 --- a/src/commands/exportDocuments/exportDocuments.ts +++ b/src/commands/exportDocuments/exportDocuments.ts @@ -7,22 +7,36 @@ import { callWithTelemetryAndErrorHandling, type IActionContext, parseError } fr import * as l10n from '@vscode/l10n'; import { EJSON } from 'bson'; import * as vscode from 'vscode'; -import { ClustersClient, type FindQueryParams } from '../../documentdb/ClustersClient'; +import { type ConnectionBinding, type FindQueryParams } from '../../documentdb/ClustersClient'; +import { resolveTransferClient } from '../../documentdb/resolveTransferClient'; import { ext } from '../../extensionVariables'; import { type CollectionItem } from '../../tree/documentdb/CollectionItem'; import { appendToFile } from '../../utils/fs/appendToFile'; import { getRootPath } from '../../utils/workspacUtils'; +import { rethrowBoundCommandUnavailable } from '../rethrowBoundCommandUnavailable'; -export async function exportEntireCollection(context: IActionContext, node?: CollectionItem) { +export async function exportEntireCollection( + context: IActionContext, + node?: CollectionItem, + _nodes?: CollectionItem[], + options?: { readonly source?: string; readonly binding?: ConnectionBinding }, +): Promise { context.telemetry.properties.experience = node?.experience.api; - return exportQueryResults(context, node); + try { + await exportQueryResults(context, node, options); + } catch (error) { + if (options?.binding) { + rethrowBoundCommandUnavailable(context, error); + } + throw error; + } } export async function exportQueryResults( context: IActionContext, node?: CollectionItem, - props?: { queryText?: string; queryParams?: FindQueryParams; source?: string }, + props?: { queryText?: string; queryParams?: FindQueryParams; source?: string; binding?: ConnectionBinding }, ): Promise { context.telemetry.properties.experience = node?.experience.api; @@ -39,7 +53,7 @@ export async function exportQueryResults( return; } - const client = await ClustersClient.getClient(node.cluster.clusterId); + const client = await resolveTransferClient(node.cluster.clusterId, props?.binding); const docStreamAbortController = new AbortController(); diff --git a/src/commands/importDocuments/importDocuments.test.ts b/src/commands/importDocuments/importDocuments.test.ts new file mode 100644 index 000000000..a8bcf8124 --- /dev/null +++ b/src/commands/importDocuments/importDocuments.test.ts @@ -0,0 +1,101 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { readFile } from 'node:fs/promises'; +import { 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 { ext } from '../../extensionVariables'; +import { CollectionItem } from '../../tree/documentdb/CollectionItem'; +import { importDocuments } from './importDocuments'; + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { getClient: vi.fn(), resolveBoundClient: vi.fn(), reportFailure: vi.fn() }, + isBulkWriteError: vi.fn(() => false), +})); +vi.mock('node:fs/promises', () => ({ + readFile: vi.fn(async () => '[{"name":"new document"}]'), +})); +vi.mock('../../extensionVariables', () => ({ + ext: { + outputChannel: { info: vi.fn(), trace: vi.fn(), warn: vi.fn(), error: vi.fn(), show: vi.fn() }, + state: { + runWithTemporaryDescription: async (_id: string, _description: string, task: () => Promise) => task(), + notifyChildrenChanged: vi.fn(), + }, + }, +})); +vi.mock('../../utils/workspacUtils', () => ({ getRootPath: vi.fn() })); + +const binding: ConnectionBinding = { clusterId: 'cluster', fingerprint: 'original', generation: 1 }; + +function createSource(): CollectionItem { + return new CollectionItem( + { + clusterId: 'cluster', + treeId: 'folder/cluster', + viewId: 'connectionsView', + name: 'Cluster', + dbExperience: DocumentDBExperience, + }, + { name: 'database' }, + { name: 'collection' }, + ); +} + +function prepareImport(showOpenDialog: () => Promise): IActionContext { + vi.mocked(vscode.window.withProgress).mockImplementationOnce((_options, task) => + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ); + return { + ui: { showOpenDialog }, + telemetry: { properties: {}, measurements: {} }, + errorHandling: { issueProperties: {} }, + valuesToMask: [], + } as unknown as IActionContext; +} + +it('does not import using a different identity selected while the file picker was open', async (): Promise => { + const insertDocuments = vi.fn(); + const replacement = { insertDocuments, getConnectionString: () => 'mongodb://example.test' }; + vi.mocked(ClustersClient.getClient).mockResolvedValue(replacement as unknown as ClustersClient); + const showOpenDialog = vi.fn(async () => { + vi.mocked(ClustersClient.resolveBoundClient).mockRejectedValueOnce( + new ConnectionUnavailableError('identityChanged'), + ); + return [vscode.Uri.file('/fixture/documents.json')]; + }); + await expect( + importDocuments(prepareImport(showOpenDialog), createSource(), undefined, { binding }), + ).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(showOpenDialog).toHaveBeenCalledOnce(); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledExactlyOnceWith(binding, undefined); + expect(ClustersClient.getClient).not.toHaveBeenCalled(); + expect(insertDocuments).not.toHaveBeenCalled(); +}); + +it('stops a bound import after rejection and reports only confirmed inserts', async (): Promise => { + const failure = new Error('Rejected fixture credentials'); + const insertDocuments = vi.fn().mockResolvedValueOnce({ insertedCount: 1 }).mockRejectedValueOnce(failure); + const client = { + binding: { ...binding, generation: 2 }, + insertDocuments, + getConnectionString: () => 'mongodb://fixture.mongo.cosmos.azure.com', + }; + vi.mocked(readFile).mockResolvedValueOnce('[{"n":1},{"n":2},{"n":3},{"n":4}]'); + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValueOnce(client as unknown as ClustersClient); + vi.mocked(ClustersClient.reportFailure).mockReturnValueOnce('credentialsRejected'); + const context = prepareImport(async () => [vscode.Uri.file('/fixture/documents.json')]); + + await expect(importDocuments(context, createSource(), undefined, { binding })).rejects.toMatchObject({ + reason: 'credentialsRejected', + }); + expect(insertDocuments).toHaveBeenCalledTimes(2); + expect(ClustersClient.reportFailure).toHaveBeenCalledExactlyOnceWith(client.binding, failure); + expect(ext.outputChannel.warn).toHaveBeenCalledWith('Inserted 1 document(s).'); +}); diff --git a/src/commands/importDocuments/importDocuments.ts b/src/commands/importDocuments/importDocuments.ts index 82b323216..c389047ed 100644 --- a/src/commands/importDocuments/importDocuments.ts +++ b/src/commands/importDocuments/importDocuments.ts @@ -8,7 +8,9 @@ import * as l10n from '@vscode/l10n'; import { EJSON, type Document } from 'bson'; import * as fs from 'node:fs/promises'; import * as vscode from 'vscode'; -import { ClustersClient, isBulkWriteError } from '../../documentdb/ClustersClient'; +import { ClustersClient, isBulkWriteError, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { resolveTransferClient } from '../../documentdb/resolveTransferClient'; import { AzureDomains, getHostsFromConnectionString, @@ -18,11 +20,13 @@ import { ext } from '../../extensionVariables'; import { CollectionItem } from '../../tree/documentdb/CollectionItem'; import { BufferErrorCode, createMongoDbBuffer, type DocumentBuffer } from '../../utils/documentBuffer'; import { getRootPath } from '../../utils/workspacUtils'; +import { rethrowBoundCommandUnavailable } from '../rethrowBoundCommandUnavailable'; export async function importDocuments( context: IActionContext, selectedItem: vscode.Uri | CollectionItem | undefined, uris: vscode.Uri[] | undefined, + options?: { readonly binding?: ConnectionBinding; readonly source?: string }, ): Promise { if (selectedItem instanceof vscode.Uri) { uris ||= [selectedItem]; @@ -75,8 +79,13 @@ export async function importDocuments( try { await ext.state.runWithTemporaryDescription(selectedItem.id, l10n.t('Importing…'), async () => { - await importDocumentsWithProgress(selectedItem, uris); + await importDocumentsWithProgress(selectedItem, uris, options?.binding); }); + } catch (error) { + if (options?.binding && options.source === 'webview;clusterDashboard') { + rethrowBoundCommandUnavailable(context, error); + } + throw error; } finally { // Always refresh at the database level (parent of the collection) so collection // descriptions (document counts) update correctly, even after partial failures @@ -85,7 +94,11 @@ export async function importDocuments( } } -export async function importDocumentsWithProgress(selectedItem: CollectionItem, uris: vscode.Uri[]): Promise { +export async function importDocumentsWithProgress( + selectedItem: CollectionItem, + uris: vscode.Uri[], + binding?: ConnectionBinding, +): Promise { const result = await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, @@ -145,11 +158,16 @@ export async function importDocumentsWithProgress(selectedItem: CollectionItem, 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 ClustersClient.getClient(selectedItem.cluster.clusterId); + 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 @@ -171,6 +189,16 @@ export async function importDocumentsWithProgress(selectedItem: CollectionItem, } let wasCancelled = false; + const insertBatch = async (document: unknown): Promise<{ count: number; errorOccurred: boolean }> => { + try { + return await insertDocument(selectedItem, document, buffer, boundClient); + } catch (error) { + if (error instanceof ConnectionUnavailableError) { + ext.outputChannel.warn(l10n.t('Inserted {0} document(s).', count)); + } + throw error; + } + }; for (let i = 0; i < countDocuments; i++) { if (cancellationToken.isCancellationRequested) { @@ -187,7 +215,7 @@ export async function importDocumentsWithProgress(selectedItem: CollectionItem, }), }); - const result = await insertDocument(selectedItem, documents[i], buffer); + const result = await insertBatch(documents[i]); // 'count' in result means that the result is from the buffer count += result.count; @@ -197,7 +225,7 @@ export async function importDocumentsWithProgress(selectedItem: CollectionItem, // Do insertion for the last batch for bulk insertion if (!wasCancelled && buffer && buffer.getStats().documentCount > 0) { - const lastBatchFlushResult = await insertDocument(selectedItem, undefined, buffer); + const lastBatchFlushResult = await insertBatch(undefined); count += lastBatchFlushResult.count; hasErrors = hasErrors || lastBatchFlushResult.errorOccurred; @@ -313,6 +341,7 @@ async function insertDocument( node: CollectionItem, document: unknown, buffer: DocumentBuffer | undefined, + boundClient?: ClustersClient, ): Promise<{ count: number; errorOccurred: boolean }> { try { // Check for valid buffer @@ -323,13 +352,16 @@ async function insertDocument( // Route to appropriate handler based on node type if (node instanceof CollectionItem) { - return await insertDocumentWithBufferIntoCluster(node, buffer, document as Document); + return await insertDocumentWithBufferIntoCluster(node, buffer, boundClient, document as Document); } // Should only reach here if node is neither CollectionItem nor CosmosDBContainerResourceItem ext.outputChannel.error(l10n.t('Import failed: unsupported node type.')); return { count: 0, errorOccurred: true }; } catch (error) { + if (boundClient && error instanceof ConnectionUnavailableError) { + throw error; + } const errorMessage = error instanceof Error ? error.message : String(error); ext.outputChannel.error(l10n.t('Import failed with unexpected error: {0}', errorMessage)); return { count: 0, errorOccurred: true }; @@ -339,6 +371,7 @@ async function insertDocument( async function insertDocumentWithBufferIntoCluster( node: CollectionItem, buffer: DocumentBuffer, + boundClient?: ClustersClient, document?: Document, // If document is undefined, it means that we are flushing the buffer // It is used for the last batch, and not recommended to be used for normal batches @@ -364,7 +397,7 @@ async function insertDocumentWithBufferIntoCluster( // Documents to process could be the current document (if too large) // or the contents of the buffer (if it was full) - const client = await ClustersClient.getClient(node.cluster.clusterId); + const client = boundClient ?? (await ClustersClient.getClient(node.cluster.clusterId)); try { const insertResult = await client.insertDocuments( databaseName, @@ -377,6 +410,19 @@ async function insertDocumentWithBufferIntoCluster( errorOccurred: false, }; } catch (error) { + if (boundClient) { + const kind = ClustersClient.reportFailure(boundClient.binding, error); + switch (kind) { + case 'signInRequired': + case 'credentialsRejected': + case 'credentialsMissing': + case 'identityChanged': + throw new ConnectionUnavailableError(kind); + case 'clientClosed': + case 'transient': + throw new ConnectionUnavailableError('unreachable'); + } + } if (isBulkWriteError(error)) { // Handle MongoDB bulk write errors // It could be a partial failure, so we need to check the result diff --git a/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts b/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts index cdaf10e8c..5b8b23a52 100644 --- a/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts +++ b/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts @@ -7,13 +7,14 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext import * as l10n from '@vscode/l10n'; import { type Document, type Filter } from 'mongodb'; import * as vscode from 'vscode'; -import { type IndexItemModel } from '../../documentdb/ClustersClient'; +import { type ClustersClient, type IndexItemModel } from '../../documentdb/ClustersClient'; import { ClusterSession } from '../../documentdb/ClusterSession'; import { type CollectionStats, type IndexStats } from '../../documentdb/LlmEnhancedFeatureApis'; import { type ClusterMetadata } from '../../documentdb/utils/getClusterMetadata'; import { ext } from '../../extensionVariables'; import { CopilotService, type CopilotTokenUsage } from '../../services/copilotService'; import { PromptTemplateService } from '../../services/promptTemplateService'; +import { throwIfBoundViewUnavailable } from '../../webviews/documentdb/boundViewOperations'; import { getLastPromptSource, type FilledPromptResult } from './promptTemplates'; /** @@ -469,6 +470,13 @@ async function prepareOptimizationRequest( throw new UserCancelledError('AbortSignal'); } + // TODO: allow null sessionId for testing framework + if (!queryContext.sessionId) { + throw new Error(l10n.t('sessionId is required for query optimization')); + } + const session = ClusterSession.getSession(queryContext.sessionId); + const epoch = session.getEpoch(); + // Check if Copilot is available const copilotAvailable = await CopilotService.isAvailable(); if (!copilotAvailable) { @@ -479,16 +487,22 @@ async function prepareOptimizationRequest( ); } + return session.runWithClient(async (client) => { + const prepared = await prepareBoundOptimizationRequest(context, queryContext, client); + session.assertCurrent(epoch, queryContext.signal); + return prepared; + }, epoch); +} + +async function prepareBoundOptimizationRequest( + context: IActionContext, + queryContext: QueryOptimizationContext, + client: ClustersClient, +): Promise { let explainResult: unknown; let collectionStats: CollectionStats | undefined; let indexes: IndexStats[] | undefined; - // TODO: allow null sessionId for testing framework - if (!queryContext.sessionId) { - throw new Error(l10n.t('sessionId is required for query optimization')); - } - const session = ClusterSession.getSession(queryContext.sessionId); - const client = session.getClient(); const clusterInfo = await client.getClusterMetadata(); // Track cluster information in telemetry @@ -589,6 +603,7 @@ async function prepareOptimizationRequest( l10n.t('Failed to gather query optimization data: {message}', { message: error instanceof Error ? error.message : String(error), }), + { cause: error }, ); } } @@ -674,6 +689,7 @@ async function prepareOptimizationRequest( if (error instanceof UserCancelledError) { throw error; } + throwIfBoundViewUnavailable(client.binding, error); // They are not critical errors, we can continue without index stats and collection stats // If the API calls failed, collectionStats and indexes remain undefined (safe to continue) diff --git a/src/commands/openClusterDashboard/openClusterDashboard.ts b/src/commands/openClusterDashboard/openClusterDashboard.ts index 65422b076..983aa07b5 100644 --- a/src/commands/openClusterDashboard/openClusterDashboard.ts +++ b/src/commands/openClusterDashboard/openClusterDashboard.ts @@ -113,18 +113,20 @@ export async function openClusterDashboard( // run the same authentication the tree runs. Cached credentials make this a no-op. context.telemetry.properties.wasSignedIn = String(CredentialCache.hasCredentials(node.cluster.clusterId)); + let client: ClustersClient; if (node instanceof DatabaseItem) { // Database nodes are only rendered after their cluster connected, so reuse that client. - await ClustersClient.getClient(node.cluster.clusterId, undefined, undefined, 'clusterDashboard'); + client = await ClustersClient.getClient(node.cluster.clusterId, undefined, undefined, 'clusterDashboard'); } else { - const client = await node.connect(); - if (!client) { + const connectedClient = await node.connect(); + if (!connectedClient) { // `connect()` has already surfaced the reason, or the user cancelled the prompt. context.telemetry.properties.connectionResult = 'failed'; const canceled = node.lastConnectionOutcome === 'canceled'; context.telemetry.properties.result = canceled ? 'Canceled' : 'Failed'; return { opened: false, canceled }; } + client = connectedClient; } // Extract viewId from the cluster model, or infer from treeId prefix @@ -153,6 +155,7 @@ export async function openClusterDashboard( ? context.telemetry.properties.journeyCorrelationId : undefined, }, + client.binding, options?.deepLink, ); diff --git a/src/commands/openDocument/openDocument.ts b/src/commands/openDocument/openDocument.ts index 7465801d6..5583abb48 100644 --- a/src/commands/openDocument/openDocument.ts +++ b/src/commands/openDocument/openDocument.ts @@ -5,10 +5,11 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; import { Views } from '../../documentdb/Views'; import { openDocumentWebview } from '../../webviews/documentdb/documentView/documentsViewController'; -export function openDocumentView( +export async function openDocumentView( _context: IActionContext, props: { id: string; @@ -26,18 +27,27 @@ export function openDocumentView( mode: string; }, -): void { - const view = openDocumentWebview({ - id: props.id, - - clusterId: props.clusterId, - viewId: props.viewId ?? Views.ConnectionsView, // fallback for backward compatibility - databaseName: props.databaseName, - collectionName: props.collectionName, - documentId: props.documentId, - - mode: props.mode, - }); + sourceBinding?: ConnectionBinding, +): Promise { + const binding = + sourceBinding ?? + ClustersClient.getBinding(props.clusterId) ?? + (await ClustersClient.getClient(props.clusterId, undefined, undefined, 'documentView')).binding; + + const view = openDocumentWebview( + { + id: props.id, + + clusterId: props.clusterId, + viewId: props.viewId ?? Views.ConnectionsView, // fallback for backward compatibility + databaseName: props.databaseName, + collectionName: props.collectionName, + documentId: props.documentId, + + mode: props.mode, + }, + binding, + ); view.revealToForeground(vscode.ViewColumn.Active); } diff --git a/src/commands/rethrowBoundCommandUnavailable.ts b/src/commands/rethrowBoundCommandUnavailable.ts new file mode 100644 index 000000000..5616ebff9 --- /dev/null +++ b/src/commands/rethrowBoundCommandUnavailable.ts @@ -0,0 +1,20 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { ConnectionUnavailableError } from '../documentdb/ConnectionUnavailableError'; + +export function rethrowBoundCommandUnavailable(context: IActionContext, error: unknown): never { + // AzureWizard's async input validation wraps the failure in Error with the original cause. + const cause: unknown = error instanceof Error ? error.cause : undefined; + const unavailable = error instanceof ConnectionUnavailableError ? error : cause; + if (unavailable instanceof ConnectionUnavailableError) { + context.errorHandling.suppressDisplay = true; + context.errorHandling.rethrow = true; + throw unavailable; + } + + throw error; +} diff --git a/src/commands/runBoundNamespaceCommand.ts b/src/commands/runBoundNamespaceCommand.ts new file mode 100644 index 000000000..6737c9d8e --- /dev/null +++ b/src/commands/runBoundNamespaceCommand.ts @@ -0,0 +1,49 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { ClustersClient, type ConnectionBinding } from '../documentdb/ClustersClient'; +import { classifyConnectionFailure } from '../documentdb/connectionFailures'; +import { ConnectionUnavailableError } from '../documentdb/ConnectionUnavailableError'; +import { runWithClient } from '../documentdb/runWithClient'; + +export async function runBoundNamespaceCommand( + clusterId: string, + binding: ConnectionBinding, + operation: (client: ClustersClient) => Promise, + confirmationEpoch?: number, +): Promise { + if (clusterId !== binding.clusterId) { + throw new ConnectionUnavailableError('identityChanged'); + } + + const assertConfirmationCurrent = (): void => { + if (confirmationEpoch !== undefined && ClustersClient.getEpoch(clusterId) !== confirmationEpoch) { + throw new UserCancelledError('staleDeleteConfirmation'); + } + }; + assertConfirmationCurrent(); + + try { + const result = await runWithClient( + binding, + async (client) => { + assertConfirmationCurrent(); + return { value: await operation(client) }; + }, + { trigger: 'clusterDashboard' }, + ); + if ('unavailable' in result) { + throw new ConnectionUnavailableError(result.unavailable.reason); + } + return result.value; + } catch (error) { + const { kind } = classifyConnectionFailure(error); + if (kind === 'transient' || kind === 'clientClosed') { + throw new ConnectionUnavailableError('unreachable', { cause: error }); + } + throw error; + } +} diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index 2a7ed1ed9..0e1da1664 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type FieldEntry } from '@documentdb-js/schema-analyzer'; +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import { ParseMode, parse as parseShellBSON } from '@mongodb-js/shell-bson-parser'; import * as l10n from '@vscode/l10n'; import { EJSON } from 'bson'; @@ -12,7 +13,9 @@ import { ext } from '../extensionVariables'; 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 FindQueryParams } from './ClustersClient'; +import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; +import { runWithClient } from './runWithClient'; import { SchemaStore } from './SchemaStore'; import { fixupDocumentDbExplain } from './utils/fixupDocumentDbExplain'; import { parseDocumentId } from './utils/parseDocumentId'; @@ -70,15 +73,66 @@ export class ClusterSession { * Private constructor to enforce the use of `initNewSession` for creating new sessions. * This ensures that sessions are properly initialized and managed. */ - private constructor( - private _client: ClustersClient, - private readonly _clusterId: string, - ) { - return; + private constructor(private readonly binding: ConnectionBinding) {} + + public getBinding(): ConnectionBinding { + return this.binding; + } + + public async getClient(): Promise { + return ClustersClient.resolveBoundClient(this.binding, { trigger: 'collectionView' }); + } + + public getEpoch(): number { + return ClustersClient.getEpoch(this.binding.clusterId); } - public getClient(): ClustersClient { - return this._client; + private isCurrent(epoch: number): boolean { + const { clusterId, fingerprint } = this.binding; + return ( + epoch === ClustersClient.getEpoch(clusterId) && + ClustersClient.getLatchReason(clusterId) === undefined && + ClustersClient.getBinding(clusterId)?.fingerprint === fingerprint + ); + } + + public assertCurrent(epoch: number, signal?: AbortSignal): void { + if (signal?.aborted || !this.isCurrent(epoch)) { + throw new UserCancelledError('staleCollectionViewOperation'); + } + } + + public assertAvailable(signal?: AbortSignal): void { + if (signal?.aborted) { + throw new UserCancelledError('staleCollectionViewOperation'); + } + const reason = ClustersClient.getLatchReason(this.binding.clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + const current = ClustersClient.getBinding(this.binding.clusterId); + if (current?.fingerprint !== this.binding.fingerprint) { + throw new ConnectionUnavailableError(current ? 'identityChanged' : 'unreachable'); + } + } + + // Keep the existing procedure return types until the routers map unavailable results. + public async runWithClient( + operation: (client: ClustersClient, epoch: number) => Promise, + epoch = this.getEpoch(), + ): Promise { + const result = await runWithClient( + this.binding, + async (client) => { + this.assertCurrent(epoch); + return { value: await operation(client, epoch) }; + }, + { trigger: 'collectionView' }, + ); + if ('unavailable' in result) { + throw new ConnectionUnavailableError(result.unavailable.reason); + } + return result.value; } /** @@ -114,7 +168,6 @@ export class ClusterSession { /** * Query Insights caching - * Note: QueryInsightsApis instance is accessed via this._client.queryInsightsApis * * Timestamps are included for potential future features: * - Time-based cache invalidation (e.g., expire after N seconds) @@ -248,6 +301,7 @@ export class ClusterSession { pageNumber: number, pageSize: number, executionIntent: 'initial' | 'refresh' | 'pagination' = 'pagination', + signal?: AbortSignal, ): Promise { const querySkip = queryParams.skip ?? 0; const queryLimit = queryParams.limit ?? 0; @@ -261,9 +315,11 @@ export class ClusterSession { // Early return if trying to skip beyond the query limit // Note: queryLimit=0 means no limit, so only check when queryLimit > 0 if (queryLimit > 0 && pageOffset >= queryLimit) { - // We're trying to page beyond the query's limit - return empty results - this._currentRawDocuments = []; - return 0; + return this.runWithClient((_client, epoch) => { + this.assertCurrent(epoch, signal); + this._currentRawDocuments = []; + return Promise.resolve(0); + }); } // Calculate effective limit: @@ -275,18 +331,6 @@ export class ClusterSession { dbLimit = Math.min(pageSize, remainingInWindow); } - // Check if the user's query has changed (not pagination, just the actual query) - this.resetCachesIfUserQueryChanged(queryParams); - - // Check if page size has changed (invalidates accumulation strategy) - this.resetAccumulationIfPageSizeChanged(pageSize); - - // Force clear query insights caches for initial/refresh operations - // This ensures fresh performance data when user explicitly requests it - if (executionIntent === 'initial' || executionIntent === 'refresh') { - this.clearQueryInsightsCaches(); - } - // Build final query parameters with computed skip/limit const paginatedQueryParams: FindQueryParams = { ...queryParams, @@ -294,14 +338,21 @@ export class ClusterSession { limit: dbLimit, }; - // Track execution time for query insights - const startTime = performance.now(); - const documents: WithId[] = await this._client.runFindQuery( - databaseName, - collectionName, - paginatedQueryParams, - ); - this._lastExecutionTimeMs = performance.now() - startTime; + const epoch = this.getEpoch(); + const { documents, executionTimeMs } = await this.runWithClient(async (client) => { + this.assertCurrent(epoch, signal); + const startTime = performance.now(); + const documents = await client.runFindQuery(databaseName, collectionName, paginatedQueryParams); + return { documents, executionTimeMs: performance.now() - startTime }; + }, epoch); + + this.assertCurrent(epoch, signal); + this.resetCachesIfUserQueryChanged(queryParams); + this.resetAccumulationIfPageSizeChanged(pageSize); + if (executionIntent === 'initial' || executionIntent === 'refresh') { + this.clearQueryInsightsCaches(); + } + this._lastExecutionTimeMs = executionTimeMs; // Update current page documents (always replace, not accumulate) this._currentRawDocuments = documents; @@ -313,10 +364,11 @@ export class ClusterSession { // Feed documents to the shared SchemaStore if (documents.length > 0) { const store = SchemaStore.getInstance(); - store.addDocuments(this._clusterId, databaseName, collectionName, documents); + const { clusterId } = this.binding; + store.addDocuments(clusterId, databaseName, collectionName, documents); ext.outputChannel.trace( - `[SchemaStore] Fed ${String(documents.length)} documents, ${String(store.getDocumentCount(this._clusterId, databaseName, collectionName))} total, ${String(store.getKnownFields(this._clusterId, databaseName, collectionName).length)} known fields`, + `[SchemaStore] Fed ${String(documents.length)} documents, ${String(store.getDocumentCount(clusterId, databaseName, collectionName))} total, ${String(store.getKnownFields(clusterId, databaseName, collectionName).length)} known fields`, ); } @@ -331,10 +383,19 @@ export class ClusterSession { return toSlickGridTree(this._currentRawDocuments); } - async deleteDocuments(databaseName: string, collectionName: string, documentIds: string[]): Promise { - const acknowledged = await this._client.deleteDocuments(databaseName, collectionName, documentIds); + public async deleteDocuments( + databaseName: string, + collectionName: string, + documentIds: string[], + epoch = this.getEpoch(), + ): Promise { + const acknowledged = await this.runWithClient( + (client) => client.deleteDocuments(databaseName, collectionName, documentIds), + epoch, + ); - if (acknowledged) { + // Acknowledge a completed write, but don't update the page from an old operation. + if (acknowledged && this.isCurrent(epoch)) { this._currentRawDocuments = this._currentRawDocuments.filter((doc) => { return !documentIds.some((id) => { const parsedId = parseDocumentId(id); @@ -356,7 +417,12 @@ export class ClusterSession { path: path, headers: this._databaseName && this._collectionName - ? store.getPropertyNamesAtLevel(this._clusterId, this._databaseName, this._collectionName, path) + ? store.getPropertyNamesAtLevel( + this.binding.clusterId, + this._databaseName, + this._collectionName, + path, + ) : [], data: getDataAtPath(this._currentRawDocuments, path), }; @@ -372,7 +438,11 @@ export class ClusterSession { if (!this._databaseName || !this._collectionName) { return []; } - return SchemaStore.getInstance().getKnownFields(this._clusterId, this._databaseName, this._collectionName); + return SchemaStore.getInstance().getKnownFields( + this.binding.clusterId, + this._databaseName, + this._collectionName, + ); } // ============================================================================ @@ -393,6 +463,8 @@ export class ClusterSession { * @returns Explain output from queryPlanner verbosity */ public async getQueryPlannerInfo( + client: ClustersClient, + epoch: number, databaseName: string, collectionName: string, filter: Document, @@ -402,14 +474,16 @@ export class ClusterSession { skip?: number; limit?: number; }, + signal?: AbortSignal, ): Promise { + this.assertCurrent(epoch, signal); // Check cache if (this._queryPlannerCache) { return this._queryPlannerCache.result; } // Execute explain("queryPlanner") using QueryInsightsApis from ClustersClient - const rawResult = await this._client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { + const rawResult = await client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { verbosity: 'queryPlanner', sort: options?.sort, projection: options?.projection, @@ -418,10 +492,11 @@ export class ClusterSession { }); // Apply Azure DocumentDB explain fixup (see fixupDocumentDbExplain for details) - const clusterMetadata = await this._client.getClusterMetadata(); + const clusterMetadata = await client.getClusterMetadata(); const explainResult = fixupDocumentDbExplain(rawResult, clusterMetadata) ?? rawResult; // Cache result + this.assertCurrent(epoch, signal); this._queryPlannerCache = { result: explainResult, timestamp: Date.now(), @@ -447,6 +522,8 @@ export class ClusterSession { * @returns Explain output with executionStats */ public async getExecutionStats( + client: ClustersClient, + epoch: number, databaseName: string, collectionName: string, filter: Document, @@ -456,7 +533,9 @@ export class ClusterSession { skip?: number; limit?: number; }, + signal?: AbortSignal, ): Promise { + this.assertCurrent(epoch, signal); // Check cache if (this._executionStatsCache) { return this._executionStatsCache.result; @@ -464,7 +543,7 @@ export class ClusterSession { // Determine verbosity based on cluster type // Azure DocumentDB clusters support allPlansExecution for richer plan data - const clusterMetadata = await this._client.getClusterMetadata(); + const clusterMetadata = await client.getClusterMetadata(); const verbosity = clusterMetadata.domainInfo_isAzure === 'true' && clusterMetadata.domainInfo_api === 'vCore' ? 'allPlansExecution' @@ -472,7 +551,8 @@ export class ClusterSession { // Execute explain using QueryInsightsApis from ClustersClient // This re-runs the query to get authoritative execution metrics - const rawResult = await this._client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { + this.assertCurrent(epoch, signal); + const rawResult = await client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { verbosity, sort: options?.sort, projection: options?.projection, @@ -484,6 +564,7 @@ export class ClusterSession { const explainResult = fixupDocumentDbExplain(rawResult, clusterMetadata) ?? rawResult; // Cache result + this.assertCurrent(epoch, signal); this._executionStatsCache = { result: explainResult, timestamp: Date.now(), @@ -606,7 +687,13 @@ export class ClusterSession { * Caches the transformed Stage 2 response and total collection docs * for use by Stage 3 when building the static analysis summary. */ - public setStage2Response(response: QueryInsightsStage2Response, totalCollectionDocs?: number): void { + public setStage2Response( + epoch: number, + response: QueryInsightsStage2Response, + totalCollectionDocs?: number, + signal?: AbortSignal, + ): void { + this.assertCurrent(epoch, signal); this._stage2ResponseCache = { response, totalCollectionDocs }; } @@ -635,7 +722,7 @@ export class ClusterSession { * * @remarks * This method will be implemented in Phase 3. The AI service is accessed via - * this._client.queryInsightsAIService (similar to queryInsightsApis pattern). + * the resolved client's Query Insights service. */ public getAIRecommendations( _databaseName: string, @@ -649,7 +736,7 @@ export class ClusterSession { } // TODO: Phase 3 implementation - // const recommendations = await this._client.queryInsightsAIService.generateRecommendations( + // const recommendations = await client.queryInsightsAIService.generateRecommendations( // databaseName, // collectionName, // filter, @@ -692,7 +779,7 @@ export class ClusterSession { const sessionId = Math.random().toString(16).substring(2, 15) + Math.random().toString(36).substring(2, 15); - const session = new ClusterSession(client, clusterId); + const session = new ClusterSession(client.binding); ClusterSession._sessions.set(sessionId, session); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 3fe3353a3..e02da895e 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -35,10 +35,12 @@ import { getIndexExclusionReason, type IndexItemModel, } from './ClustersClient'; +import { ClusterSession } from './ClusterSession'; import { computeConnectionFingerprint } from './connectionFingerprint'; import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { CredentialCache } from './CredentialCache'; import { runWithClient } from './runWithClient'; +import { SchemaStore } from './SchemaStore'; import { prepareDriverConnectionString } from './srv/prepareDriverConnectionString'; import { type SrvResolutionSummary } from './srv/srvResolutionSummary'; import { getClusterMetadata, getDomainMetadata } from './utils/getClusterMetadata'; @@ -130,7 +132,11 @@ vi.mock('./utils/getClusterMetadata', () => ({ })); vi.mock('./LlmEnhancedFeatureApis', () => ({ llmEnhancedFeatureApis: vi.fn() })); -vi.mock('./client/QueryInsightsApis', () => ({ QueryInsightsApis: vi.fn() })); +vi.mock('./client/QueryInsightsApis', () => ({ + QueryInsightsApis: vi.fn(function () { + return { explainFind: vi.fn() }; + }), +})); vi.mock('./srv/prepareDriverConnectionString', () => ({ prepareDriverConnectionString: vi.fn() })); vi.mock('./auth/createAuthHandler', async () => { const actual = await vi.importActual('./auth/createAuthHandler'); @@ -160,6 +166,9 @@ describe('regular connection startup diagnostics', () => { const mockConnect = vi.fn(); const mockClose = vi.fn(); const mockListDatabases = vi.fn<() => Promise>(); + const mockFind = vi.fn(); + const mockToArray = vi.fn<() => Promise[]>>(); + const mockDeleteMany = vi.fn<() => Promise>(); let poolEvents: EventEmitter; function pauseNextConnect(): { started: Promise; resolve: () => void; reject: (error: Error) => void } { @@ -193,12 +202,18 @@ describe('regular connection startup diagnostics', () => { }); mockClose.mockResolvedValue(undefined); mockListDatabases.mockReset(); + mockFind.mockReset().mockReturnValue({ toArray: mockToArray }); + mockToArray.mockReset(); + mockDeleteMany.mockReset(); vi.mocked(MongoClient).mockImplementation(function () { poolEvents = new EventEmitter(); return Object.assign(poolEvents, { connect: mockConnect, close: mockClose, - db: () => ({ admin: () => ({ listDatabases: mockListDatabases }) }), + db: () => ({ + admin: () => ({ listDatabases: mockListDatabases }), + collection: () => ({ find: mockFind, deleteMany: mockDeleteMany }), + }), }) as unknown as MongoClient; }); for (const handler of [ @@ -271,6 +286,146 @@ describe('regular connection startup diagnostics', () => { expect(mockClose).not.toHaveBeenCalled(); }); + it('lets a surface follow a same-identity generation but does not redial while latched', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + const replacement = await ClustersClient.resolveBoundClient(client.binding); + expect(replacement.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + expect(mockConnect).toHaveBeenCalledTimes(2); + + ClustersClient.latch(clusterId, 'userDisconnected'); + try { + await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ + reason: 'userDisconnected', + }); + expect(mockConnect).toHaveBeenCalledTimes(2); + } finally { + ClustersClient.unlatch(clusterId); + } + }); + + it('does not open a changed connection for an old surface, even with no cached client', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://different.test/'); + + await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(MongoClient).toHaveBeenCalledOnce(); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + + const current = await ClustersClient.getClient(clusterId); + await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(ClustersClient.getBinding(clusterId)).toBe(current.binding); + }); + + 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)); + const query = { filter: '{}', skip: 2, limit: 3 }; + mockToArray.mockResolvedValueOnce([{ _id: 'first', previousField: true }]); + await session.runFindQueryWithCache('db', 'items', query, 1, 2); + + ClustersClient.reportFailure(original.binding, new MongoNotConnectedError('idle connection closed')); + const replacement = await session.getClient(); + expect(replacement.generation).toBe(original.generation + 1); + expect(replacement.fingerprint).toBe(original.fingerprint); + const runFind = vi.spyOn(replacement, 'runFindQuery'); + + mockToArray.mockResolvedValueOnce([{ _id: 'last', nextField: true }]); + await expect(session.runFindQueryWithCache('db', 'items', query, 2, 2)).resolves.toBe(1); + expect(runFind).toHaveBeenCalledExactlyOnceWith('db', 'items', { ...query, skip: 4, limit: 1 }); + expect(session.getCurrentPageAsJson().map((page) => JSON.parse(page) as unknown)).toEqual([ + { _id: 'last', nextField: true }, + ]); + expect(SchemaStore.getInstance().getDocumentCount(clusterId, 'db', 'items')).toBe(2); + await expect(session.runFindQueryWithCache('db', 'items', query, 3, 2)).resolves.toBe(0); + expect(session.getCurrentPageAsJson()).toEqual([]); + expect(runFind).toHaveBeenCalledOnce(); + }); + + it('rejects a changed identity before a session can submit a write', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + await ClustersClient.deleteClient(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://different.test/'); + await ClustersClient.getClient(clusterId); + + await expect(session.getClient()).rejects.toMatchObject({ reason: 'identityChanged' }); + await expect(session.deleteDocuments('db', 'items', ['"one"'])).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(mockDeleteMany).not.toHaveBeenCalled(); + }); + + it('drops a find completed after reconnect without changing the query, page, or schema', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + const query = { filter: '{}' }; + mockToArray.mockResolvedValueOnce([{ _id: 'current' }]); + await session.runFindQueryWithCache('db', 'items', query, 1, 10); + const page = session.getCurrentPageAsJson(); + + const started = deferred(); + const finish = deferred(); + mockToArray.mockImplementationOnce(async () => { + started.resolve(); + await finish.promise; + return [{ _id: 'stale', staleField: true }]; + }); + const pending = session.runFindQueryWithCache('db', 'items', { filter: '{ staleField: true }' }, 1, 10); + await started.promise; + ClustersClient.latch(clusterId, 'userDisconnected'); + await ClustersClient.deleteClient(clusterId); + ClustersClient.unlatch(clusterId); + await session.getClient(); + finish.resolve(); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(session.getCurrentFindQueryParams()).toEqual(query); + expect(session.getCurrentPageAsJson()).toEqual(page); + expect(SchemaStore.getInstance().getDocumentCount(clusterId, 'db', 'items')).toBe(0); + }); + + it('does not cache execution stats that complete while the session is latched', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + const started = deferred(); + const finish = deferred(); + vi.spyOn(client.queryInsightsApis, 'explainFind').mockImplementationOnce(async () => { + started.resolve(); + await finish.promise; + return { executionStats: { nReturned: 1 } }; + }); + const pending = session.runWithClient((resolved, epoch) => + session.getExecutionStats(resolved, epoch, 'db', 'items', {}), + ); + await started.promise; + ClustersClient.latch(clusterId, 'userDisconnected'); + finish.resolve(); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(session.getRawExplainOutput('db', 'items')).toBeNull(); + }); + + it('does not replay a failed delete or remove the cached document', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + mockToArray.mockResolvedValueOnce([{ _id: 'one' }]); + await session.runFindQueryWithCache('db', 'items', {}, 1, 10); + const page = session.getCurrentPageAsJson(); + const failure = new MongoNotConnectedError('connection closed during delete'); + mockDeleteMany.mockRejectedValueOnce(failure); + + await expect(session.deleteDocuments('db', 'items', ['"one"'])).rejects.toBe(failure); + expect(mockDeleteMany).toHaveBeenCalledExactlyOnceWith({ _id: { $in: ['one'] } }); + expect(session.getCurrentPageAsJson()).toEqual(page); + expect(mockConnect).toHaveBeenCalledOnce(); + }); + it('reports only the expiry of the last Entra token supplied to the driver', async (): Promise => { const firstExpiry = 1_800_000_000; const renewedExpiry = firstExpiry + 3600; @@ -676,29 +831,41 @@ describe('regular connection startup diagnostics', () => { it('uses the resolved binding, preserves nonterminal errors and returns terminal unavailability without replay', async () => { const old = await ClustersClient.connectInteractive(clusterId); poolEvents.emit('topologyClosed'); - const client = await ClustersClient.getClient(clusterId); - const resolveClient = vi.fn(async (): Promise => client); const network = Object.freeze(new MongoNetworkError('tunnel refused')); const op = vi.fn<() => Promise>().mockRejectedValueOnce(network); - resolveClient.mockRejectedValueOnce(new ConnectionUnavailableError('unreachable')); - await expect(runWithClient(old.binding, op, { resolveClient, background: true })).resolves.toEqual({ + await expect(runWithClient(old.binding, op, { background: true })).resolves.toEqual({ unavailable: { reason: 'unreachable' }, }); + expect(mockConnect).toHaveBeenCalledOnce(); expect(op).not.toHaveBeenCalled(); - await expect(runWithClient(old.binding, op, { resolveClient, background: true })).rejects.toBe(network); - expect(resolveClient).toHaveBeenLastCalledWith(old.binding, { background: true }); + const client = await ClustersClient.getClient(clusterId); + await expect(runWithClient(old.binding, op, { background: true })).rejects.toBe(network); expect(op).toHaveBeenCalledExactlyOnceWith(client); expect(await ClustersClient.getClient(clusterId)).toBe(client); op.mockRejectedValueOnce(new EntraIdentityMismatchError()); - await expect(runWithClient(old.binding, op, { resolveClient })).resolves.toEqual({ + await expect(runWithClient(old.binding, op)).resolves.toEqual({ unavailable: { reason: 'identityChanged' }, }); expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); expect(op).toHaveBeenCalledTimes(2); }); + it('reports a startup credential rejection without submitting the bound operation', async (): Promise => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://private-host:27017'); + const client = await ClustersClient.getClient(clusterId); + await ClustersClient.deleteClient(clusterId); + mockConnect.mockRejectedValueOnce(new MongoServerError({ code: 18 })); + const op = vi.fn<() => Promise>(); + + await expect(runWithClient(client.binding, op)).resolves.toEqual({ + unavailable: { reason: 'credentialsRejected' }, + }); + expect(mockConnect).toHaveBeenCalledTimes(2); + expect(op).not.toHaveBeenCalled(); + }); + it('binds Entra to the original cached URI and the verified identity, even if credentials change during startup', async () => { const originalUri = 'mongodb+srv://original.example.com/database?authSource=admin'; const driverUri = 'mongodb://localhost:27018/database'; @@ -979,6 +1146,8 @@ describe('regular connection startup diagnostics', () => { }); afterEach(() => { + ClusterSession._sessions.clear(); + SchemaStore.getInstance().clearCluster(clusterId); if (ClustersClient.getLatchReason(clusterId)) { ClustersClient.unlatch(clusterId); } diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index bba86d893..dd72e7759 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -838,6 +838,22 @@ export class ClustersClient { return ClustersClient.acquireClient(clusterId, abortSignal, onStartup, trigger, true, false); } + /** A surface can follow new generations, but never start or use a client for a different identity. */ + public static resolveBoundClient( + binding: ConnectionBinding, + options?: { readonly background?: boolean; readonly trigger?: ClientStartupTrigger }, + ): Promise { + return ClustersClient.acquireClient( + binding.clusterId, + undefined, + undefined, + options?.trigger ?? 'other', + false, + options?.background === true, + binding.fingerprint, + ); + } + /** Publish only after explicit sign-in and database startup succeed. The prior pin stays intact until then. */ public static async startAfterSignIn( clusterId: string, @@ -894,6 +910,7 @@ export class ClustersClient { trigger: ClientStartupTrigger, allowInteractive: boolean, background: boolean, + boundFingerprint?: string, ): Promise { for (let attempt = 0; ; attempt++) { const reason = ClustersClient.getLatchReason(clusterId); @@ -909,6 +926,9 @@ export class ClustersClient { const epoch = ClustersClient.getEpoch(clusterId); const cached = ClustersClient._clients.get(clusterId); + if (cached && boundFingerprint !== undefined && cached.fingerprint !== boundFingerprint) { + throw new ConnectionUnavailableError('identityChanged'); + } if (cached?._replacement === 'replaceOnRecovery') { throw new ConnectionUnavailableError('signInRequired'); } @@ -936,12 +956,15 @@ export class ClustersClient { trigger, allowInteractive, background, - cached?.fingerprint, + boundFingerprint ?? cached?.fingerprint, ); onStartup?.(id); try { const client = await waitForClient(promise, abortSignal, id); if (epoch === ClustersClient.getEpoch(clusterId) && client.canReuse()) { + if (boundFingerprint !== undefined && client.fingerprint !== boundFingerprint) { + throw new ConnectionUnavailableError('identityChanged'); + } return client; } } catch (error) { diff --git a/src/documentdb/connectionSurfaces.test.ts b/src/documentdb/connectionSurfaces.test.ts new file mode 100644 index 000000000..23957e479 --- /dev/null +++ b/src/documentdb/connectionSurfaces.test.ts @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { expect, it, vi } from 'vitest'; +import { getConnectionSurfaces, registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; + +it('keeps teardown scoped to the current registered surfaces for one cluster', (): void => { + const makeSurface = (clusterId: string, kind: ConnectionSurface['kind']): ConnectionSurface => ({ + clusterId, + kind, + disable: vi.fn(), + dispose: vi.fn(), + }); + const document = makeSurface('cluster-a', 'documentView'); + const dashboard = makeSurface('cluster-a', 'clusterDashboard'); + const otherCluster = makeSurface('cluster-b', 'collectionView'); + const registrations = [document, dashboard, otherCluster].map(registerConnectionSurface); + + try { + expect(getConnectionSurfaces('cluster-a')).toEqual([document, dashboard]); + registrations[0].dispose(); + expect(getConnectionSurfaces('cluster-a')).toEqual([dashboard]); + expect(getConnectionSurfaces('cluster-b')).toEqual([otherCluster]); + expect(document.dispose).not.toHaveBeenCalled(); + expect(document.disable).not.toHaveBeenCalled(); + } finally { + for (const registration of registrations) { + registration.dispose(); + } + } + + expect(getConnectionSurfaces('cluster-a')).toEqual([]); + expect(getConnectionSurfaces('cluster-b')).toEqual([]); +}); diff --git a/src/documentdb/connectionSurfaces.ts b/src/documentdb/connectionSurfaces.ts new file mode 100644 index 000000000..f48f199fd --- /dev/null +++ b/src/documentdb/connectionSurfaces.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type Disposable } from 'vscode'; +import { type ConnectionUnavailableReason } from './ConnectionUnavailableError'; + +export interface ConnectionSurface { + readonly clusterId: string; + readonly kind: 'collectionView' | 'documentView' | 'clusterDashboard'; + disable(reason: ConnectionUnavailableReason): void; + dispose(): void; + isDirty?(): boolean; +} + +const surfacesByCluster = new Map>(); + +export function registerConnectionSurface(surface: ConnectionSurface): Disposable { + const { clusterId } = surface; + let surfaces = surfacesByCluster.get(clusterId); + if (!surfaces) { + surfaces = new Set(); + surfacesByCluster.set(clusterId, surfaces); + } + + surfaces.add(surface); + return { + dispose(): void { + if (surfaces.delete(surface) && surfaces.size === 0) { + surfacesByCluster.delete(clusterId); + } + }, + }; +} + +export function getConnectionSurfaces(clusterId: string): readonly ConnectionSurface[] { + return [...(surfacesByCluster.get(clusterId) ?? [])]; +} diff --git a/src/documentdb/resolveTransferClient.ts b/src/documentdb/resolveTransferClient.ts new file mode 100644 index 000000000..18301fc09 --- /dev/null +++ b/src/documentdb/resolveTransferClient.ts @@ -0,0 +1,23 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ClustersClient, type ConnectionBinding } from './ClustersClient'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; +import { runWithClient } from './runWithClient'; + +export async function resolveTransferClient(clusterId: string, binding?: ConnectionBinding): Promise { + if (!binding) { + return ClustersClient.getClient(clusterId); + } + if (binding.clusterId !== clusterId) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + const result = await runWithClient(binding, async (client) => ({ client })); + if ('unavailable' in result) { + const { reason } = result.unavailable; + throw new ConnectionUnavailableError(reason === 'identityChanged' ? 'credentialsChanged' : reason); + } + return result.client; +} diff --git a/src/documentdb/runWithClient.ts b/src/documentdb/runWithClient.ts index 5bcf53a7b..30c370542 100644 --- a/src/documentdb/runWithClient.ts +++ b/src/documentdb/runWithClient.ts @@ -3,16 +3,16 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { AuthMethodId } from './auth/AuthMethodId'; import { ClustersClient, type ConnectionBinding } from './ClustersClient'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; +import { CredentialCache } from './CredentialCache'; +import { type ClientStartupTrigger } from './utils/startupFailureTelemetry'; -interface ResolveOptions { +interface RunOptions { readonly background?: boolean; -} - -interface RunOptions extends ResolveOptions { - resolveClient(binding: ConnectionBinding, options: ResolveOptions): Promise; + readonly trigger?: ClientStartupTrigger; } interface Unavailable { @@ -31,21 +31,22 @@ function unavailableFor(kind: ConnectionFailure['kind'] | undefined): Unavailabl } } -/** @internal The bound resolver and conversion to a surface response are supplied by WI-6. */ export async function runWithClient( binding: ConnectionBinding, op: (client: ClustersClient) => Promise, - { resolveClient, background }: RunOptions, + options?: RunOptions, ): Promise { + const credentials = CredentialCache.getCredentials(binding.clusterId); + const authMethod = credentials ? (credentials.authMechanism ?? AuthMethodId.NativeAuth) : undefined; let client: ClustersClient; try { - client = await resolveClient(binding, { background }); + client = await ClustersClient.resolveBoundClient(binding, options); } catch (error) { // No operation ran, so there is no client generation to report against. const unavailable = error instanceof ConnectionUnavailableError ? { unavailable: { reason: error.reason } } - : unavailableFor(classifyConnectionFailure(error).kind); + : unavailableFor(classifyConnectionFailure(error, authMethod).kind); if (unavailable) { return unavailable; } diff --git a/src/documentdb/utils/getClusterHealth.ts b/src/documentdb/utils/getClusterHealth.ts index 1ff637286..7e0b3856c 100644 --- a/src/documentdb/utils/getClusterHealth.ts +++ b/src/documentdb/utils/getClusterHealth.ts @@ -278,7 +278,10 @@ function toStringOrNull(value: unknown): string | null { * @returns A sample where unsupported/failed commands are reported through `errors` * rather than by throwing. */ -export async function sampleClusterHealth(client: MongoClient): Promise { +export async function sampleClusterHealth( + client: MongoClient, + onCommandError?: (error: unknown) => void, +): Promise { const sample: ClusterHealthSample = { pingLatencyMs: null, uptimeSeconds: null, @@ -301,6 +304,7 @@ export async function sampleClusterHealth(client: MongoClient): Promise void, ): Promise { const errors: string[] = []; const adminDb = client.db().admin(); @@ -363,6 +369,7 @@ export async function getStorageStats( result: { ok: true, response: listed }, }); } catch (error) { + onCommandError?.(error); diagnostics?.push({ database: 'admin', command: listDatabasesCommand, @@ -421,6 +428,7 @@ export async function getStorageStats( // replaced, but `null` (field absent) should fall back to storageSize. database.sizeOnDiskBytes ??= toNumberOrNull(stats.storageSize); } catch (error) { + onCommandError?.(error); diagnostics?.push({ database: name, command: dbStatsCommand, @@ -462,6 +470,7 @@ export async function getDatabaseCollections( client: MongoClient, databaseName: string, signal?: AbortSignal, + onCommandError?: (error: unknown) => void, ): Promise { const errors: string[] = []; const db = client.db(databaseName); @@ -470,6 +479,7 @@ export async function getDatabaseCollections( try { listed = await db.listCollections().toArray(); } catch (error) { + onCommandError?.(error); return { databaseName, collections: [], @@ -511,6 +521,7 @@ export async function getDatabaseCollections( collection.indexSizeBytes = toNumberOrNull(stats.totalIndexSize); collection.indexes = toNumberOrNull(stats.nindexes); } catch (error) { + onCommandError?.(error); errors.push(describeCommandFailure(`collStats:${name}`, error)); } diff --git a/src/services/ai/QueryInsightsAIService.ts b/src/services/ai/QueryInsightsAIService.ts index dbd19776d..3650f0599 100644 --- a/src/services/ai/QueryInsightsAIService.ts +++ b/src/services/ai/QueryInsightsAIService.ts @@ -9,7 +9,6 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; -import { type Document } from 'mongodb'; import { CommandType, optimizeQuery, @@ -18,6 +17,7 @@ import { type QueryOptimizationContext, } from '../../commands/llmEnhancedCommands/indexAdvisorCommands'; import { ClusterSession } from '../../documentdb/ClusterSession'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { type IndexSpecification } from '../../documentdb/LlmEnhancedFeatureApis'; import { ext } from '../../extensionVariables'; import { getConfirmationAsInSettings, getConfirmationWithClick } from '../../utils/dialogs/getConfirmation'; @@ -207,6 +207,7 @@ export class QueryInsightsAIService { signal?: AbortSignal, staticAnalysisSummary?: string, ): Promise { + let unavailable: ConnectionUnavailableError | undefined; const result = await callWithTelemetryAndErrorHandling( 'vscode-documentdb.queryInsights.getOptimizationRecommendationsStreaming', async (context: IActionContext): Promise => { @@ -235,7 +236,13 @@ export class QueryInsightsAIService { }; } - const streamHandle = await optimizeQueryStreaming(context, queryContext); + const streamHandle = await optimizeQueryStreaming(context, queryContext).catch((error: unknown) => { + if (error instanceof ConnectionUnavailableError) { + context.errorHandling.suppressDisplay = true; + unavailable = error; + } + throw error; + }); // Final parse + per-action counts happen once at completion time. // The dedicated Stage 3 completion event (plan §7 / WI-10) will @@ -264,6 +271,9 @@ export class QueryInsightsAIService { }, ); + if (unavailable) { + throw unavailable; + } if (!result) { if (signal?.aborted) { throw new UserCancelledError('AbortSignal'); @@ -375,6 +385,9 @@ export class QueryInsightsAIService { educationalContent: parsedJson.educationalContent, }; } catch (error) { + if (error instanceof ConnectionUnavailableError) { + throw error; + } const errorMessage = error instanceof Error ? error.message : String(error); throw new Error(l10n.t('Failed to parse AI optimization response. {error}', { error: errorMessage })); } @@ -395,31 +408,44 @@ export class QueryInsightsAIService { actionId: string, payload: unknown, ): Promise<{ success: boolean; message?: string }> { - return await callWithTelemetryAndErrorHandling( + let unavailable: ConnectionUnavailableError | undefined; + const result = await callWithTelemetryAndErrorHandling( 'vscode-documentdb.queryInsights.action', async (context: IActionContext) => { // Track which action was executed context.telemetry.properties.actionId = actionId; // Route to appropriate handler based on actionId - switch (actionId) { - case 'createIndex': - return this.handleCreateIndex(context, sessionId, payload); - case 'dropIndex': - return this.handleDropIndex(context, sessionId, payload); - case 'modifyIndex': - return this.handleModifyIndex(context, sessionId, payload); - case 'learnMore': - return this.handleLearnMore(payload); - default: - context.telemetry.properties.actionError = 'unknownAction'; - return { - success: false, - message: `Unknown action: ${actionId}`, - }; + try { + switch (actionId) { + case 'createIndex': + return await this.handleCreateIndex(context, sessionId, payload); + case 'dropIndex': + return await this.handleDropIndex(context, sessionId, payload); + case 'modifyIndex': + return await this.handleModifyIndex(context, sessionId, payload); + case 'learnMore': + return this.handleLearnMore(payload); + default: + context.telemetry.properties.actionError = 'unknownAction'; + return { + success: false, + message: `Unknown action: ${actionId}`, + }; + } + } catch (error) { + if (error instanceof ConnectionUnavailableError) { + context.errorHandling.suppressDisplay = true; + unavailable = error; + } + throw error; } }, - ).then((result) => result ?? { success: false, message: 'Unknown error' }); + ); + if (unavailable) { + throw unavailable; + } + return result ?? { success: false, message: 'Unknown error' }; } /** @@ -509,6 +535,9 @@ export class QueryInsightsAIService { }), ); + const session = ClusterSession.getSession(actualSessionId); + const epoch = session.getEpoch(); + // Ask for confirmation before creating the index const confirmed = await getConfirmationWithClick( l10n.t('Create index?'), @@ -529,10 +558,10 @@ export class QueryInsightsAIService { }; } - const session = ClusterSession.getSession(actualSessionId); - const client = session.getClient(); - - const result = await client.createIndex(payload.databaseName, payload.collectionName, payload.indexSpec); + const result = await session.runWithClient( + (client) => client.createIndex(payload.databaseName, payload.collectionName, payload.indexSpec), + epoch, + ); if (result.ok === 1) { // Provide positive feedback with additional context from result.note if available @@ -561,6 +590,9 @@ export class QueryInsightsAIService { }; } } catch (error) { + if (error instanceof ConnectionUnavailableError) { + throw error; + } const errorMessage = error instanceof Error ? error.message : String(error); context.telemetry.properties.actionError = 'createIndexException'; ext.outputChannel.error( @@ -630,6 +662,9 @@ export class QueryInsightsAIService { ), ); + const session = ClusterSession.getSession(actualSessionId); + const epoch = session.getEpoch(); + // Ask for confirmation before dropping the index (destructive action) const confirmed = await getConfirmationAsInSettings( l10n.t('Delete index?'), @@ -653,10 +688,10 @@ export class QueryInsightsAIService { }; } - const session = ClusterSession.getSession(actualSessionId); - const client = session.getClient(); - - const result = await client.dropIndex(payload.databaseName, payload.collectionName, payload.indexName); + const result = await session.runWithClient( + (client) => client.dropIndex(payload.databaseName, payload.collectionName, payload.indexName), + epoch, + ); if (result.ok === 1) { // Provide positive feedback with additional context from result.note if available @@ -685,6 +720,9 @@ export class QueryInsightsAIService { }; } } catch (error) { + if (error instanceof ConnectionUnavailableError) { + throw error; + } const errorMessage = error instanceof Error ? error.message : String(error); context.telemetry.properties.actionError = 'dropIndexException'; ext.outputChannel.error( @@ -774,6 +812,9 @@ export class QueryInsightsAIService { ), ); + const session = ClusterSession.getSession(actualSessionId); + const epoch = session.getEpoch(); + // Ask for confirmation before modifying the index const operationText = operation === 'hideIndex' ? l10n.t('hide') : l10n.t('unhide'); const confirmed = await getConfirmationWithClick( @@ -797,17 +838,13 @@ export class QueryInsightsAIService { }; } - const session = ClusterSession.getSession(actualSessionId); - const client = session.getClient(); - - // Execute the operation - let result: Document; - if (operation === 'hideIndex') { - result = await client.hideIndex(payload.databaseName, payload.collectionName, indexName); - } else { - // unhideIndex - result = await client.unhideIndex(payload.databaseName, payload.collectionName, indexName); - } + const result = await session.runWithClient( + (client) => + operation === 'hideIndex' + ? client.hideIndex(payload.databaseName, payload.collectionName, indexName) + : client.unhideIndex(payload.databaseName, payload.collectionName, indexName), + epoch, + ); if (result.ok === 1) { // Provide positive feedback with additional context from result.note if available @@ -842,6 +879,9 @@ export class QueryInsightsAIService { }; } } catch (error) { + if (error instanceof ConnectionUnavailableError) { + throw error; + } const errorMessage = error instanceof Error ? error.message : String(error); context.telemetry.properties.actionError = 'modifyIndexException'; ext.outputChannel.error( diff --git a/src/webviews/_integration/connectionUnavailable.ts b/src/webviews/_integration/connectionUnavailable.ts new file mode 100644 index 000000000..bae57d4f9 --- /dev/null +++ b/src/webviews/_integration/connectionUnavailable.ts @@ -0,0 +1,82 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type ConnectionUnavailableReason } from '../../documentdb/ConnectionUnavailableError'; + +export const connectionRecoveryActions = ['retry', 'close'] as const; +export type ConnectionRecoveryAction = (typeof connectionRecoveryActions)[number]; + +export const connectionUnavailableReasons = [ + 'signInRequired', + 'credentialsRejected', + 'credentialsMissing', + 'credentialsChanged', + 'identityChanged', + 'userDisconnected', + 'connectionRemoved', + 'unreachable', +] as const satisfies readonly ConnectionUnavailableReason[]; + +export interface ConnectionUnavailableDetails { + readonly reason: ConnectionUnavailableReason; + readonly title: string; + readonly detail: string; + readonly action: ConnectionRecoveryAction; +} + +export interface ConnectionUnavailableResponse { + readonly unavailable: ConnectionUnavailableDetails; +} + +export interface ConnectionRecoveryRequest { + readonly action: ConnectionRecoveryAction; +} + +export interface ConnectionRecoveryResponse { + readonly recovered: { + readonly text: string; + }; +} + +export interface ConnectionUnavailableMessage { + readonly type: + | 'documentView.connectionUnavailable' + | 'clusterDashboard.connectionUnavailable' + | 'collectionView.connectionUnavailable'; + readonly unavailable: ConnectionUnavailableDetails; +} + +function isConnectionUnavailableDetails(value: unknown): value is ConnectionUnavailableDetails { + if (typeof value !== 'object' || value === null) { + return false; + } + + const candidate = value as Partial; + return ( + connectionUnavailableReasons.some((reason) => reason === candidate.reason) && + typeof candidate.title === 'string' && + typeof candidate.detail === 'string' && + connectionRecoveryActions.some((action) => action === candidate.action) + ); +} + +export function isConnectionUnavailableResponse(value: unknown): value is ConnectionUnavailableResponse { + if (typeof value !== 'object' || value === null || !('unavailable' in value)) { + return false; + } + return isConnectionUnavailableDetails(value.unavailable); +} + +export function isConnectionUnavailableMessage(value: unknown): value is ConnectionUnavailableMessage { + return ( + typeof value === 'object' && + value !== null && + 'type' in value && + (value.type === 'documentView.connectionUnavailable' || + value.type === 'clusterDashboard.connectionUnavailable' || + value.type === 'collectionView.connectionUnavailable') && + isConnectionUnavailableResponse(value) + ); +} diff --git a/src/webviews/_integration/describeUnavailableConnection.test.ts b/src/webviews/_integration/describeUnavailableConnection.test.ts new file mode 100644 index 000000000..875b5b7ad --- /dev/null +++ b/src/webviews/_integration/describeUnavailableConnection.test.ts @@ -0,0 +1,23 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { expect, it } from 'vitest'; +import { describeUnavailableConnection } from './describeUnavailableConnection'; + +it.each(['signInRequired', 'credentialsRejected', 'credentialsMissing'] as const)( + 'directs credential repair to the tree before retrying %s', + (reason): void => { + const { unavailable } = describeUnavailableConnection(reason); + expect(unavailable).toMatchObject({ reason, action: 'retry' }); + expect(unavailable.detail).toContain('tree'); + }, +); + +it.each(['identityChanged', 'credentialsChanged', 'connectionRemoved'] as const)( + 'offers only Close view for %s', + (reason): void => { + expect(describeUnavailableConnection(reason).unavailable.action).toBe('close'); + }, +); diff --git a/src/webviews/_integration/describeUnavailableConnection.ts b/src/webviews/_integration/describeUnavailableConnection.ts new file mode 100644 index 000000000..2ce107c28 --- /dev/null +++ b/src/webviews/_integration/describeUnavailableConnection.ts @@ -0,0 +1,71 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as l10n from '@vscode/l10n'; +import { type ConnectionUnavailableReason } from '../../documentdb/ConnectionUnavailableError'; +import { type ConnectionUnavailableResponse } from './connectionUnavailable'; + +export function describeUnavailableConnection(reason: ConnectionUnavailableReason): ConnectionUnavailableResponse { + switch (reason) { + case 'signInRequired': + return { + unavailable: { + reason, + title: l10n.t('Sign-in required'), + detail: l10n.t('Sign in from the connection tree, then click Retry.'), + action: 'retry', + }, + }; + case 'credentialsRejected': + return { + unavailable: { + reason, + title: l10n.t('Authentication failed'), + detail: l10n.t('Repair the connection in the tree, then click Retry.'), + action: 'retry', + }, + }; + case 'credentialsMissing': + case 'userDisconnected': + return { + unavailable: { + reason, + title: l10n.t('Disconnected'), + detail: l10n.t('Connect from the connection tree, then click Retry.'), + action: 'retry', + }, + }; + case 'identityChanged': + case 'credentialsChanged': + return { + unavailable: { + reason, + title: l10n.t('Connection changed'), + detail: l10n.t( + 'This view is tied to the previous connection. Close it and reopen it from the tree.', + ), + action: 'close', + }, + }; + case 'connectionRemoved': + return { + unavailable: { + reason, + title: l10n.t('Connection removed'), + detail: l10n.t('This connection is no longer in the tree. Close this view.'), + action: 'close', + }, + }; + case 'unreachable': + return { + unavailable: { + reason, + title: l10n.t('Connection lost'), + detail: l10n.t('Check the network or server, then click Retry.'), + action: 'retry', + }, + }; + } +} diff --git a/src/webviews/components/DisconnectedOverlay.scss b/src/webviews/components/DisconnectedOverlay.scss new file mode 100644 index 000000000..187b9cf8e --- /dev/null +++ b/src/webviews/components/DisconnectedOverlay.scss @@ -0,0 +1,30 @@ +.disconnectedOverlayBackground { + display: contents; +} + +.disconnectedOverlay { + width: min(28rem, calc(100vw - 2rem)); + + .disconnectedOverlayTitle, + .disconnectedOverlayDetail { + text-align: center; + overflow-wrap: anywhere; + } + + .disconnectedOverlayDetail { + p { + margin: 0; + } + + p + p { + margin-top: 8px; + } + } + + .disconnectedOverlayActions { + flex-direction: row; + flex-wrap: wrap; + justify-content: center; + justify-self: stretch; + } +} diff --git a/src/webviews/components/DisconnectedOverlay.test.tsx b/src/webviews/components/DisconnectedOverlay.test.tsx new file mode 100644 index 000000000..7a62e54d8 --- /dev/null +++ b/src/webviews/components/DisconnectedOverlay.test.tsx @@ -0,0 +1,118 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// @vitest-environment jsdom + +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules +import { expect, it, vi } from 'vitest'; +import { type ConnectionUnavailableDetails } from '../_integration/connectionUnavailable'; +import { DisconnectedOverlay } from './DisconnectedOverlay'; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const confirm = vi.hoisted(() => vi.fn()); +vi.mock('../_integration/useTrpcClient', () => ({ + useTrpcClient: () => ({ common: { confirm: { mutate: confirm } } }), +})); + +it('dismisses without closing, and only closes a dirty view after confirmation', async (): Promise => { + const unavailable: ConnectionUnavailableDetails = { + reason: 'signInRequired', + title: 'Sign-in required', + detail: 'Sign in from the connection tree, then click Retry.', + action: 'retry', + }; + const onAction = vi.fn(); + const onDismiss = vi.fn(); + confirm.mockResolvedValueOnce({ confirmed: false }).mockResolvedValueOnce({ confirmed: true }); + const host = document.createElement('div'); + document.body.appendChild(host); + const root = createRoot(host); + try { + const render = async (failure?: ConnectionUnavailableDetails, recovering?: boolean): Promise => { + await act(async () => + root.render( + +